-
Notifications
You must be signed in to change notification settings - Fork 0
/
prepare-commit-msg.go
74 lines (63 loc) · 1.36 KB
/
prepare-commit-msg.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
package main
import (
"bytes"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
)
func readFile(filename string) string {
contents, err := ioutil.ReadFile(filename)
if err != nil {
log.Printf("Error during reading file: %s", err)
return ""
}
return string(contents)
}
func runCommand(command string, values ...string) string {
cmd := exec.Command(command, values...)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
panic(err)
}
return out.String()
}
func main() {
gitDir := runCommand("git", "rev-parse", "--git-dir")
gitDiff := runCommand("git", "diff", "--name-only", "--cached")
absolutePath := filepath.Dir(gitDir)
resultLines := strings.Split(gitDiff, "\n")
if resultLines == nil {
return
}
re := regexp.MustCompile(`package\s(\w+)`)
names := make(map[string]bool)
var prefix string
for _, filename := range resultLines {
if filename != "" {
content := readFile(absolutePath + "/" + filename)
pkg := re.FindStringSubmatch(string(content))
if len(pkg) < 2 {
continue
}
if _, found := names[pkg[1]]; !found {
if prefix != "" {
prefix += "|"
}
prefix += pkg[1]
names[pkg[1]] = true
}
}
}
if prefix != "" {
prefix = "[" + prefix + "] "
filename := os.Args[1]
msg := readFile(filename)
ioutil.WriteFile(filename, []byte(prefix+msg), 0x777)
}
}