Debian Codegraph @

internal/command/status.go

raw symbols SCIP
1 package command
2
3 import (
4 "fmt"
5 "os"
6 "regexp"
7 "sort"
8 "strings"
9
10 "github.com/isacikgoz/gitbatch/internal/git"
11 )
12
13 func shortStatus(r *git.Repository, option string) string {
14 args := make([]string, 0)
15 args = append(args, "status")
16 args = append(args, option)
17 args = append(args, "--short")
18 out, err := Run(r.AbsPath, "git", args)
19 if err != nil {
20 return "?"
21 }
22 return out
23 }
24
25 // Status returns the dirty files
26 func Status(r *git.Repository) ([]*git.File, error) {
27 // in case we want configure Status command externally
28 mode := ModeLegacy
29
30 switch mode {
31 case ModeLegacy:
32 return statusWithGit(r)
33 case ModeNative:
34 return statusWithGoGit(r)
35 }
36 return nil, fmt.Errorf("unhandled status operation")
37 }
38
39 // PlainStatus returns the plain status
40 func PlainStatus(r *git.Repository) (string, error) {
41 args := make([]string, 0)
42 args = append(args, "status")
43 output, err := Run(r.AbsPath, "git", args)
44 if err != nil {
45 return "", err
46 }
47 re := regexp.MustCompile(`\n?\r`)
48 output = re.ReplaceAllString(output, "\n")
49 return output, err
50 }
51
52 // LoadFiles function simply commands a git status and collects output in a
53 // structured way
54 func statusWithGit(r *git.Repository) ([]*git.File, error) {
55 files := make([]*git.File, 0)
56 output := shortStatus(r, "--untracked-files=all")
57 if len(output) == 0 {
58 return files, nil
59 }
60 fileslist := strings.Split(output, "\n")
61 for _, file := range fileslist {
62 x := byte(file[0])
63 y := byte(file[1])
64 relativePathRegex := regexp.MustCompile(`[(\w|/|.|\-)]+`)
65 path := relativePathRegex.FindString(file[2:])
66
67 files = append(files, &git.File{
68 Name: path,
69 AbsPath: r.AbsPath + string(os.PathSeparator) + path,
70 X: git.FileStatus(x),
71 Y: git.FileStatus(y),
72 })
73 }
74 sort.Sort(git.FilesAlphabetical(files))
75 return files, nil
76 }
77
78 func statusWithGoGit(r *git.Repository) ([]*git.File, error) {
79 files := make([]*git.File, 0)
80 w, err := r.Repo.Worktree()
81 if err != nil {
82 return files, err
83 }
84 s, err := w.Status()
85 if err != nil {
86 return files, err
87 }
88 for k, v := range s {
89 files = append(files, &git.File{
90 Name: k,
91 AbsPath: r.AbsPath + string(os.PathSeparator) + k,
92 X: git.FileStatus(v.Staging),
93 Y: git.FileStatus(v.Worktree),
94 })
95 }
96 sort.Sort(git.FilesAlphabetical(files))
97 return files, nil
98 }