forked from abiosoft/caddy-git
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic_hook.go
64 lines (51 loc) · 1.36 KB
/
generic_hook.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
package git
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strings"
)
// GenericHook is generic webhook.
type GenericHook struct{}
type gPush struct {
Ref string `json:"ref"`
}
// DoesHandle satisfies hookHandler.
func (g GenericHook) DoesHandle(h http.Header) bool {
return true
}
// Handle satisfies hookhandler.
func (g GenericHook) Handle(w http.ResponseWriter, r *http.Request, repo *Repo) (int, error) {
if r.Method != "POST" {
return http.StatusMethodNotAllowed, errors.New("the request had an invalid method")
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return http.StatusRequestTimeout, errors.New("could not read body from request")
}
err = g.handlePush(body, repo)
if err != nil {
return http.StatusBadRequest, err
}
return http.StatusOK, nil
}
func (g GenericHook) handlePush(body []byte, repo *Repo) error {
var push gPush
err := json.Unmarshal(body, &push)
if err != nil {
return err
}
// extract the branch being pushed from the ref string
// and if it matches with our locally tracked one, pull.
refSlice := strings.Split(push.Ref, "/")
if len(refSlice) != 3 {
return errors.New("the push request contained an invalid reference string")
}
branch := refSlice[2]
if branch == repo.Branch {
Logger().Print("Received pull notification for the tracking branch, updating...\n")
repo.Pull()
}
return nil
}