forked from ae6rt/decap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stash.go
85 lines (71 loc) · 2.5 KB
/
stash.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
)
// See https://confluence.atlassian.com/stash/post-service-webhook-for-stash-393284006.html for payload information.
// StashEvent models a post-commit hook payload from Atlassian Stash Git SCM
type StashEvent struct {
Repository StashRepository `json:"repository"`
RefChanges []StashRefChange `json:"refChanges"`
}
// StashRepository models a Stash repository, consisting of a project and slug. Slug is the foo part of scheme://host:port/project/foo.git Stash URL.
type StashRepository struct {
Slug string `json:"slug"`
Project StashProject `json:"project"`
}
// StashProject models the Project name for an Atlassian Stash repository.
type StashProject struct {
Key string `json:"key"`
}
// StashRefChange models the branch or tag ref of a Stash post commit hook payload.
type StashRefChange struct {
RefID string `json:"refId"`
}
// Team returns the Project-part of a Stash post commit hook payload.
func (stash StashEvent) Team() string {
return stash.Repository.Project.Key
}
// Project returns the Slug part of a Stash post commit hook payload.
func (stash StashEvent) Project() string {
return stash.Repository.Slug
}
// Key returns the project key / slug tuple. This defines the key in a Decap map of projects that holds this project's configuration.
func (stash StashEvent) Key() string {
return projectKey(stash.Repository.Project.Key, stash.Repository.Slug)
}
// Refs returns the list of branches referenced in a Stash post commit hook payload.
func (stash StashEvent) Refs() []string {
var branches []string
for _, v := range stash.RefChanges {
branches = append(branches, strings.ToLower(strings.Replace(v.RefID, "refs/heads/", "", -1)))
}
return branches
}
// Hash returns a hash key for a project for use in identifying unique deferred builds.
func (stash StashEvent) Hash() string {
return fmt.Sprintf("%s/%s", stash.Key(), strings.Join(stash.Refs(), "/"))
}
// StashHandler handles launching a build for Stash post commit hook events.
type StashHandler struct {
decap Builder
}
// The http handler for handling Stash post commit hook events.
func (handler StashHandler) handle(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
data, err := ioutil.ReadAll(r.Body)
if err != nil {
Log.Println(err)
return
}
Log.Printf("Stash hook received: %s\n", data)
var event StashEvent
if err := json.Unmarshal(data, &event); err != nil {
Log.Println(err)
return
}
go handler.decap.LaunchBuild(event)
}