summaryrefslogtreecommitdiffstats
path: root/pkg/commands/loaders/commit_files.go
blob: 1b65737ecd307ab6ce69b5f44170a432d5a0fddc (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
package loaders

import (
	"fmt"
	"strings"

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

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) {
	reverseFlag := ""
	if reverse {
		reverseFlag = " -R "
	}

	filenames, err := self.cmd.New(fmt.Sprintf("git diff --submodule --no-ext-diff --name-status -z --no-renames %s %s %s", reverseFlag, from, to)).RunWithOutput()
	if err != nil {
		return nil, err
	}

	return self.getCommitFilesFromFilenames(filenames), nil
}

// filenames string is something like "file1\nfile2\nfile3"
func (self *CommitFileLoader) getCommitFilesFromFilenames(filenames string) []*models.CommitFile {
	commitFiles := make([]*models.CommitFile, 0)

	lines := strings.Split(strings.TrimRight(filenames, "\x00"), "\x00")
	n := len(lines)
	for i := 0; i < n-1; i += 2 {
		// typical result looks like 'A my_file' meaning my_file was added
		changeStatus := lines[i]
		name := lines[i+1]

		commitFiles = append(commitFiles, &models.CommitFile{
			Name:         name,
			ChangeStatus: changeStatus,
		})
	}

	return commitFiles
}