summaryrefslogtreecommitdiffstats
path: root/pkg/commands/files.go
blob: 9e17e60e04a21fb517e5f90f2ad438eeb50adbce (plain)
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
package commands

import (
	"io/ioutil"
	"strconv"

	"github.com/go-errors/errors"
	"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
	"github.com/jesseduffield/lazygit/pkg/common"
	"github.com/jesseduffield/lazygit/pkg/utils"
)

type FileCommands struct {
	*common.Common

	cmd    oscommands.ICmdObjBuilder
	config *ConfigCommands
	os     FileOSCommand
}

type FileOSCommand interface {
	Getenv(string) string
}

func NewFileCommands(
	common *common.Common,
	cmd oscommands.ICmdObjBuilder,
	config *ConfigCommands,
	osCommand FileOSCommand,
) *FileCommands {
	return &FileCommands{
		Common: common,
		cmd:    cmd,
		config: config,
		os:     osCommand,
	}
}

// Cat obtains the content of a file
func (self *FileCommands) Cat(fileName string) (string, error) {
	buf, err := ioutil.ReadFile(fileName)
	if err != nil {
		return "", nil
	}
	return string(buf), nil
}

func (c *FileCommands) GetEditCmdStr(filename string, lineNumber int) (string, error) {
	editor := c.UserConfig.OS.EditCommand

	if editor == "" {
		editor = c.config.GetCoreEditor()
	}

	if editor == "" {
		editor = c.os.Getenv("GIT_EDITOR")
	}
	if editor == "" {
		editor = c.os.Getenv("VISUAL")
	}
	if editor == "" {
		editor = c.os.Getenv("EDITOR")
	}
	if editor == "" {
		if err := c.cmd.New("which vi").DontLog().Run(); err == nil {
			editor = "vi"
		}
	}
	if editor == "" {
		return "", errors.New("No editor defined in config file, $GIT_EDITOR, $VISUAL, $EDITOR, or git config")
	}

	templateValues := map[string]string{
		"editor":   editor,
		"filename": c.cmd.Quote(filename),
		"line":     strconv.Itoa(lineNumber),
	}

	editCmdTemplate := c.UserConfig.OS.EditCommandTemplate
	return utils.ResolvePlaceholderString(editCmdTemplate, templateValues), nil
}