|
| 1 | +package context |
| 2 | + |
| 3 | +import ( |
| 4 | + "os" |
| 5 | + "os/exec" |
| 6 | + "path/filepath" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +func StagedFiles() ([]string, error) { |
| 11 | + return ExecGitCommand("git diff --name-only --cached") |
| 12 | +} |
| 13 | + |
| 14 | +func AllFiles() ([]string, error) { |
| 15 | + return ExecGitCommand("git ls-files --cached") |
| 16 | +} |
| 17 | + |
| 18 | +func PushFiles() ([]string, error) { |
| 19 | + return ExecGitCommand("git diff --name-only HEAD master") |
| 20 | +} |
| 21 | + |
| 22 | +func ExecGitCommand(command string) ([]string, error) { |
| 23 | + commandArg := strings.Split(command, " ") |
| 24 | + cmd := exec.Command(commandArg[0], commandArg[1:]...) |
| 25 | + |
| 26 | + outputBytes, err := cmd.CombinedOutput() |
| 27 | + if err != nil { |
| 28 | + return []string{}, err |
| 29 | + } |
| 30 | + |
| 31 | + lines := strings.Split(string(outputBytes), "\n") |
| 32 | + |
| 33 | + return ExtractFiles(lines) |
| 34 | +} |
| 35 | + |
| 36 | +func FilterByExt(files []string, ext string) []string { |
| 37 | + filtred := make([]string, 0) |
| 38 | + |
| 39 | + for _, f := range files { |
| 40 | + if filepath.Ext(f) == ext { |
| 41 | + filtred = append(filtred, f) |
| 42 | + } |
| 43 | + } |
| 44 | + return filtred |
| 45 | +} |
| 46 | + |
| 47 | +func IsFile(path string) (bool, error) { |
| 48 | + stat, err := os.Stat(path) |
| 49 | + if err != nil { |
| 50 | + if os.IsNotExist(err) { |
| 51 | + return false, nil |
| 52 | + } else { |
| 53 | + return false, err |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return !stat.IsDir(), nil |
| 58 | +} |
| 59 | + |
| 60 | +func IsDir(path string) (bool, error) { |
| 61 | + stat, err := os.Stat(path) |
| 62 | + if err != nil { |
| 63 | + if os.IsNotExist(err) { |
| 64 | + return false, nil |
| 65 | + } else { |
| 66 | + return false, err |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + return stat.IsDir(), nil |
| 71 | +} |
| 72 | + |
| 73 | +func ExtractFiles(lines []string) ([]string, error) { |
| 74 | + var files []string |
| 75 | + |
| 76 | + for _, line := range lines { |
| 77 | + file := strings.TrimSpace(line) |
| 78 | + if len(file) == 0 { |
| 79 | + continue |
| 80 | + } |
| 81 | + |
| 82 | + isFile, err := IsFile(file) |
| 83 | + if err != nil { |
| 84 | + return nil, err |
| 85 | + } |
| 86 | + |
| 87 | + if isFile { |
| 88 | + files = append(files, file) |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + return files, nil |
| 93 | +} |
0 commit comments