summaryrefslogtreecommitdiff
path: root/main.go
blob: 59f864f63363d47ac8302c3da3003cbae4e0071a (plain)
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
package main

// see `man 5 githooks` for details

import (
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"strings"
)

func main() {
	log.SetFlags(0)

	log.Println("Starting craft")
	log.Printf("Git hook type: %s\n", getHookType())

	cwd, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Current working directory: %s\n", cwd)

	for {
		fmt.Println(getUpdate())
	}
}

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)
}

type update struct {
	old, updated, ref string
}

func (u update) String() string {
	ret := fmt.Sprintf("'%s' updated from '%s' to '%s'", u.ref, u.old, u.updated)
	return ret
}

func getUpdate() 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) {
			os.Exit(0)
		} else {
			log.Fatal(err)
		}
	}
	return u
}