-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.go
112 lines (101 loc) · 2.43 KB
/
main.go
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"flag"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
func removeDuplicates(elements []string) []string {
encountered := map[string]bool{}
result := []string{}
for v := range elements {
if encountered[elements[v]] == true {
// Don't do anything
} else {
encountered[elements[v]] = true
result = append(result, elements[v])
}
}
return result
}
func main() {
// Option to only consider top level folders
topLevelOnly := flag.Bool("top", false, "")
args := os.Args
if len(args) < 2 {
log.Fatal("Please provide a path as argument.")
}
path, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
if args[1:][0] == "." {
update(path, *topLevelOnly)
} else {
update(path+"/"+args[1:][0], *topLevelOnly)
}
}
// Track & update files in passed in path.
// If it's folder, commit entire folder. If one file, commit the file.
// Commit with file names as commit msg & push to remote.
func update(path string, topLevelOnly bool) {
cmd := exec.Command("git")
file, err := os.Stat(path)
if err != nil {
log.Fatal(err)
}
// if it's not dir, then strip the extension
if !file.IsDir() {
path = filepath.Dir(path)
}
cmd.Dir = path
cmd.Args = []string{"git", "add", path}
_, err = cmd.Output()
if err != nil {
log.Fatal(err)
} else {
cmd = exec.Command("git")
cmd.Dir = path
cmd.Args = []string{"git", "diff", "--cached", "HEAD", "--name-only"}
out, err := cmd.Output()
if err != nil {
log.Fatal(err)
} else {
outS := strings.Fields(string(out))
filesChanged := make([]string, 0)
// Get all files changed without extension
for _, v := range outS {
split := strings.Split(v, "/")
if topLevelOnly {
first := split[0]
filesChanged = append(filesChanged, first)
} else {
filename := split[len(split)-1]
normalizedFilename := strings.TrimPrefix(filename, ".")
basename := strings.Split(normalizedFilename, ".")[0]
filesChanged = append(filesChanged, basename)
}
}
filesChanged = removeDuplicates(filesChanged)
// Commit with a message
commitMsg := strings.Join(filesChanged, " ")
cmd = exec.Command("git")
cmd.Dir = path
cmd.Args = []string{"git", "commit", "-m", commitMsg}
_, err = cmd.Output()
if err != nil {
log.Fatal(err)
}
// Push changes
cmd = exec.Command("git")
cmd.Dir = path
cmd.Args = []string{"git", "push"}
_, err = cmd.Output()
if err != nil {
log.Fatal(err)
}
}
}
}