File: os.go

package info (click to toggle)
lazygit 0.50.0%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,808 kB
  • sloc: sh: 128; makefile: 76
file content (362 lines) | stat: -rw-r--r-- 9,145 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package oscommands

import (
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"

	"github.com/go-errors/errors"
	"github.com/samber/lo"

	"github.com/atotto/clipboard"
	"github.com/jesseduffield/kill"
	"github.com/jesseduffield/lazygit/pkg/common"
	"github.com/jesseduffield/lazygit/pkg/config"
	"github.com/jesseduffield/lazygit/pkg/utils"
)

// OSCommand holds all the os commands
type OSCommand struct {
	*common.Common
	Platform *Platform
	getenvFn func(string) string
	guiIO    *guiIO

	removeFileFn func(string) error

	Cmd *CmdObjBuilder

	tempDir string
}

// Platform stores the os state
type Platform struct {
	OS                          string
	Shell                       string
	ShellArg                    string
	PrefixForShellFunctionsFile string
	OpenCommand                 string
	OpenLinkCommand             string
}

// NewOSCommand os command runner
func NewOSCommand(common *common.Common, config config.AppConfigurer, platform *Platform, guiIO *guiIO) *OSCommand {
	c := &OSCommand{
		Common:       common,
		Platform:     platform,
		getenvFn:     os.Getenv,
		removeFileFn: os.RemoveAll,
		guiIO:        guiIO,
		tempDir:      config.GetTempDir(),
	}

	runner := &cmdObjRunner{log: common.Log, guiIO: guiIO}
	c.Cmd = &CmdObjBuilder{runner: runner, platform: platform}

	return c
}

func (c *OSCommand) LogCommand(cmdStr string, commandLine bool) {
	c.Log.WithField("command", cmdStr).Info("RunCommand")

	c.guiIO.logCommandFn(cmdStr, commandLine)
}

// FileType tells us if the file is a file, directory or other
func FileType(path string) string {
	fileInfo, err := os.Stat(path)
	if err != nil {
		return "other"
	}
	if fileInfo.IsDir() {
		return "directory"
	}
	return "file"
}

func (c *OSCommand) OpenFile(filename string) error {
	commandTemplate := c.UserConfig().OS.Open
	if commandTemplate == "" {
		// Legacy support
		commandTemplate = c.UserConfig().OS.OpenCommand
	}
	if commandTemplate == "" {
		commandTemplate = config.GetPlatformDefaultConfig().Open
	}
	templateValues := map[string]string{
		"filename": c.Quote(filename),
	}
	command := utils.ResolvePlaceholderString(commandTemplate, templateValues)
	return c.Cmd.NewShell(command, c.UserConfig().OS.ShellFunctionsFile).Run()
}

func (c *OSCommand) OpenLink(link string) error {
	commandTemplate := c.UserConfig().OS.OpenLink
	if commandTemplate == "" {
		// Legacy support
		commandTemplate = c.UserConfig().OS.OpenLinkCommand
	}
	if commandTemplate == "" {
		commandTemplate = config.GetPlatformDefaultConfig().OpenLink
	}
	templateValues := map[string]string{
		"link": c.Quote(link),
	}

	command := utils.ResolvePlaceholderString(commandTemplate, templateValues)
	return c.Cmd.NewShell(command, c.UserConfig().OS.ShellFunctionsFile).Run()
}

// Quote wraps a message in platform-specific quotation marks
func (c *OSCommand) Quote(message string) string {
	return c.Cmd.Quote(message)
}

// AppendLineToFile adds a new line in file
func (c *OSCommand) AppendLineToFile(filename, line string) error {
	msg := utils.ResolvePlaceholderString(
		c.Tr.Log.AppendingLineToFile,
		map[string]string{
			"line":     line,
			"filename": filename,
		},
	)
	c.LogCommand(msg, false)

	f, err := os.OpenFile(filename, os.O_APPEND|os.O_RDWR|os.O_CREATE, 0o600)
	if err != nil {
		return utils.WrapError(err)
	}
	defer f.Close()

	info, err := os.Stat(filename)
	if err != nil {
		return utils.WrapError(err)
	}

	if info.Size() > 0 {
		// read last char
		buf := make([]byte, 1)
		if _, err := f.ReadAt(buf, info.Size()-1); err != nil {
			return utils.WrapError(err)
		}

		// if the last byte of the file is not a newline, add it
		if []byte("\n")[0] != buf[0] {
			_, err = f.WriteString("\n")
		}
	}

	if err == nil {
		_, err = f.WriteString(line + "\n")
	}

	if err != nil {
		return utils.WrapError(err)
	}
	return nil
}

// CreateFileWithContent creates a file with the given content
func (c *OSCommand) CreateFileWithContent(path string, content string) error {
	msg := utils.ResolvePlaceholderString(
		c.Tr.Log.CreateFileWithContent,
		map[string]string{
			"path": path,
		},
	)
	c.LogCommand(msg, false)
	if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
		c.Log.Error(err)
		return err
	}

	if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
		c.Log.Error(err)
		return utils.WrapError(err)
	}

	return nil
}

// Remove removes a file or directory at the specified path
func (c *OSCommand) Remove(filename string) error {
	msg := utils.ResolvePlaceholderString(
		c.Tr.Log.Remove,
		map[string]string{
			"filename": filename,
		},
	)
	c.LogCommand(msg, false)
	err := os.RemoveAll(filename)
	return utils.WrapError(err)
}

// FileExists checks whether a file exists at the specified path
func (c *OSCommand) FileExists(path string) (bool, error) {
	if _, err := os.Stat(path); err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

// PipeCommands runs a heap of commands and pipes their inputs/outputs together like A | B | C
func (c *OSCommand) PipeCommands(cmdObjs ...ICmdObj) error {
	cmds := lo.Map(cmdObjs, func(cmdObj ICmdObj, _ int) *exec.Cmd {
		return cmdObj.GetCmd()
	})

	logCmdStr := strings.Join(
		lo.Map(cmdObjs, func(cmdObj ICmdObj, _ int) string {
			return cmdObj.ToString()
		}),
		" | ",
	)

	c.LogCommand(logCmdStr, true)

	for i := 0; i < len(cmds)-1; i++ {
		stdout, err := cmds[i].StdoutPipe()
		if err != nil {
			return err
		}

		cmds[i+1].Stdin = stdout
	}

	// keeping this here in case I adapt this code for some other purpose in the future
	// cmds[len(cmds)-1].Stdout = os.Stdout

	finalErrors := []string{}

	wg := sync.WaitGroup{}
	wg.Add(len(cmds))

	for _, cmd := range cmds {
		go utils.Safe(func() {
			stderr, err := cmd.StderrPipe()
			if err != nil {
				c.Log.Error(err)
			}

			if err := cmd.Start(); err != nil {
				c.Log.Error(err)
			}

			if b, err := io.ReadAll(stderr); err == nil {
				if len(b) > 0 {
					finalErrors = append(finalErrors, string(b))
				}
			}

			if err := cmd.Wait(); err != nil {
				c.Log.Error(err)
			}

			wg.Done()
		})
	}

	wg.Wait()

	if len(finalErrors) > 0 {
		return errors.New(strings.Join(finalErrors, "\n"))
	}
	return nil
}

// Kill kills a process. If the process has Setpgid == true, then we have anticipated that it might spawn its own child processes, so we've given it a process group ID (PGID) equal to its process id (PID) and given its child processes will inherit the PGID, we can kill that group, rather than killing the process itself.
func Kill(cmd *exec.Cmd) error {
	return kill.Kill(cmd)
}

// PrepareForChildren sets Setpgid to true on the cmd, so that when we run it as a subprocess, we can kill its group rather than the process itself. This is because some commands, like `docker-compose logs` spawn multiple children processes, and killing the parent process isn't sufficient for killing those child processes. We set the group id here, and then in subprocess.go we check if the group id is set and if so, we kill the whole group rather than just the one process.
func PrepareForChildren(cmd *exec.Cmd) {
	kill.PrepareForChildren(cmd)
}

func (c *OSCommand) CopyToClipboard(str string) error {
	escaped := strings.Replace(str, "\n", "\\n", -1)
	truncated := utils.TruncateWithEllipsis(escaped, 40)

	msg := utils.ResolvePlaceholderString(
		c.Tr.Log.CopyToClipboard,
		map[string]string{
			"str": truncated,
		},
	)
	c.LogCommand(msg, false)
	if c.UserConfig().OS.CopyToClipboardCmd != "" {
		cmdStr := utils.ResolvePlaceholderString(c.UserConfig().OS.CopyToClipboardCmd, map[string]string{
			"text": c.Cmd.Quote(str),
		})
		return c.Cmd.NewShell(cmdStr, c.UserConfig().OS.ShellFunctionsFile).Run()
	}

	return clipboard.WriteAll(str)
}

func (c *OSCommand) PasteFromClipboard() (string, error) {
	var s string
	var err error
	if c.UserConfig().OS.CopyToClipboardCmd != "" {
		cmdStr := c.UserConfig().OS.ReadFromClipboardCmd
		s, err = c.Cmd.NewShell(cmdStr, c.UserConfig().OS.ShellFunctionsFile).RunWithOutput()
	} else {
		s, err = clipboard.ReadAll()
	}

	if err != nil {
		return "", err
	}

	return strings.ReplaceAll(s, "\r\n", "\n"), nil
}

func (c *OSCommand) RemoveFile(path string) error {
	msg := utils.ResolvePlaceholderString(
		c.Tr.Log.RemoveFile,
		map[string]string{
			"path": path,
		},
	)
	c.LogCommand(msg, false)

	return c.removeFileFn(path)
}

func (c *OSCommand) Getenv(key string) string {
	return c.getenvFn(key)
}

func (c *OSCommand) GetTempDir() string {
	return c.tempDir
}

// GetLazygitPath returns the path of the currently executed file
func GetLazygitPath() string {
	ex, err := os.Executable() // get the executable path for git to use
	if err != nil {
		ex = os.Args[0] // fallback to the first call argument if needed
	}
	return `"` + filepath.ToSlash(ex) + `"`
}

func (c *OSCommand) UpdateWindowTitle() error {
	if c.Platform.OS != "windows" {
		return nil
	}
	path, getWdErr := os.Getwd()
	if getWdErr != nil {
		return getWdErr
	}
	argString := fmt.Sprint("title ", filepath.Base(path), " - Lazygit")
	return c.Cmd.NewShell(argString, c.UserConfig().OS.ShellFunctionsFile).Run()
}