summaryrefslogtreecommitdiffstats
path: root/pkg/commands/git_commands/commit_file_loader.go
blob: 68faf31cad46b5daf500da19a195d873fd6470b9 (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
package git_commands

import (
	"strings"

	"github.com/jesseduffield/lazygit/pkg/commands/models"
	"github.com/jesseduffield/lazygit/pkg/commands/oscommands"
	"github.com/jesseduffield/lazygit/pkg/common"
	"github.com/samber/lo"
)

type CommitFileLoader struct {
	*common.Common
	cmd oscommands.ICmdObjBuilder
}

func NewCommitFileLoader(common *common.Common, cmd oscommands.ICmdObjBuilder) *CommitFileLoader {
	return &CommitFileLoader{
		Common: common,
		cmd:    cmd,
	}
}

// GetFilesInDiff get the specified commit files
func (self *CommitFileLoader) GetFilesInDiff(from string, to string, reverse bool) ([]*models.CommitFile, error) {
	cmdArgs := NewGitCmd("diff").
		Config("diff.noprefix=false").
		Arg("--submodule").
		Arg("--no-ext-diff").
		Arg("--name-status").
		Arg("-z").
		Arg("--no-renames").
		ArgIf(reverse, "-R").
		Arg(from).
		Arg(to).
		ToArgv()

	filenames, err := self.cmd.New(cmdArgs).DontLog().RunWithOutput()
	if err != nil {
		return nil, err
	}

	return getCommitFilesFromFilenames(filenames), nil
}

// filenames string is something like "MM\x00file1\x00MU\x00file2\x00AA\x00file3\x00"
// so we need to split it by the null character and then map each status-name pair to a commit file
func getCommitFilesFromFilenames(filenames string) []*models.CommitFile {
	lines := strings.Split(strings.TrimRight(filenames, "\x00"), "\x00")
	if len(lines) == 1 {
		return []*models.CommitFile{}
	}

	// typical result looks like 'A my_file' meaning my_file was added
	return lo.Map(lo.Chunk(lines, 2), func(chunk []string, _ int) *models.CommitFile {
		return &models.CommitFile{
			ChangeStatus: chunk[0],
			Name:         chunk[1],
		}
	})
}