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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
|
package main
// see `man 5 githooks` for details
import (
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
func main() {
log.SetFlags(0)
defer log.Println("Exiting craft")
log.Println("Starting craft")
hookType := getHookType()
log.Printf("Git hook type: %s\n", hookType)
repo := getRepositoryPath()
log.Printf("Git repository: %s\n", repo)
for {
eof, update := getUpdate()
if eof {
break
}
log.Printf("Git ref update: %s\n", update)
commit := update.updated
_ = prepareWorkbench(repo, commit)
}
}
func runCommand(name string, args ...string) {
log.Printf("%s %s\n", name, strings.Join(args, " "))
command := exec.Command(name, args...)
err := command.Run()
if err != nil {
log.Fatal(err)
}
}
func prepareWorkbench(repo string, commit string) string {
workbench, err := os.MkdirTemp("", "*-craft")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(workbench)
runCommand(
"git",
"clone",
repo,
workbench,
)
runCommand(
"git",
"--git-dir",
filepath.Join(workbench, ".git"),
"--work-tree",
workbench,
"checkout",
commit,
)
return workbench
}
func getHookType() string {
args := len(os.Args)
if args != 1 {
log.Fatalf("Expected zero arguments but %d were given", args-1)
}
prefix := `hooks/`
path := os.Args[0]
hookType := strings.TrimPrefix(path, prefix)
if path == hookType {
log.Fatalf("Hook path '%s' has no '%s' prefix", path, prefix)
}
validateHookType(hookType)
return hookType
}
func validateHookType(hookType string) {
validTypes := [...]string{
`post-receive`,
}
for _, currentType := range validTypes {
if hookType == currentType {
return
}
}
log.Fatalf("Not supported Git hook type '%s'\n", hookType)
}
func getRepositoryPath() string {
cwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
return cwd
}
type update struct {
old, updated, ref string
}
func (u update) String() string {
ret := fmt.Sprintf("'%s' from '%s' to '%s'", u.ref, u.old, u.updated)
return ret
}
func getUpdate() (bool, update) {
var u update
_, err := fmt.Scanf("%s %s %s\n", &u.old, &u.updated, &u.ref)
if err != nil {
if errors.Is(err, io.EOF) {
return true, u
} else {
log.Fatal(err)
}
}
return false, u
}
|