Brendan Abolivier преди 6 години
родител
ревизия
c776a2f822
Signed by: Brendan Abolivier <contact@brendanabolivier.com> GPG key ID: 8EF1500759F70623
променени са 24 файла, в които са добавени 17371 реда и са изтрити 7 реда
  1. 15
    5
      src/grafana/client.go
  2. 51
    2
      src/grafana/dashboards.go
  3. 16
    0
      src/grafana/json.go
  4. 61
    0
      src/pusher/main.go
  5. 58
    0
      src/pusher/webhook.go
  6. 6
    0
      vendor/manifest
  7. 22
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/LICENSE
  8. 155
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/README.md
  9. 195
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/bitbucket/bitbucket.go
  10. 3037
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/bitbucket/bitbucket_test.go
  11. 509
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/bitbucket/payload.go
  12. 67
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/examples/custom-logger/main.go
  13. 51
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/examples/multiple-handlers/main.go
  14. 42
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/examples/single-handler/main.go
  15. 281
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/github/github.go
  16. 5596
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/github/github_test.go
  17. 4972
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/github/payload.go
  18. 157
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/gitlab/gitlab.go
  19. 1197
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/gitlab/gitlab_test.go
  20. 438
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/gitlab/payload.go
  21. 44
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/logger.go
  22. BIN
      vendor/src/gopkg.in/go-playground/webhooks.v3/logo.png
  23. 121
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/webhooks.go
  24. 280
    0
      vendor/src/gopkg.in/go-playground/webhooks.v3/webhooks_test.go

+ 15
- 5
src/grafana/client.go Целия файл

@@ -51,13 +51,23 @@ func (c *Client) request(method string, endpoint string, body []byte) ([]byte, e
51 51
 		if resp.StatusCode == http.StatusNotFound {
52 52
 			err = fmt.Errorf("%s not found (404)", url)
53 53
 		} else {
54
-			err = fmt.Errorf(
55
-				"Unknown error: %d; body: %s",
56
-				resp.StatusCode,
57
-				string(respBody),
58
-			)
54
+			err = newHttpUnknownError(resp.StatusCode)
59 55
 		}
60 56
 	}
61 57
 
62 58
 	return respBody, err
63 59
 }
60
+
61
+type httpUnkownError struct {
62
+	StatusCode int
63
+}
64
+
65
+func newHttpUnknownError(statusCode int) *httpUnkownError {
66
+	return &httpUnkownError{
67
+		StatusCode: statusCode,
68
+	}
69
+}
70
+
71
+func (e *httpUnkownError) Error() string {
72
+	return fmt.Sprintf("Unknown HTTP error: %d", e.StatusCode)
73
+}

+ 51
- 2
src/grafana/dashboards.go Целия файл

@@ -2,6 +2,7 @@ package grafana
2 2
 
3 3
 import (
4 4
 	"encoding/json"
5
+	"fmt"
5 6
 )
6 7
 
7 8
 type dbSearchResponse struct {
@@ -13,6 +14,17 @@ type dbSearchResponse struct {
13 14
 	Starred bool     `json:"isStarred"`
14 15
 }
15 16
 
17
+type dbUpdateRequest struct {
18
+	Dashboard rawJSON `json:"dashboard"`
19
+	Overwrite bool    `json:"overwrite"`
20
+}
21
+
22
+type dbUpdateResponse struct {
23
+	Status  string `json:"success"`
24
+	Version int    `json:"version,omitempty"`
25
+	Message string `json:"message,omitempty"`
26
+}
27
+
16 28
 type Dashboard struct {
17 29
 	RawJSON []byte
18 30
 	Slug    string
@@ -21,7 +33,7 @@ type Dashboard struct {
21 33
 
22 34
 func (d *Dashboard) UnmarshalJSON(b []byte) (err error) {
23 35
 	var body struct {
24
-		Dashboard interface{} `json:"dashboard"`
36
+		Dashboard rawJSON `json:"dashboard"`
25 37
 		Meta      struct {
26 38
 			Slug    string `json:"slug"`
27 39
 			Version int    `json:"version"`
@@ -33,7 +45,7 @@ func (d *Dashboard) UnmarshalJSON(b []byte) (err error) {
33 45
 	}
34 46
 	d.Slug = body.Meta.Slug
35 47
 	d.Version = body.Meta.Version
36
-	d.RawJSON, err = json.Marshal(body.Dashboard)
48
+	d.RawJSON = body.Dashboard
37 49
 
38 50
 	return
39 51
 }
@@ -64,3 +76,40 @@ func (c *Client) GetDashboard(URI string) (db *Dashboard, err error) {
64 76
 	err = json.Unmarshal(body, db)
65 77
 	return
66 78
 }
79
+
80
+func (c *Client) UpdateDashboard(slug string, contentJSON []byte) (err error) {
81
+	reqBody := dbUpdateRequest{
82
+		Dashboard: rawJSON(contentJSON),
83
+		Overwrite: false,
84
+	}
85
+
86
+	reqBodyJSON, err := json.Marshal(reqBody)
87
+	if err != nil {
88
+		return
89
+	}
90
+
91
+	var httpError *httpUnkownError
92
+	var isHttpUnknownError bool
93
+	respBodyJSON, err := c.request("POST", "dashboards/db", reqBodyJSON)
94
+	if err != nil {
95
+		httpError, isHttpUnknownError = err.(*httpUnkownError)
96
+		// We process httpUnkownError errors below, after we decoded the body
97
+		if !isHttpUnknownError {
98
+			return
99
+		}
100
+	}
101
+
102
+	var respBody dbUpdateResponse
103
+	if err = json.Unmarshal(respBodyJSON, &respBody); err != nil {
104
+		return
105
+	}
106
+
107
+	if respBody.Status != "success" && isHttpUnknownError {
108
+		return fmt.Errorf(
109
+			"Failed to update dashboard %s (%d %s): %s",
110
+			slug, httpError.StatusCode, respBody.Status, respBody.Message,
111
+		)
112
+	}
113
+
114
+	return
115
+}

+ 16
- 0
src/grafana/json.go Целия файл

@@ -0,0 +1,16 @@
1
+package grafana
2
+
3
+// Taken from https://github.com/matrix-org/gomatrixserverlib/blob/7d789f4fb6fa1624901abf391426c5560d76793f/redactevent.go#L39-L51
4
+type rawJSON []byte
5
+
6
+// MarshalJSON implements the json.Marshaller interface using a value receiver.
7
+// This means that rawJSON used as an embedded value will still encode correctly.
8
+func (r rawJSON) MarshalJSON() ([]byte, error) {
9
+	return []byte(r), nil
10
+}
11
+
12
+// UnmarshalJSON implements the json.Unmarshaller interface using a pointer receiver.
13
+func (r *rawJSON) UnmarshalJSON(data []byte) error {
14
+	*r = rawJSON(data)
15
+	return nil
16
+}

+ 61
- 0
src/pusher/main.go Целия файл

@@ -0,0 +1,61 @@
1
+package main
2
+
3
+import (
4
+	"flag"
5
+	"os"
6
+
7
+	"grafana"
8
+)
9
+
10
+// The Grafana API client needs to be global to the package since we need it in
11
+// the webhook handlers
12
+// TODO: Find a better way to pass it to the handlers
13
+var grafanaClient *grafana.Client
14
+
15
+var (
16
+	grafanaURL       = flag.String("grafana-url", "", "Base URL of the Grafana instance")
17
+	grafanaAPIKey    = flag.String("api-key", "", "API key to use in authenticated requests")
18
+	clonePath        = flag.String("clone-path", "/tmp/grafana-dashboards", "Path to directory where the repo will be cloned")
19
+	repoURL          = flag.String("git-repo", "", "SSH URL for the Git repository, without the user part")
20
+	privateKeyPath   = flag.String("private-key", "", "Path to the private key used to talk with the Git remote")
21
+	webhookInterface = flag.String("webhook-interface", "127.0.0.1", "Interface on which the GitLab webhook will be exposed")
22
+	webhookPort      = flag.Int("webhook-port", 8080, "Port on which the GitLab webhook will be exposed")
23
+	webhookPath      = flag.String("webhook-path", "/gitlab-webhook", "Path at which GitLab should send payloads to the webhook")
24
+	webhookSecret    = flag.String("webhook-secret", "", "Secret GitLab will use to send payloads to the webhook")
25
+)
26
+
27
+func main() {
28
+	flag.Parse()
29
+
30
+	if *grafanaURL == "" {
31
+		println("Error: No Grafana URL provided")
32
+		flag.Usage()
33
+		os.Exit(1)
34
+	}
35
+	if *grafanaAPIKey == "" {
36
+		println("Error: No Grafana API key provided")
37
+		flag.Usage()
38
+		os.Exit(1)
39
+	}
40
+	if *repoURL == "" {
41
+		println("Error: No Git repository provided")
42
+		flag.Usage()
43
+		os.Exit(1)
44
+	}
45
+	if *privateKeyPath == "" {
46
+		println("Error: No private key provided")
47
+		flag.Usage()
48
+		os.Exit(1)
49
+	}
50
+	if *webhookSecret == "" {
51
+		println("Error: No webhook secret provided")
52
+		flag.Usage()
53
+		os.Exit(1)
54
+	}
55
+
56
+	grafanaClient = grafana.NewClient(*grafanaURL, *grafanaAPIKey)
57
+
58
+	if err := SetupWebhook(); err != nil {
59
+		panic(err)
60
+	}
61
+}

+ 58
- 0
src/pusher/webhook.go Целия файл

@@ -0,0 +1,58 @@
1
+package main
2
+
3
+import (
4
+	"io/ioutil"
5
+	"strconv"
6
+	"strings"
7
+
8
+	"gopkg.in/go-playground/webhooks.v3"
9
+	"gopkg.in/go-playground/webhooks.v3/gitlab"
10
+)
11
+
12
+func SetupWebhook() error {
13
+	hook := gitlab.New(&gitlab.Config{
14
+		Secret: "mysecret",
15
+	})
16
+	hook.RegisterEvents(HandlePush, gitlab.PushEvents)
17
+
18
+	return webhooks.Run(
19
+		hook,
20
+		*webhookInterface+":"+strconv.Itoa(*webhookPort),
21
+		*webhookPath,
22
+	)
23
+}
24
+
25
+func HandlePush(payload interface{}, header webhooks.Header) {
26
+	pl := payload.(gitlab.PushEventPayload)
27
+
28
+	var err error
29
+	for _, commit := range pl.Commits {
30
+		for _, addedFile := range commit.Added {
31
+			if err = pushFile(addedFile); err != nil {
32
+				panic(err)
33
+			}
34
+		}
35
+
36
+		for _, modifiedFile := range commit.Modified {
37
+			if err = pushFile(modifiedFile); err != nil {
38
+				panic(err)
39
+			}
40
+		}
41
+
42
+		// TODO: Remove a dashboard when its file gets deleted?
43
+	}
44
+
45
+}
46
+
47
+func pushFile(filename string) error {
48
+	filePath := *clonePath + "/" + filename
49
+	fileContent, err := ioutil.ReadFile(filePath)
50
+	if err != nil {
51
+		return err
52
+	}
53
+
54
+	// Remove the .json part
55
+	slug := strings.Split(filename, ".json")[0]
56
+
57
+	return grafanaClient.UpdateDashboard(slug, fileContent)
58
+}

+ 6
- 0
vendor/manifest Целия файл

@@ -100,6 +100,12 @@
100 100
 			"branch": "v1"
101 101
 		},
102 102
 		{
103
+			"importpath": "gopkg.in/go-playground/webhooks.v3",
104
+			"repository": "https://gopkg.in/go-playground/webhooks.v3",
105
+			"revision": "ad5392160cf8f0bfc3be06bc469ce5dfa4cd77c4",
106
+			"branch": "master"
107
+		},
108
+		{
103 109
 			"importpath": "gopkg.in/src-d/go-billy.v3",
104 110
 			"repository": "https://gopkg.in/src-d/go-billy.v3",
105 111
 			"revision": "c329b7bc7b9d24905d2bc1b85bfa29f7ae266314",

+ 22
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/LICENSE Целия файл

@@ -0,0 +1,22 @@
1
+The MIT License (MIT)
2
+
3
+Copyright (c) 2015 Dean Karn
4
+
5
+Permission is hereby granted, free of charge, to any person obtaining a copy
6
+of this software and associated documentation files (the "Software"), to deal
7
+in the Software without restriction, including without limitation the rights
8
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+copies of the Software, and to permit persons to whom the Software is
10
+furnished to do so, subject to the following conditions:
11
+
12
+The above copyright notice and this permission notice shall be included in all
13
+copies or substantial portions of the Software.
14
+
15
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+SOFTWARE.
22
+

+ 155
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/README.md Целия файл

@@ -0,0 +1,155 @@
1
+Library webhooks
2
+================
3
+<img align="right" src="https://raw.githubusercontent.com/go-playground/webhooks/v3/logo.png">![Project status](https://img.shields.io/badge/version-3.5.0-green.svg)
4
+[![Build Status](https://travis-ci.org/go-playground/webhooks.svg?branch=v3)](https://travis-ci.org/go-playground/webhooks)
5
+[![Coverage Status](https://coveralls.io/repos/go-playground/webhooks/badge.svg?branch=v3&service=github)](https://coveralls.io/github/go-playground/webhooks?branch=v3)
6
+[![Go Report Card](https://goreportcard.com/badge/go-playground/webhooks)](https://goreportcard.com/report/go-playground/webhooks)
7
+[![GoDoc](https://godoc.org/gopkg.in/go-playground/webhooks.v3?status.svg)](https://godoc.org/gopkg.in/go-playground/webhooks.v3)
8
+![License](https://img.shields.io/dub/l/vibe-d.svg)
9
+
10
+Library webhooks allows for easy receiving and parsing of GitHub, Bitbucket and GitLab Webhook Events
11
+
12
+Features:
13
+
14
+* Parses the entire payload, not just a few fields.
15
+* Fields + Schema directly lines up with webhook posted json
16
+
17
+Notes:
18
+
19
+* Currently only accepting json payloads.
20
+
21
+Installation
22
+------------
23
+
24
+Use go get.
25
+
26
+```shell
27
+	go get -u gopkg.in/go-playground/webhooks.v3
28
+```
29
+
30
+Then import the package into your own code.
31
+
32
+	import "gopkg.in/go-playground/webhooks.v3"
33
+
34
+Usage and Documentation
35
+------
36
+
37
+Please see http://godoc.org/gopkg.in/go-playground/webhooks.v3 for detailed usage docs.
38
+
39
+##### Examples:
40
+
41
+Multiple Handlers for each event you subscribe to
42
+```go
43
+package main
44
+
45
+import (
46
+	"fmt"
47
+	"strconv"
48
+
49
+	"gopkg.in/go-playground/webhooks.v3"
50
+	"gopkg.in/go-playground/webhooks.v3/github"
51
+)
52
+
53
+const (
54
+	path = "/webhooks"
55
+	port = 3016
56
+)
57
+
58
+func main() {
59
+
60
+	hook := github.New(&github.Config{Secret: "MyGitHubSuperSecretSecrect...?"})
61
+	hook.RegisterEvents(HandleRelease, github.ReleaseEvent)
62
+	hook.RegisterEvents(HandlePullRequest, github.PullRequestEvent)
63
+
64
+	err := webhooks.Run(hook, ":"+strconv.Itoa(port), path)
65
+	if err != nil {
66
+		fmt.Println(err)
67
+	}
68
+}
69
+
70
+// HandleRelease handles GitHub release events
71
+func HandleRelease(payload interface{}, header webhooks.Header) {
72
+
73
+	fmt.Println("Handling Release")
74
+
75
+	pl := payload.(github.ReleasePayload)
76
+
77
+	// only want to compile on full releases
78
+	if pl.Release.Draft || pl.Release.Prerelease || pl.Release.TargetCommitish != "master" {
79
+		return
80
+	}
81
+
82
+	// Do whatever you want from here...
83
+	fmt.Printf("%+v", pl)
84
+}
85
+
86
+// HandlePullRequest handles GitHub pull_request events
87
+func HandlePullRequest(payload interface{}, header webhooks.Header) {
88
+
89
+	fmt.Println("Handling Pull Request")
90
+
91
+	pl := payload.(github.PullRequestPayload)
92
+
93
+	// Do whatever you want from here...
94
+	fmt.Printf("%+v", pl)
95
+}
96
+```
97
+
98
+Single receiver for events you subscribe to
99
+```go
100
+package main
101
+
102
+import (
103
+	"fmt"
104
+	"strconv"
105
+
106
+	"gopkg.in/go-playground/webhooks.v3"
107
+	"gopkg.in/go-playground/webhooks.v3/github"
108
+)
109
+
110
+const (
111
+	path = "/webhooks"
112
+	port = 3016
113
+)
114
+
115
+func main() {
116
+
117
+	hook := github.New(&github.Config{Secret: "MyGitHubSuperSecretSecrect...?"})
118
+	hook.RegisterEvents(HandleMultiple, github.ReleaseEvent, github.PullRequestEvent) // Add as many as you want
119
+
120
+	err := webhooks.Run(hook, ":"+strconv.Itoa(port), path)
121
+	if err != nil {
122
+		fmt.Println(err)
123
+	}
124
+}
125
+
126
+// HandleMultiple handles multiple GitHub events
127
+func HandleMultiple(payload interface{}, header webhooks.Header) {
128
+
129
+	fmt.Println("Handling Payload..")
130
+
131
+	switch payload.(type) {
132
+
133
+	case github.ReleasePayload:
134
+		release := payload.(github.ReleasePayload)
135
+		// Do whatever you want from here...
136
+		fmt.Printf("%+v", release)
137
+
138
+	case github.PullRequestPayload:
139
+		pullRequest := payload.(github.PullRequestPayload)
140
+		// Do whatever you want from here...
141
+		fmt.Printf("%+v", pullRequest)
142
+	}
143
+}
144
+```
145
+
146
+Contributing
147
+------
148
+
149
+Pull requests for other services are welcome!
150
+
151
+If the changes being proposed or requested are breaking changes, please create an issue for discussion.
152
+
153
+License
154
+------
155
+Distributed under MIT License, please see license file in code for more details.

+ 195
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/bitbucket/bitbucket.go Целия файл

@@ -0,0 +1,195 @@
1
+package bitbucket
2
+
3
+import (
4
+	"encoding/json"
5
+	"fmt"
6
+	"io/ioutil"
7
+	"net/http"
8
+
9
+	"gopkg.in/go-playground/webhooks.v3"
10
+)
11
+
12
+// Webhook instance contains all methods needed to process events
13
+type Webhook struct {
14
+	provider   webhooks.Provider
15
+	uuid       string
16
+	eventFuncs map[Event]webhooks.ProcessPayloadFunc
17
+}
18
+
19
+// Config defines the configuration to create a new Bitbucket Webhook instance
20
+type Config struct {
21
+	UUID string
22
+}
23
+
24
+// Event defines a Bitbucket hook event type
25
+type Event string
26
+
27
+// Bitbucket hook types
28
+const (
29
+	RepoPushEvent                  Event = "repo:push"
30
+	RepoForkEvent                  Event = "repo:fork"
31
+	RepoUpdatedEvent               Event = "repo:updated"
32
+	RepoCommitCommentCreatedEvent  Event = "repo:commit_comment_created"
33
+	RepoCommitStatusCreatedEvent   Event = "repo:commit_status_created"
34
+	RepoCommitStatusUpdatedEvent   Event = "repo:commit_status_updated"
35
+	IssueCreatedEvent              Event = "issue:created"
36
+	IssueUpdatedEvent              Event = "issue:updated"
37
+	IssueCommentCreatedEvent       Event = "issue:comment_created"
38
+	PullRequestCreatedEvent        Event = "pullrequest:created"
39
+	PullRequestUpdatedEvent        Event = "pullrequest:updated"
40
+	PullRequestApprovedEvent       Event = "pullrequest:approved"
41
+	PullRequestUnapprovedEvent     Event = "pullrequest:unapproved"
42
+	PullRequestMergedEvent         Event = "pullrequest:fulfilled"
43
+	PullRequestDeclinedEvent       Event = "pullrequest:rejected"
44
+	PullRequestCommentCreatedEvent Event = "pullrequest:comment_created"
45
+	PullRequestCommentUpdatedEvent Event = "pullrequest:comment_updated"
46
+	PullRequestCommentDeletedEvent Event = "pull_request:comment_deleted"
47
+)
48
+
49
+// New creates and returns a WebHook instance denoted by the Provider type
50
+func New(config *Config) *Webhook {
51
+	return &Webhook{
52
+		provider:   webhooks.Bitbucket,
53
+		uuid:       config.UUID,
54
+		eventFuncs: map[Event]webhooks.ProcessPayloadFunc{},
55
+	}
56
+}
57
+
58
+// Provider returns the current hooks provider ID
59
+func (hook Webhook) Provider() webhooks.Provider {
60
+	return hook.provider
61
+}
62
+
63
+// RegisterEvents registers the function to call when the specified event(s) are encountered
64
+func (hook Webhook) RegisterEvents(fn webhooks.ProcessPayloadFunc, events ...Event) {
65
+
66
+	for _, event := range events {
67
+		hook.eventFuncs[event] = fn
68
+	}
69
+}
70
+
71
+// ParsePayload parses and verifies the payload and fires off the mapped function, if it exists.
72
+func (hook Webhook) ParsePayload(w http.ResponseWriter, r *http.Request) {
73
+	webhooks.DefaultLog.Info("Parsing Payload...")
74
+
75
+	uuid := r.Header.Get("X-Hook-UUID")
76
+	if uuid == "" {
77
+		webhooks.DefaultLog.Error("Missing X-Hook-UUID Header")
78
+		http.Error(w, "400 Bad Request - Missing X-Hook-UUID Header", http.StatusBadRequest)
79
+		return
80
+	}
81
+	webhooks.DefaultLog.Debug(fmt.Sprintf("X-Hook-UUID:%s", uuid))
82
+
83
+	if uuid != hook.uuid {
84
+		webhooks.DefaultLog.Error(fmt.Sprintf("X-Hook-UUID does not match configured uuid of %s", hook.uuid))
85
+		http.Error(w, "403 Forbidden - X-Hook-UUID does not match", http.StatusForbidden)
86
+		return
87
+	}
88
+
89
+	event := r.Header.Get("X-Event-Key")
90
+	if event == "" {
91
+		webhooks.DefaultLog.Error("Missing X-Event-Key Header")
92
+		http.Error(w, "400 Bad Request - Missing X-Event-Key Header", http.StatusBadRequest)
93
+		return
94
+	}
95
+	webhooks.DefaultLog.Debug(fmt.Sprintf("X-Event-Key:%s", event))
96
+
97
+	bitbucketEvent := Event(event)
98
+
99
+	fn, ok := hook.eventFuncs[bitbucketEvent]
100
+	// if no event registered
101
+	if !ok {
102
+		webhooks.DefaultLog.Info(fmt.Sprintf("Webhook Event %s not registered, it is recommended to setup only events in bitbucket that will be registered in the webhook to avoid unnecessary traffic and reduce potential attack vectors.", event))
103
+		return
104
+	}
105
+
106
+	payload, err := ioutil.ReadAll(r.Body)
107
+	if err != nil || len(payload) == 0 {
108
+		webhooks.DefaultLog.Error("Issue reading Payload")
109
+		http.Error(w, "Issue reading Payload", http.StatusInternalServerError)
110
+		return
111
+	}
112
+	webhooks.DefaultLog.Debug(fmt.Sprintf("Payload:%s", string(payload)))
113
+	hd := webhooks.Header(r.Header)
114
+
115
+	switch bitbucketEvent {
116
+	case RepoPushEvent:
117
+		var pl RepoPushPayload
118
+		json.Unmarshal([]byte(payload), &pl)
119
+		hook.runProcessPayloadFunc(fn, pl, hd)
120
+	case RepoForkEvent:
121
+		var pl RepoForkPayload
122
+		json.Unmarshal([]byte(payload), &pl)
123
+		hook.runProcessPayloadFunc(fn, pl, hd)
124
+	case RepoUpdatedEvent:
125
+		var pl RepoUpdatedPayload
126
+		json.Unmarshal([]byte(payload), &pl)
127
+		hook.runProcessPayloadFunc(fn, pl, hd)
128
+	case RepoCommitCommentCreatedEvent:
129
+		var pl RepoCommitCommentCreatedPayload
130
+		json.Unmarshal([]byte(payload), &pl)
131
+		hook.runProcessPayloadFunc(fn, pl, hd)
132
+	case RepoCommitStatusCreatedEvent:
133
+		var pl RepoCommitStatusCreatedPayload
134
+		json.Unmarshal([]byte(payload), &pl)
135
+		hook.runProcessPayloadFunc(fn, pl, hd)
136
+	case RepoCommitStatusUpdatedEvent:
137
+		var pl RepoCommitStatusUpdatedPayload
138
+		json.Unmarshal([]byte(payload), &pl)
139
+		hook.runProcessPayloadFunc(fn, pl, hd)
140
+	case IssueCreatedEvent:
141
+		var pl IssueCreatedPayload
142
+		json.Unmarshal([]byte(payload), &pl)
143
+		hook.runProcessPayloadFunc(fn, pl, hd)
144
+	case IssueUpdatedEvent:
145
+		var pl IssueUpdatedPayload
146
+		json.Unmarshal([]byte(payload), &pl)
147
+		hook.runProcessPayloadFunc(fn, pl, hd)
148
+	case IssueCommentCreatedEvent:
149
+		var pl IssueCommentCreatedPayload
150
+		json.Unmarshal([]byte(payload), &pl)
151
+		hook.runProcessPayloadFunc(fn, pl, hd)
152
+	case PullRequestCreatedEvent:
153
+		var pl PullRequestCreatedPayload
154
+		json.Unmarshal([]byte(payload), &pl)
155
+		hook.runProcessPayloadFunc(fn, pl, hd)
156
+	case PullRequestUpdatedEvent:
157
+		var pl PullRequestUpdatedPayload
158
+		json.Unmarshal([]byte(payload), &pl)
159
+		hook.runProcessPayloadFunc(fn, pl, hd)
160
+	case PullRequestApprovedEvent:
161
+		var pl PullRequestApprovedPayload
162
+		json.Unmarshal([]byte(payload), &pl)
163
+		hook.runProcessPayloadFunc(fn, pl, hd)
164
+	case PullRequestUnapprovedEvent:
165
+		var pl PullRequestUnapprovedPayload
166
+		json.Unmarshal([]byte(payload), &pl)
167
+		hook.runProcessPayloadFunc(fn, pl, hd)
168
+	case PullRequestMergedEvent:
169
+		var pl PullRequestMergedPayload
170
+		json.Unmarshal([]byte(payload), &pl)
171
+		hook.runProcessPayloadFunc(fn, pl, hd)
172
+	case PullRequestDeclinedEvent:
173
+		var pl PullRequestDeclinedPayload
174
+		json.Unmarshal([]byte(payload), &pl)
175
+		hook.runProcessPayloadFunc(fn, pl, hd)
176
+	case PullRequestCommentCreatedEvent:
177
+		var pl PullRequestCommentCreatedPayload
178
+		json.Unmarshal([]byte(payload), &pl)
179
+		hook.runProcessPayloadFunc(fn, pl, hd)
180
+	case PullRequestCommentUpdatedEvent:
181
+		var pl PullRequestCommentUpdatedPayload
182
+		json.Unmarshal([]byte(payload), &pl)
183
+		hook.runProcessPayloadFunc(fn, pl, hd)
184
+	case PullRequestCommentDeletedEvent:
185
+		var pl PullRequestCommentDeletedPayload
186
+		json.Unmarshal([]byte(payload), &pl)
187
+		hook.runProcessPayloadFunc(fn, pl, hd)
188
+	}
189
+}
190
+
191
+func (hook Webhook) runProcessPayloadFunc(fn webhooks.ProcessPayloadFunc, results interface{}, header webhooks.Header) {
192
+	go func(fn webhooks.ProcessPayloadFunc, results interface{}, header webhooks.Header) {
193
+		fn(results, header)
194
+	}(fn, results, header)
195
+}

+ 3037
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/bitbucket/bitbucket_test.go
Файловите разлики са ограничени, защото са твърде много
Целия файл


+ 509
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/bitbucket/payload.go Целия файл

@@ -0,0 +1,509 @@
1
+package bitbucket
2
+
3
+import "time"
4
+
5
+// RepoPushPayload is the Bitbucket repo:push payload
6
+type RepoPushPayload struct {
7
+	Actor      Owner      `json:"actor"`
8
+	Repository Repository `json:"repository"`
9
+	Push       struct {
10
+		Changes []struct {
11
+			New struct {
12
+				Type   string `json:"type"`
13
+				Name   string `json:"name"`
14
+				Target struct {
15
+					Type    string    `json:"type"`
16
+					Hash    string    `json:"hash"`
17
+					Author  Owner     `json:"author"`
18
+					Message string    `json:"message"`
19
+					Date    time.Time `json:"date"`
20
+					Parents []struct {
21
+						Type  string `json:"type"`
22
+						Hash  string `json:"hash"`
23
+						Links struct {
24
+							Self struct {
25
+								Href string `json:"href"`
26
+							} `json:"self"`
27
+							HTML struct {
28
+								Href string `json:"href"`
29
+							} `json:"html"`
30
+						} `json:"links"`
31
+					} `json:"parents"`
32
+					Links struct {
33
+						Self struct {
34
+							Href string `json:"href"`
35
+						} `json:"self"`
36
+						HTML struct {
37
+							Href string `json:"href"`
38
+						} `json:"html"`
39
+					} `json:"links"`
40
+				} `json:"target"`
41
+				Links struct {
42
+					Self struct {
43
+						Href string `json:"href"`
44
+					} `json:"self"`
45
+					Commits struct {
46
+						Href string `json:"href"`
47
+					} `json:"commits"`
48
+					HTML struct {
49
+						Href string `json:"href"`
50
+					} `json:"html"`
51
+				} `json:"links"`
52
+			} `json:"new"`
53
+			Old struct {
54
+				Type   string `json:"type"`
55
+				Name   string `json:"name"`
56
+				Target struct {
57
+					Type    string    `json:"type"`
58
+					Hash    string    `json:"hash"`
59
+					Author  Owner     `json:"author"`
60
+					Message string    `json:"message"`
61
+					Date    time.Time `json:"date"`
62
+					Parents []struct {
63
+						Type  string `json:"type"`
64
+						Hash  string `json:"hash"`
65
+						Links struct {
66
+							Self struct {
67
+								Href string `json:"href"`
68
+							} `json:"self"`
69
+							HTML struct {
70
+								Href string `json:"href"`
71
+							} `json:"html"`
72
+						} `json:"links"`
73
+					} `json:"parents"`
74
+					Links struct {
75
+						Self struct {
76
+							Href string `json:"href"`
77
+						} `json:"self"`
78
+						HTML struct {
79
+							Href string `json:"href"`
80
+						} `json:"html"`
81
+					} `json:"links"`
82
+				} `json:"target"`
83
+				Links struct {
84
+					Self struct {
85
+						Href string `json:"href"`
86
+					} `json:"self"`
87
+					Commits struct {
88
+						Href string `json:"href"`
89
+					} `json:"commits"`
90
+					HTML struct {
91
+						Href string `json:"href"`
92
+					} `json:"html"`
93
+				} `json:"links"`
94
+			} `json:"old"`
95
+			Links struct {
96
+				HTML struct {
97
+					Href string `json:"href"`
98
+				} `json:"html"`
99
+				Diff struct {
100
+					Href string `json:"href"`
101
+				} `json:"diff"`
102
+				Commits struct {
103
+					Href string `json:"href"`
104
+				} `json:"commits"`
105
+			} `json:"links"`
106
+			Created bool `json:"created"`
107
+			Forced  bool `json:"forced"`
108
+			Closed  bool `json:"closed"`
109
+			Commits []struct {
110
+				Hash    string `json:"hash"`
111
+				Type    string `json:"type"`
112
+				Message string `json:"message"`
113
+				Author  Owner  `json:"author"`
114
+				Links   struct {
115
+					Self struct {
116
+						Href string `json:"href"`
117
+					} `json:"self"`
118
+					HTML struct {
119
+						Href string `json:"href"`
120
+					} `json:"html"`
121
+				} `json:"links"`
122
+			} `json:"commits"`
123
+			Truncated bool `json:"truncated"`
124
+		} `json:"changes"`
125
+	} `json:"push"`
126
+}
127
+
128
+// RepoForkPayload is the Bitbucket repo:fork payload
129
+type RepoForkPayload struct {
130
+	Actor      Owner      `json:"actor"`
131
+	Repository Repository `json:"repository"`
132
+	Fork       Repository `json:"fork"`
133
+}
134
+
135
+// RepoUpdatedPayload is the Bitbucket repo:updated payload
136
+type RepoUpdatedPayload struct {
137
+	Actor      Owner      `json:"actor"`
138
+	Repository Repository `json:"repository"`
139
+	Changes    struct {
140
+		Name struct {
141
+			New string `json:"new"`
142
+			Old string `json:"old"`
143
+		} `json:"name"`
144
+		Website struct {
145
+			New string `json:"new"`
146
+			Old string `json:"old"`
147
+		} `json:"website"`
148
+		Language struct {
149
+			New string `json:"new"`
150
+			Old string `json:"old"`
151
+		} `json:"language"`
152
+		Links struct {
153
+			New struct {
154
+				Avatar struct {
155
+					Href string `json:"href"`
156
+				} `json:"avatar"`
157
+				Self struct {
158
+					Href string `json:"href"`
159
+				} `json:"self"`
160
+				HTML struct {
161
+					Href string `json:"href"`
162
+				} `json:"html"`
163
+			} `json:"new"`
164
+			Old struct {
165
+				Avatar struct {
166
+					Href string `json:"href"`
167
+				} `json:"avatar"`
168
+				Self struct {
169
+					Href string `json:"href"`
170
+				} `json:"self"`
171
+				HTML struct {
172
+					Href string `json:"href"`
173
+				} `json:"html"`
174
+			} `json:"old"`
175
+		} `json:"links"`
176
+		Description struct {
177
+			New string `json:"new"`
178
+			Old string `json:"old"`
179
+		} `json:"description"`
180
+		FullName struct {
181
+			New string `json:"new"`
182
+			Old string `json:"old"`
183
+		} `json:"full_name"`
184
+	} `json:"changes"`
185
+}
186
+
187
+// RepoCommitCommentCreatedPayload is the Bitbucket repo:commit_comment_created payload
188
+type RepoCommitCommentCreatedPayload struct {
189
+	Actor      Owner      `json:"actor"`
190
+	Comment    Comment    `json:"comment"`
191
+	Repository Repository `json:"repository"`
192
+	Commit     struct {
193
+		Hash string `json:"hash"`
194
+	} `json:"commit"`
195
+}
196
+
197
+// RepoCommitStatusCreatedPayload is the Bitbucket repo:commit_status_created payload
198
+type RepoCommitStatusCreatedPayload struct {
199
+	Actor        Owner      `json:"actor"`
200
+	Repository   Repository `json:"repository"`
201
+	CommitStatus struct {
202
+		Name        string    `json:"name"`
203
+		Description string    `json:"description"`
204
+		State       string    `json:"state"`
205
+		Key         string    `json:"key"`
206
+		URL         string    `json:"url"`
207
+		Type        string    `json:"type"`
208
+		CreatedOn   time.Time `json:"created_on"`
209
+		UpdatedOn   time.Time `json:"updated_on"`
210
+		Links       struct {
211
+			Commit struct {
212
+				Href string `json:"href"`
213
+			} `json:"commit"`
214
+			Self struct {
215
+				Href string `json:"href"`
216
+			} `json:"self"`
217
+		} `json:"links"`
218
+	} `json:"commit_status"`
219
+}
220
+
221
+// RepoCommitStatusUpdatedPayload is the Bitbucket repo:commit_status_updated payload
222
+type RepoCommitStatusUpdatedPayload struct {
223
+	Actor        Owner      `json:"actor"`
224
+	Repository   Repository `json:"repository"`
225
+	CommitStatus struct {
226
+		Name        string    `json:"name"`
227
+		Description string    `json:"description"`
228
+		State       string    `json:"state"`
229
+		Key         string    `json:"key"`
230
+		URL         string    `json:"url"`
231
+		Type        string    `json:"type"`
232
+		CreatedOn   time.Time `json:"created_on"`
233
+		UpdatedOn   time.Time `json:"updated_on"`
234
+		Links       struct {
235
+			Commit struct {
236
+				Href string `json:"href"`
237
+			} `json:"commit"`
238
+			Self struct {
239
+				Href string `json:"href"`
240
+			} `json:"self"`
241
+		} `json:"links"`
242
+	} `json:"commit_status"`
243
+}
244
+
245
+// IssueCreatedPayload is the Bitbucket issue:created payload
246
+type IssueCreatedPayload struct {
247
+	Actor      Owner      `json:"actor"`
248
+	Issue      Issue      `json:"issue"`
249
+	Repository Repository `json:"repository"`
250
+}
251
+
252
+// IssueUpdatedPayload is the Bitbucket issue:updated payload
253
+type IssueUpdatedPayload struct {
254
+	Actor      Owner      `json:"actor"`
255
+	Issue      Issue      `json:"issue"`
256
+	Repository Repository `json:"repository"`
257
+	Comment    Comment    `json:"comment"`
258
+	Changes    struct {
259
+		Status struct {
260
+			Old string `json:"old"`
261
+			New string `json:"new"`
262
+		} `json:"status"`
263
+	} `json:"changes"`
264
+}
265
+
266
+// IssueCommentCreatedPayload is the Bitbucket pullrequest:created payload
267
+type IssueCommentCreatedPayload struct {
268
+	Actor      Owner      `json:"actor"`
269
+	Repository Repository `json:"repository"`
270
+	Issue      Issue      `json:"issue"`
271
+	Comment    Comment    `json:"comment"`
272
+}
273
+
274
+// PullRequestCreatedPayload is the Bitbucket pullrequest:created payload
275
+type PullRequestCreatedPayload struct {
276
+	Actor       Owner       `json:"actor"`
277
+	PullRequest PullRequest `json:"pullrequest"`
278
+	Repository  Repository  `json:"repository"`
279
+}
280
+
281
+// PullRequestUpdatedPayload is the Bitbucket pullrequest:updated payload
282
+type PullRequestUpdatedPayload struct {
283
+	Actor       Owner       `json:"actor"`
284
+	PullRequest PullRequest `json:"pullrequest"`
285
+	Repository  Repository  `json:"repository"`
286
+}
287
+
288
+// PullRequestApprovedPayload is the Bitbucket pullrequest:approved payload
289
+type PullRequestApprovedPayload struct {
290
+	Actor       Owner       `json:"actor"`
291
+	PullRequest PullRequest `json:"pullrequest"`
292
+	Repository  Repository  `json:"repository"`
293
+	Approval    struct {
294
+		Date time.Time `json:"date"`
295
+		User Owner     `json:"user"`
296
+	} `json:"approval"`
297
+}
298
+
299
+// PullRequestUnapprovedPayload is the Bitbucket pullrequest:unapproved payload
300
+type PullRequestUnapprovedPayload struct {
301
+	Actor       Owner       `json:"actor"`
302
+	PullRequest PullRequest `json:"pullrequest"`
303
+	Repository  Repository  `json:"repository"`
304
+	Approval    struct {
305
+		Date time.Time `json:"date"`
306
+		User Owner     `json:"user"`
307
+	} `json:"approval"`
308
+}
309
+
310
+// PullRequestMergedPayload is the Bitbucket pullrequest:fulfilled payload
311
+type PullRequestMergedPayload struct {
312
+	Actor       Owner       `json:"actor"`
313
+	PullRequest PullRequest `json:"pullrequest"`
314
+	Repository  Repository  `json:"repository"`
315
+}
316
+
317
+// PullRequestDeclinedPayload is the Bitbucket pullrequest:rejected payload
318
+type PullRequestDeclinedPayload struct {
319
+	Actor       Owner       `json:"actor"`
320
+	PullRequest PullRequest `json:"pullrequest"`
321
+	Repository  Repository  `json:"repository"`
322
+}
323
+
324
+// PullRequestCommentCreatedPayload is the Bitbucket pullrequest:comment_updated payload
325
+type PullRequestCommentCreatedPayload struct {
326
+	Actor       Owner       `json:"actor"`
327
+	Repository  Repository  `json:"repository"`
328
+	PullRequest PullRequest `json:"pullrequest"`
329
+	Comment     Comment     `json:"comment"`
330
+}
331
+
332
+// PullRequestCommentUpdatedPayload is the Bitbucket pullrequest:comment_created payload
333
+type PullRequestCommentUpdatedPayload struct {
334
+	Actor       Owner       `json:"actor"`
335
+	Repository  Repository  `json:"repository"`
336
+	PullRequest PullRequest `json:"pullrequest"`
337
+	Comment     Comment     `json:"comment"`
338
+}
339
+
340
+// PullRequestCommentDeletedPayload is the Bitbucket pullrequest:comment_deleted payload
341
+type PullRequestCommentDeletedPayload struct {
342
+	Actor       Owner       `json:"actor"`
343
+	Repository  Repository  `json:"repository"`
344
+	PullRequest PullRequest `json:"pullrequest"`
345
+	Comment     Comment     `json:"comment"`
346
+}
347
+
348
+// Owner is the common Bitbucket Owner Sub Entity
349
+type Owner struct {
350
+	Type        string `json:"type"`
351
+	Username    string `json:"username"`
352
+	DisplayName string `json:"display_name"`
353
+	UUID        string `json:"uuid"`
354
+	Links       struct {
355
+		Self struct {
356
+			Href string `json:"href"`
357
+		} `json:"self"`
358
+		HTML struct {
359
+			Href string `json:"href"`
360
+		} `json:"html"`
361
+		Avatar struct {
362
+			Href string `json:"href"`
363
+		} `json:"avatar"`
364
+	} `json:"links"`
365
+}
366
+
367
+// Repository is the common Bitbucket Repository Sub Entity
368
+type Repository struct {
369
+	Type  string `json:"type"`
370
+	Links struct {
371
+		Self struct {
372
+			Href string `json:"href"`
373
+		} `json:"self"`
374
+		HTML struct {
375
+			Href string `json:"href"`
376
+		} `json:"html"`
377
+		Avatar struct {
378
+			Href string `json:"href"`
379
+		} `json:"avatar"`
380
+	} `json:"links"`
381
+	UUID      string  `json:"uuid"`
382
+	Project   Project `json:"project"`
383
+	FullName  string  `json:"full_name"`
384
+	Name      string  `json:"name"`
385
+	Website   string  `json:"website"`
386
+	Owner     Owner   `json:"owner"`
387
+	Scm       string  `json:"scm"`
388
+	IsPrivate bool    `json:"is_private"`
389
+}
390
+
391
+// Project is the common Bitbucket Project Sub Entity
392
+type Project struct {
393
+	Type    string `json:"type"`
394
+	Project string `json:"project"`
395
+	UUID    string `json:"uuid"`
396
+	Links   struct {
397
+		HTML struct {
398
+			Href string `json:"href"`
399
+		} `json:"html"`
400
+		Avatar struct {
401
+			Href string `json:"href"`
402
+		} `json:"avatar"`
403
+	} `json:"links"`
404
+	Key string `json:"key"`
405
+}
406
+
407
+// Issue is the common Bitbucket Issue Sub Entity
408
+type Issue struct {
409
+	ID        int64  `json:"id"`
410
+	Component string `json:"component"`
411
+	Title     string `json:"title"`
412
+	Content   struct {
413
+		Raw    string `json:"raw"`
414
+		HTML   string `json:"html"`
415
+		Markup string `json:"markup"`
416
+	} `json:"content"`
417
+	Priority  string `json:"priority"`
418
+	State     string `json:"state"`
419
+	Type      string `json:"type"`
420
+	Milestone struct {
421
+		Name string `json:"name"`
422
+	} `json:"milestone"`
423
+	Version struct {
424
+		Name string `json:"name"`
425
+	} `json:"version"`
426
+	CreatedOn time.Time `json:"created_on"`
427
+	UpdatedOn time.Time `json:"updated_on"`
428
+	Links     struct {
429
+		Self struct {
430
+			Href string `json:"href"`
431
+		} `json:"self"`
432
+		HTML struct {
433
+			Href string `json:"href"`
434
+		} `json:"html"`
435
+	} `json:"links"`
436
+}
437
+
438
+// Comment is the common Bitbucket Comment Sub Entity
439
+type Comment struct {
440
+	ID     int64 `json:"id"`
441
+	Parent struct {
442
+		ID int64 `json:"id"`
443
+	} `json:"parent"`
444
+	Content struct {
445
+		Raw    string `json:"raw"`
446
+		HTML   string `json:"html"`
447
+		Markup string `json:"markup"`
448
+	} `json:"content"`
449
+	Inline struct {
450
+		Path string `json:"path"`
451
+		From *int64 `json:"from"`
452
+		To   int64  `json:"to"`
453
+	} `json:"inline"`
454
+	CreatedOn time.Time `json:"created_on"`
455
+	UpdatedOn time.Time `json:"updated_on"`
456
+	Links     struct {
457
+		Self struct {
458
+			Href string `json:"href"`
459
+		} `json:"self"`
460
+		HTML struct {
461
+			Href string `json:"href"`
462
+		} `json:"html"`
463
+	} `json:"links"`
464
+}
465
+
466
+// PullRequest is the common Bitbucket Pull Request Sub Entity
467
+type PullRequest struct {
468
+	ID          int64  `json:"id"`
469
+	Title       string `json:"title"`
470
+	Description string `json:"description"`
471
+	State       string `json:"state"`
472
+	Author      Owner  `json:"author"`
473
+	Source      struct {
474
+		Branch struct {
475
+			Name string `json:"name"`
476
+		} `json:"branch"`
477
+		Commit struct {
478
+			Hash string `json:"hash"`
479
+		} `json:"commit"`
480
+		Repository Repository `json:"repository"`
481
+	} `json:"source"`
482
+	Destination struct {
483
+		Branch struct {
484
+			Name string `json:"name"`
485
+		} `json:"branch"`
486
+		Commit struct {
487
+			Hash string `json:"hash"`
488
+		} `json:"commit"`
489
+		Repository Repository `json:"repository"`
490
+	} `json:"destination"`
491
+	MergeCommit struct {
492
+		Hash string `json:"hash"`
493
+	} `json:"merge_commit"`
494
+	Participants      []Owner   `json:"participants"`
495
+	Reviewers         []Owner   `json:"reviewers"`
496
+	CloseSourceBranch bool      `json:"close_source_branch"`
497
+	ClosedBy          Owner     `json:"closed_by"`
498
+	Reason            string    `json:"reason"`
499
+	CreatedOn         time.Time `json:"created_on"`
500
+	UpdatedOn         time.Time `json:"updated_on"`
501
+	Links             struct {
502
+		Self struct {
503
+			Href string `json:"href"`
504
+		} `json:"self"`
505
+		HTML struct {
506
+			Href string `json:"href"`
507
+		} `json:"html"`
508
+	} `json:"links"`
509
+}

+ 67
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/examples/custom-logger/main.go Целия файл

@@ -0,0 +1,67 @@
1
+package main
2
+
3
+import (
4
+	"fmt"
5
+	"log"
6
+	"strconv"
7
+
8
+	"gopkg.in/go-playground/webhooks.v3"
9
+	"gopkg.in/go-playground/webhooks.v3/github"
10
+)
11
+
12
+const (
13
+	path = "/webhooks"
14
+	port = 3016
15
+)
16
+
17
+type myLogger struct {
18
+	PrintDebugs bool
19
+}
20
+
21
+func (l *myLogger) Info(msg string) {
22
+	log.Println(msg)
23
+}
24
+
25
+func (l *myLogger) Error(msg string) {
26
+	log.Println(msg)
27
+}
28
+
29
+func (l *myLogger) Debug(msg string) {
30
+	if !l.PrintDebugs {
31
+		return
32
+	}
33
+	log.Println(msg)
34
+}
35
+
36
+func main() {
37
+	// webhooks.DefaultLog=webhooks.NewLogger(true)
38
+	//
39
+	// or override with your own
40
+	webhooks.DefaultLog = &myLogger{PrintDebugs: true}
41
+
42
+	hook := github.New(&github.Config{Secret: "MyGitHubSuperSecretSecrect...?"})
43
+	hook.RegisterEvents(HandleMultiple, github.ReleaseEvent, github.PullRequestEvent) // Add as many as you want
44
+
45
+	err := webhooks.Run(hook, ":"+strconv.Itoa(port), path)
46
+	if err != nil {
47
+		fmt.Println(err)
48
+	}
49
+}
50
+
51
+// HandleMultiple handles multiple GitHub events
52
+func HandleMultiple(payload interface{}, header webhooks.Header) {
53
+	fmt.Println("Handling Payload..")
54
+
55
+	switch payload.(type) {
56
+
57
+	case github.ReleasePayload:
58
+		release := payload.(github.ReleasePayload)
59
+		// Do whatever you want from here...
60
+		fmt.Printf("%+v", release)
61
+
62
+	case github.PullRequestPayload:
63
+		pullRequest := payload.(github.PullRequestPayload)
64
+		// Do whatever you want from here...
65
+		fmt.Printf("%+v", pullRequest)
66
+	}
67
+}

+ 51
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/examples/multiple-handlers/main.go Целия файл

@@ -0,0 +1,51 @@
1
+package main
2
+
3
+import (
4
+	"fmt"
5
+	"strconv"
6
+
7
+	"gopkg.in/go-playground/webhooks.v3"
8
+	"gopkg.in/go-playground/webhooks.v3/github"
9
+)
10
+
11
+const (
12
+	path = "/webhooks"
13
+	port = 3016
14
+)
15
+
16
+func main() {
17
+	hook := github.New(&github.Config{Secret: "MyGitHubSuperSecretSecrect...?"})
18
+	hook.RegisterEvents(HandleRelease, github.ReleaseEvent)
19
+	hook.RegisterEvents(HandlePullRequest, github.PullRequestEvent)
20
+
21
+	err := webhooks.Run(hook, ":"+strconv.Itoa(port), path)
22
+	if err != nil {
23
+		fmt.Println(err)
24
+	}
25
+}
26
+
27
+// HandleRelease handles GitHub release events
28
+func HandleRelease(payload interface{}, header webhooks.Header) {
29
+	fmt.Println("Handling Release")
30
+
31
+	pl := payload.(github.ReleasePayload)
32
+
33
+	// only want to compile on full releases
34
+	if pl.Release.Draft || pl.Release.Prerelease || pl.Release.TargetCommitish != "master" {
35
+		return
36
+	}
37
+
38
+	// Do whatever you want from here...
39
+	fmt.Printf("%+v", pl)
40
+}
41
+
42
+// HandlePullRequest handles GitHub pull_request events
43
+func HandlePullRequest(payload interface{}, header webhooks.Header) {
44
+
45
+	fmt.Println("Handling Pull Request")
46
+
47
+	pl := payload.(github.PullRequestPayload)
48
+
49
+	// Do whatever you want from here...
50
+	fmt.Printf("%+v", pl)
51
+}

+ 42
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/examples/single-handler/main.go Целия файл

@@ -0,0 +1,42 @@
1
+package main
2
+
3
+import (
4
+	"fmt"
5
+	"strconv"
6
+
7
+	"gopkg.in/go-playground/webhooks.v3"
8
+	"gopkg.in/go-playground/webhooks.v3/github"
9
+)
10
+
11
+const (
12
+	path = "/webhooks"
13
+	port = 3016
14
+)
15
+
16
+func main() {
17
+	hook := github.New(&github.Config{Secret: "MyGitHubSuperSecretSecrect...?"})
18
+	hook.RegisterEvents(HandleMultiple, github.ReleaseEvent, github.PullRequestEvent) // Add as many as you want
19
+
20
+	err := webhooks.Run(hook, ":"+strconv.Itoa(port), path)
21
+	if err != nil {
22
+		fmt.Println(err)
23
+	}
24
+}
25
+
26
+// HandleMultiple handles multiple GitHub events
27
+func HandleMultiple(payload interface{}, header webhooks.Header) {
28
+	fmt.Println("Handling Payload..")
29
+
30
+	switch payload.(type) {
31
+
32
+	case github.ReleasePayload:
33
+		release := payload.(github.ReleasePayload)
34
+		// Do whatever you want from here...
35
+		fmt.Printf("%+v", release)
36
+
37
+	case github.PullRequestPayload:
38
+		pullRequest := payload.(github.PullRequestPayload)
39
+		// Do whatever you want from here...
40
+		fmt.Printf("%+v", pullRequest)
41
+	}
42
+}

+ 281
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/github/github.go Целия файл

@@ -0,0 +1,281 @@
1
+package github
2
+
3
+import (
4
+	"crypto/hmac"
5
+	"crypto/sha1"
6
+	"encoding/hex"
7
+	"encoding/json"
8
+	"fmt"
9
+	"io/ioutil"
10
+	"net/http"
11
+
12
+	"gopkg.in/go-playground/webhooks.v3"
13
+)
14
+
15
+// Webhook instance contains all methods needed to process events
16
+type Webhook struct {
17
+	provider   webhooks.Provider
18
+	secret     string
19
+	eventFuncs map[Event]webhooks.ProcessPayloadFunc
20
+}
21
+
22
+// Config defines the configuration to create a new GitHub Webhook instance
23
+type Config struct {
24
+	Secret string
25
+}
26
+
27
+// Event defines a GitHub hook event type
28
+type Event string
29
+
30
+// GitHub hook types
31
+const (
32
+	CommitCommentEvent            Event = "commit_comment"
33
+	CreateEvent                   Event = "create"
34
+	DeleteEvent                   Event = "delete"
35
+	DeploymentEvent               Event = "deployment"
36
+	DeploymentStatusEvent         Event = "deployment_status"
37
+	ForkEvent                     Event = "fork"
38
+	GollumEvent                   Event = "gollum"
39
+	IssueCommentEvent             Event = "issue_comment"
40
+	IssuesEvent                   Event = "issues"
41
+	LabelEvent                    Event = "label"
42
+	MemberEvent                   Event = "member"
43
+	MembershipEvent               Event = "membership"
44
+	MilestoneEvent                Event = "milestone"
45
+	OrganizationEvent             Event = "organization"
46
+	OrgBlockEvent                 Event = "org_block"
47
+	PageBuildEvent                Event = "page_build"
48
+	ProjectCardEvent              Event = "project_card"
49
+	ProjectColumnEvent            Event = "project_column"
50
+	ProjectEvent                  Event = "project"
51
+	PublicEvent                   Event = "public"
52
+	PullRequestEvent              Event = "pull_request"
53
+	PullRequestReviewEvent        Event = "pull_request_review"
54
+	PullRequestReviewCommentEvent Event = "pull_request_review_comment"
55
+	PushEvent                     Event = "push"
56
+	ReleaseEvent                  Event = "release"
57
+	RepositoryEvent               Event = "repository"
58
+	StatusEvent                   Event = "status"
59
+	TeamEvent                     Event = "team"
60
+	TeamAddEvent                  Event = "team_add"
61
+	WatchEvent                    Event = "watch"
62
+)
63
+
64
+// EventSubtype defines a GitHub Hook Event subtype
65
+type EventSubtype string
66
+
67
+// GitHub hook event subtypes
68
+const (
69
+	NoSubtype     EventSubtype = ""
70
+	BranchSubtype EventSubtype = "branch"
71
+	TagSubtype    EventSubtype = "tag"
72
+	PullSubtype   EventSubtype = "pull"
73
+	IssueSubtype  EventSubtype = "issues"
74
+)
75
+
76
+// New creates and returns a WebHook instance denoted by the Provider type
77
+func New(config *Config) *Webhook {
78
+	return &Webhook{
79
+		provider:   webhooks.GitHub,
80
+		secret:     config.Secret,
81
+		eventFuncs: map[Event]webhooks.ProcessPayloadFunc{},
82
+	}
83
+}
84
+
85
+// Provider returns the current hooks provider ID
86
+func (hook Webhook) Provider() webhooks.Provider {
87
+	return hook.provider
88
+}
89
+
90
+// RegisterEvents registers the function to call when the specified event(s) are encountered
91
+func (hook Webhook) RegisterEvents(fn webhooks.ProcessPayloadFunc, events ...Event) {
92
+
93
+	for _, event := range events {
94
+		hook.eventFuncs[event] = fn
95
+	}
96
+}
97
+
98
+// ParsePayload parses and verifies the payload and fires off the mapped function, if it exists.
99
+func (hook Webhook) ParsePayload(w http.ResponseWriter, r *http.Request) {
100
+	webhooks.DefaultLog.Info("Parsing Payload...")
101
+
102
+	event := r.Header.Get("X-GitHub-Event")
103
+	if len(event) == 0 {
104
+		webhooks.DefaultLog.Error("Missing X-GitHub-Event Header")
105
+		http.Error(w, "400 Bad Request - Missing X-GitHub-Event Header", http.StatusBadRequest)
106
+		return
107
+	}
108
+	webhooks.DefaultLog.Debug(fmt.Sprintf("X-GitHub-Event:%s", event))
109
+
110
+	gitHubEvent := Event(event)
111
+
112
+	fn, ok := hook.eventFuncs[gitHubEvent]
113
+	// if no event registered
114
+	if !ok {
115
+		webhooks.DefaultLog.Info(fmt.Sprintf("Webhook Event %s not registered, it is recommended to setup only events in github that will be registered in the webhook to avoid unnecessary traffic and reduce potential attack vectors.", event))
116
+		return
117
+	}
118
+
119
+	payload, err := ioutil.ReadAll(r.Body)
120
+	if err != nil || len(payload) == 0 {
121
+		webhooks.DefaultLog.Error("Issue reading Payload")
122
+		http.Error(w, "Issue reading Payload", http.StatusInternalServerError)
123
+		return
124
+	}
125
+	webhooks.DefaultLog.Debug(fmt.Sprintf("Payload:%s", string(payload)))
126
+
127
+	// If we have a Secret set, we should check the MAC
128
+	if len(hook.secret) > 0 {
129
+		webhooks.DefaultLog.Info("Checking secret")
130
+		signature := r.Header.Get("X-Hub-Signature")
131
+		if len(signature) == 0 {
132
+			webhooks.DefaultLog.Error("Missing X-Hub-Signature required for HMAC verification")
133
+			http.Error(w, "403 Forbidden - Missing X-Hub-Signature required for HMAC verification", http.StatusForbidden)
134
+			return
135
+		}
136
+		webhooks.DefaultLog.Debug(fmt.Sprintf("X-Hub-Signature:%s", signature))
137
+
138
+		mac := hmac.New(sha1.New, []byte(hook.secret))
139
+		mac.Write(payload)
140
+
141
+		expectedMAC := hex.EncodeToString(mac.Sum(nil))
142
+
143
+		if !hmac.Equal([]byte(signature[5:]), []byte(expectedMAC)) {
144
+			webhooks.DefaultLog.Error("HMAC verification failed")
145
+			http.Error(w, "403 Forbidden - HMAC verification failed", http.StatusForbidden)
146
+			return
147
+		}
148
+	}
149
+
150
+	// Make headers available to ProcessPayloadFunc as a webhooks type
151
+	hd := webhooks.Header(r.Header)
152
+
153
+	switch gitHubEvent {
154
+	case CommitCommentEvent:
155
+		var cc CommitCommentPayload
156
+		json.Unmarshal([]byte(payload), &cc)
157
+		hook.runProcessPayloadFunc(fn, cc, hd)
158
+	case CreateEvent:
159
+		var c CreatePayload
160
+		json.Unmarshal([]byte(payload), &c)
161
+		hook.runProcessPayloadFunc(fn, c, hd)
162
+	case DeleteEvent:
163
+		var d DeletePayload
164
+		json.Unmarshal([]byte(payload), &d)
165
+		hook.runProcessPayloadFunc(fn, d, hd)
166
+	case DeploymentEvent:
167
+		var d DeploymentPayload
168
+		json.Unmarshal([]byte(payload), &d)
169
+		hook.runProcessPayloadFunc(fn, d, hd)
170
+	case DeploymentStatusEvent:
171
+		var d DeploymentStatusPayload
172
+		json.Unmarshal([]byte(payload), &d)
173
+		hook.runProcessPayloadFunc(fn, d, hd)
174
+	case ForkEvent:
175
+		var f ForkPayload
176
+		json.Unmarshal([]byte(payload), &f)
177
+		hook.runProcessPayloadFunc(fn, f, hd)
178
+	case GollumEvent:
179
+		var g GollumPayload
180
+		json.Unmarshal([]byte(payload), &g)
181
+		hook.runProcessPayloadFunc(fn, g, hd)
182
+	case IssueCommentEvent:
183
+		var i IssueCommentPayload
184
+		json.Unmarshal([]byte(payload), &i)
185
+		hook.runProcessPayloadFunc(fn, i, hd)
186
+	case IssuesEvent:
187
+		var i IssuesPayload
188
+		json.Unmarshal([]byte(payload), &i)
189
+		hook.runProcessPayloadFunc(fn, i, hd)
190
+	case LabelEvent:
191
+		var l LabelPayload
192
+		json.Unmarshal([]byte(payload), &l)
193
+		hook.runProcessPayloadFunc(fn, l, hd)
194
+	case MemberEvent:
195
+		var m MemberPayload
196
+		json.Unmarshal([]byte(payload), &m)
197
+		hook.runProcessPayloadFunc(fn, m, hd)
198
+	case MembershipEvent:
199
+		var m MembershipPayload
200
+		json.Unmarshal([]byte(payload), &m)
201
+		hook.runProcessPayloadFunc(fn, m, hd)
202
+	case MilestoneEvent:
203
+		var m MilestonePayload
204
+		json.Unmarshal([]byte(payload), &m)
205
+		hook.runProcessPayloadFunc(fn, m, hd)
206
+	case OrganizationEvent:
207
+		var o OrganizationPayload
208
+		json.Unmarshal([]byte(payload), &o)
209
+		hook.runProcessPayloadFunc(fn, o, hd)
210
+	case OrgBlockEvent:
211
+		var o OrgBlockPayload
212
+		json.Unmarshal([]byte(payload), &o)
213
+		hook.runProcessPayloadFunc(fn, o, hd)
214
+	case PageBuildEvent:
215
+		var p PageBuildPayload
216
+		json.Unmarshal([]byte(payload), &p)
217
+		hook.runProcessPayloadFunc(fn, p, hd)
218
+	case ProjectCardEvent:
219
+		var p ProjectCardPayload
220
+		json.Unmarshal([]byte(payload), &p)
221
+		hook.runProcessPayloadFunc(fn, p, hd)
222
+	case ProjectColumnEvent:
223
+		var p ProjectColumnPayload
224
+		json.Unmarshal([]byte(payload), &p)
225
+		hook.runProcessPayloadFunc(fn, p, hd)
226
+	case ProjectEvent:
227
+		var p ProjectPayload
228
+		json.Unmarshal([]byte(payload), &p)
229
+		hook.runProcessPayloadFunc(fn, p, hd)
230
+	case PublicEvent:
231
+		var p PublicPayload
232
+		json.Unmarshal([]byte(payload), &p)
233
+		hook.runProcessPayloadFunc(fn, p, hd)
234
+	case PullRequestEvent:
235
+		var p PullRequestPayload
236
+		json.Unmarshal([]byte(payload), &p)
237
+		hook.runProcessPayloadFunc(fn, p, hd)
238
+	case PullRequestReviewEvent:
239
+		var p PullRequestReviewPayload
240
+		json.Unmarshal([]byte(payload), &p)
241
+		hook.runProcessPayloadFunc(fn, p, hd)
242
+	case PullRequestReviewCommentEvent:
243
+		var p PullRequestReviewCommentPayload
244
+		json.Unmarshal([]byte(payload), &p)
245
+		hook.runProcessPayloadFunc(fn, p, hd)
246
+	case PushEvent:
247
+		var p PushPayload
248
+		json.Unmarshal([]byte(payload), &p)
249
+		hook.runProcessPayloadFunc(fn, p, hd)
250
+	case ReleaseEvent:
251
+		var r ReleasePayload
252
+		json.Unmarshal([]byte(payload), &r)
253
+		hook.runProcessPayloadFunc(fn, r, hd)
254
+	case RepositoryEvent:
255
+		var r RepositoryPayload
256
+		json.Unmarshal([]byte(payload), &r)
257
+		hook.runProcessPayloadFunc(fn, r, hd)
258
+	case StatusEvent:
259
+		var s StatusPayload
260
+		json.Unmarshal([]byte(payload), &s)
261
+		hook.runProcessPayloadFunc(fn, s, hd)
262
+	case TeamEvent:
263
+		var t TeamPayload
264
+		json.Unmarshal([]byte(payload), &t)
265
+		hook.runProcessPayloadFunc(fn, t, hd)
266
+	case TeamAddEvent:
267
+		var t TeamAddPayload
268
+		json.Unmarshal([]byte(payload), &t)
269
+		hook.runProcessPayloadFunc(fn, t, hd)
270
+	case WatchEvent:
271
+		var w WatchPayload
272
+		json.Unmarshal([]byte(payload), &w)
273
+		hook.runProcessPayloadFunc(fn, w, hd)
274
+	}
275
+}
276
+
277
+func (hook Webhook) runProcessPayloadFunc(fn webhooks.ProcessPayloadFunc, results interface{}, header webhooks.Header) {
278
+	go func(fn webhooks.ProcessPayloadFunc, results interface{}, header webhooks.Header) {
279
+		fn(results, header)
280
+	}(fn, results, header)
281
+}

+ 5596
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/github/github_test.go
Файловите разлики са ограничени, защото са твърде много
Целия файл


+ 4972
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/github/payload.go
Файловите разлики са ограничени, защото са твърде много
Целия файл


+ 157
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/gitlab/gitlab.go Целия файл

@@ -0,0 +1,157 @@
1
+package gitlab
2
+
3
+import (
4
+	"encoding/json"
5
+	"fmt"
6
+	"io/ioutil"
7
+	"net/http"
8
+
9
+	"gopkg.in/go-playground/webhooks.v3"
10
+)
11
+
12
+// Webhook instance contains all methods needed to process events
13
+type Webhook struct {
14
+	provider   webhooks.Provider
15
+	secret     string
16
+	eventFuncs map[Event]webhooks.ProcessPayloadFunc
17
+}
18
+
19
+// Config defines the configuration to create a new GitHub Webhook instance
20
+type Config struct {
21
+	Secret string
22
+}
23
+
24
+// Event defines a GitHub hook event type
25
+type Event string
26
+
27
+// GitLab hook types
28
+const (
29
+	PushEvents               Event = "Push Hook"
30
+	TagEvents                Event = "Tag Push Hook"
31
+	IssuesEvents             Event = "Issue Hook"
32
+	ConfidentialIssuesEvents Event = "Confidential Issue Hook"
33
+	CommentEvents            Event = "Note Hook"
34
+	MergeRequestEvents       Event = "Merge Request Hook"
35
+	WikiPageEvents           Event = "Wiki Page Hook"
36
+	PipelineEvents           Event = "Pipeline Hook"
37
+	BuildEvents              Event = "Build Hook"
38
+)
39
+
40
+// New creates and returns a WebHook instance denoted by the Provider type
41
+func New(config *Config) *Webhook {
42
+	return &Webhook{
43
+		provider:   webhooks.GitLab,
44
+		secret:     config.Secret,
45
+		eventFuncs: map[Event]webhooks.ProcessPayloadFunc{},
46
+	}
47
+}
48
+
49
+// Provider returns the current hooks provider ID
50
+func (hook Webhook) Provider() webhooks.Provider {
51
+	return hook.provider
52
+}
53
+
54
+// RegisterEvents registers the function to call when the specified event(s) are encountered
55
+func (hook Webhook) RegisterEvents(fn webhooks.ProcessPayloadFunc, events ...Event) {
56
+
57
+	for _, event := range events {
58
+		hook.eventFuncs[event] = fn
59
+	}
60
+}
61
+
62
+// ParsePayload parses and verifies the payload and fires off the mapped function, if it exists.
63
+func (hook Webhook) ParsePayload(w http.ResponseWriter, r *http.Request) {
64
+	webhooks.DefaultLog.Info("Parsing Payload...")
65
+
66
+	event := r.Header.Get("X-Gitlab-Event")
67
+	if len(event) == 0 {
68
+		webhooks.DefaultLog.Error("Missing X-Gitlab-Event Header")
69
+		http.Error(w, "400 Bad Request - Missing X-Gitlab-Event Header", http.StatusBadRequest)
70
+		return
71
+	}
72
+	webhooks.DefaultLog.Debug(fmt.Sprintf("X-Gitlab-Event:%s", event))
73
+
74
+	gitLabEvent := Event(event)
75
+
76
+	fn, ok := hook.eventFuncs[gitLabEvent]
77
+	// if no event registered
78
+	if !ok {
79
+		webhooks.DefaultLog.Info(fmt.Sprintf("Webhook Event %s not registered, it is recommended to setup only events in gitlab that will be registered in the webhook to avoid unnecessary traffic and reduce potential attack vectors.", event))
80
+		return
81
+	}
82
+
83
+	payload, err := ioutil.ReadAll(r.Body)
84
+	if err != nil || len(payload) == 0 {
85
+		webhooks.DefaultLog.Error("Issue reading Payload")
86
+		http.Error(w, "Error reading Payload", http.StatusInternalServerError)
87
+		return
88
+	}
89
+	webhooks.DefaultLog.Debug(fmt.Sprintf("Payload:%s", string(payload)))
90
+
91
+	// If we have a Secret set, we should check the MAC
92
+	if len(hook.secret) > 0 {
93
+		webhooks.DefaultLog.Info("Checking secret")
94
+		signature := r.Header.Get("X-Gitlab-Token")
95
+		if signature != hook.secret {
96
+			webhooks.DefaultLog.Error(fmt.Sprintf("Invalid X-Gitlab-Token of '%s'", signature))
97
+			http.Error(w, "403 Forbidden - Token missmatch", http.StatusForbidden)
98
+			return
99
+		}
100
+	}
101
+
102
+	// Make headers available to ProcessPayloadFunc as a webhooks type
103
+	hd := webhooks.Header(r.Header)
104
+
105
+	switch gitLabEvent {
106
+	case PushEvents:
107
+		var pe PushEventPayload
108
+		json.Unmarshal([]byte(payload), &pe)
109
+		hook.runProcessPayloadFunc(fn, pe, hd)
110
+
111
+	case TagEvents:
112
+		var te TagEventPayload
113
+		json.Unmarshal([]byte(payload), &te)
114
+		hook.runProcessPayloadFunc(fn, te, hd)
115
+
116
+	case ConfidentialIssuesEvents:
117
+		var cie ConfidentialIssueEventPayload
118
+		json.Unmarshal([]byte(payload), &cie)
119
+		hook.runProcessPayloadFunc(fn, cie, hd)
120
+
121
+	case IssuesEvents:
122
+		var ie IssueEventPayload
123
+		json.Unmarshal([]byte(payload), &ie)
124
+		hook.runProcessPayloadFunc(fn, ie, hd)
125
+
126
+	case CommentEvents:
127
+		var ce CommentEventPayload
128
+		json.Unmarshal([]byte(payload), &ce)
129
+		hook.runProcessPayloadFunc(fn, ce, hd)
130
+
131
+	case MergeRequestEvents:
132
+		var mre MergeRequestEventPayload
133
+		json.Unmarshal([]byte(payload), &mre)
134
+		hook.runProcessPayloadFunc(fn, mre, hd)
135
+
136
+	case WikiPageEvents:
137
+		var wpe WikiPageEventPayload
138
+		json.Unmarshal([]byte(payload), &wpe)
139
+		hook.runProcessPayloadFunc(fn, wpe, hd)
140
+
141
+	case PipelineEvents:
142
+		var pe PipelineEventPayload
143
+		json.Unmarshal([]byte(payload), &pe)
144
+		hook.runProcessPayloadFunc(fn, pe, hd)
145
+
146
+	case BuildEvents:
147
+		var be BuildEventPayload
148
+		json.Unmarshal([]byte(payload), &be)
149
+		hook.runProcessPayloadFunc(fn, be, hd)
150
+	}
151
+}
152
+
153
+func (hook Webhook) runProcessPayloadFunc(fn webhooks.ProcessPayloadFunc, results interface{}, header webhooks.Header) {
154
+	go func(fn webhooks.ProcessPayloadFunc, results interface{}, header webhooks.Header) {
155
+		fn(results, header)
156
+	}(fn, results, header)
157
+}

+ 1197
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/gitlab/gitlab_test.go
Файловите разлики са ограничени, защото са твърде много
Целия файл


+ 438
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/gitlab/payload.go Целия файл

@@ -0,0 +1,438 @@
1
+package gitlab
2
+
3
+import (
4
+	"strings"
5
+	"time"
6
+)
7
+
8
+type customTime struct {
9
+	time.Time
10
+}
11
+
12
+func (t *customTime) UnmarshalJSON(b []byte) (err error) {
13
+	layout := []string{
14
+		"2006-01-02 15:04:05 MST",
15
+		"2006-01-02 15:04:05 Z07:00",
16
+		"2006-01-02 15:04:05 Z0700",
17
+		time.RFC3339,
18
+	}
19
+	s := strings.Trim(string(b), "\"")
20
+	if s == "null" {
21
+		t.Time = time.Time{}
22
+		return
23
+	}
24
+	for _, l := range layout {
25
+		t.Time, err = time.Parse(l, s)
26
+		if err == nil {
27
+			break
28
+		}
29
+	}
30
+	return
31
+}
32
+
33
+// IssueEventPayload contains the information for GitLab's issue event
34
+type IssueEventPayload struct {
35
+	ObjectKind       string           `json:"object_kind"`
36
+	User             User             `json:"user"`
37
+	Project          Project          `json:"project"`
38
+	Repository       Repository       `json:"repository"`
39
+	ObjectAttributes ObjectAttributes `json:"object_attributes"`
40
+	Assignee         Assignee         `json:"assignee"`
41
+	Changes          Changes          `json:"changes"`
42
+}
43
+
44
+// ConfidentialIssueEventPayload contains the information for GitLab's confidential issue event
45
+type ConfidentialIssueEventPayload struct {
46
+	// The data for confidential issues is currently the same as normal issues,
47
+	// so we can just embed the normal issue payload type here.
48
+	IssueEventPayload
49
+}
50
+
51
+// MergeRequestEventPayload contains the information for GitLab's merge request event
52
+type MergeRequestEventPayload struct {
53
+	ObjectKind       string           `json:"object_kind"`
54
+	User             User             `json:"user"`
55
+	ObjectAttributes ObjectAttributes `json:"object_attributes"`
56
+	Changes          Changes          `json:"changes"`
57
+}
58
+
59
+// PushEventPayload contains the information for GitLab's push event
60
+type PushEventPayload struct {
61
+	ObjectKind        string     `json:"object_kind"`
62
+	Before            string     `json:"before"`
63
+	After             string     `json:"after"`
64
+	Ref               string     `json:"ref"`
65
+	CheckoutSHA       string     `json:"checkout_sha"`
66
+	UserID            int64      `json:"user_id"`
67
+	UserName          string     `json:"user_name"`
68
+	UserEmail         string     `json:"user_email"`
69
+	UserAvatar        string     `json:"user_avatar"`
70
+	ProjectID         int64      `json:"project_id"`
71
+	Project           Project    `json:"Project"`
72
+	Repository        Repository `json:"repository"`
73
+	Commits           []Commit   `json:"commits"`
74
+	TotalCommitsCount int64      `json:"total_commits_count"`
75
+}
76
+
77
+// TagEventPayload contains the information for GitLab's tag push event
78
+type TagEventPayload struct {
79
+	ObjectKind        string     `json:"object_kind"`
80
+	Before            string     `json:"before"`
81
+	After             string     `json:"after"`
82
+	Ref               string     `json:"ref"`
83
+	CheckoutSHA       string     `json:"checkout_sha"`
84
+	UserID            int64      `json:"user_id"`
85
+	UserName          string     `json:"user_name"`
86
+	UserAvatar        string     `json:"user_avatar"`
87
+	ProjectID         int64      `json:"project_id"`
88
+	Project           Project    `json:"Project"`
89
+	Repository        Repository `json:"repository"`
90
+	Commits           []Commit   `json:"commits"`
91
+	TotalCommitsCount int64      `json:"total_commits_count"`
92
+}
93
+
94
+// WikiPageEventPayload contains the information for GitLab's wiki created/updated event
95
+type WikiPageEventPayload struct {
96
+	ObjectKind       string           `json:"object_kind"`
97
+	User             User             `json:"user"`
98
+	Project          Project          `json:"project"`
99
+	Wiki             Wiki             `json:"wiki"`
100
+	ObjectAttributes ObjectAttributes `json:"object_attributes"`
101
+}
102
+
103
+// PipelineEventPayload contains the information for GitLab's pipeline status change event
104
+type PipelineEventPayload struct {
105
+	ObjectKind       string           `json:"object_kind"`
106
+	User             User             `json:"user"`
107
+	Project          Project          `json:"project"`
108
+	Commit           Commit           `json:"commit"`
109
+	ObjectAttributes ObjectAttributes `json:"object_attributes"`
110
+	Builds           []Build          `json:"builds"`
111
+}
112
+
113
+// CommentEventPayload contains the information for GitLab's comment event
114
+type CommentEventPayload struct {
115
+	ObjectKind       string           `json:"object_kind"`
116
+	User             User             `json:"user"`
117
+	ProjectID        int64            `json:"project_id"`
118
+	Project          Project          `json:"project"`
119
+	Repository       Repository       `json:"repository"`
120
+	ObjectAttributes ObjectAttributes `json:"object_attributes"`
121
+	MergeRequest     MergeRequest     `json:"merge_request"`
122
+	Commit           Commit           `json:"commit"`
123
+	Issue            Issue            `json:"issue"`
124
+	Snippet          Snippet          `json:"snippet"`
125
+}
126
+
127
+// BuildEventPayload contains the information for GitLab's build status change event
128
+type BuildEventPayload struct {
129
+	ObjectKind        string      `json:"object_kind"`
130
+	Ref               string      `json:"ref"`
131
+	Tag               bool        `json:"tag"`
132
+	BeforeSHA         string      `json:"before_sha"`
133
+	SHA               string      `json:"sha"`
134
+	BuildID           int64       `json:"build_id"`
135
+	BuildName         string      `json:"build_name"`
136
+	BuildStage        string      `json:"build_stage"`
137
+	BuildStatus       string      `json:"build_status"`
138
+	BuildStartedAt    customTime  `json:"build_started_at"`
139
+	BuildFinishedAt   customTime  `json:"build_finished_at"`
140
+	BuildDuration     int64       `json:"build_duration"`
141
+	BuildAllowFailure bool        `json:"build_allow_failure"`
142
+	ProjectID         int64       `json:"project_id"`
143
+	ProjectName       string      `json:"project_name"`
144
+	User              User        `json:"user"`
145
+	Commit            BuildCommit `json:"commit"`
146
+	Repository        Repository  `json:"repository"`
147
+}
148
+
149
+// Issue contains all of the GitLab issue information
150
+type Issue struct {
151
+	ID          int64      `json:"id"`
152
+	Title       string     `json:"title"`
153
+	AssigneeID  int64      `json:"assignee_id"`
154
+	AuthorID    int64      `json:"author_id"`
155
+	ProjectID   int64      `json:"project_id"`
156
+	CreatedAt   customTime `json:"created_at"`
157
+	UpdatedAt   customTime `json:"updated_at"`
158
+	Position    int64      `json:"position"`
159
+	BranchName  string     `json:"branch_name"`
160
+	Description string     `json:"description"`
161
+	MilestoneID int64      `json:"milestone_id"`
162
+	State       string     `json:"state"`
163
+	IID         int64      `json:"iid"`
164
+}
165
+
166
+// Build contains all of the GitLab build information
167
+type Build struct {
168
+	ID            int64         `json:"id"`
169
+	Stage         string        `json:"stage"`
170
+	Name          string        `json:"name"`
171
+	Status        string        `json:"status"`
172
+	CreatedAt     customTime    `json:"created_at"`
173
+	StartedAt     customTime    `json:"started_at"`
174
+	FinishedAt    customTime    `json:"finished_at"`
175
+	When          string        `json:"when"`
176
+	Manual        bool          `json:"manual"`
177
+	User          User          `json:"user"`
178
+	Runner        string        `json:"runner"`
179
+	ArtifactsFile ArtifactsFile `json:"artifactsfile"`
180
+}
181
+
182
+// ArtifactsFile contains all of the GitLab artifact information
183
+type ArtifactsFile struct {
184
+	Filename string `json:"filename"`
185
+	Size     string `json:"size"`
186
+}
187
+
188
+// Wiki contains all of the GitLab wiki information
189
+type Wiki struct {
190
+	WebURL            string `json:"web_url"`
191
+	GitSSHURL         string `json:"git_ssh_url"`
192
+	GitHTTPURL        string `json:"git_http_url"`
193
+	PathWithNamespace string `json:"path_with_namespace"`
194
+	DefaultBranch     string `json:"default_branch"`
195
+}
196
+
197
+// Commit contains all of the GitLab commit information
198
+type Commit struct {
199
+	ID        string     `json:"id"`
200
+	Message   string     `json:"message"`
201
+	Timestamp customTime `json:"timestamp"`
202
+	URL       string     `json:"url"`
203
+	Author    Author     `json:"author"`
204
+	Added     []string   `json:"added"`
205
+	Modified  []string   `json:"modified"`
206
+	Removed   []string   `json:"removed"`
207
+}
208
+
209
+// BuildCommit contains all of the GitLab build commit information
210
+type BuildCommit struct {
211
+	ID          int64      `json:"id"`
212
+	SHA         string     `json:"sha"`
213
+	Message     string     `json:"message"`
214
+	AuthorName  string     `json:"auuthor_name"`
215
+	AuthorEmail string     `json:"author_email"`
216
+	Status      string     `json:"status"`
217
+	Duration    int64      `json:"duration"`
218
+	StartedAt   customTime `json:"started_at"`
219
+	FinishedAt  customTime `json:"finished_at"`
220
+}
221
+
222
+// Snippet contains all of the GitLab snippet information
223
+type Snippet struct {
224
+	ID              int64      `json:"id"`
225
+	Title           string     `json:"title"`
226
+	Content         string     `json:"content"`
227
+	AuthorID        int64      `json:"author_id"`
228
+	ProjectID       int64      `json:"project_id"`
229
+	CreatedAt       customTime `json:"created_at"`
230
+	UpdatedAt       customTime `json:"updated_at"`
231
+	FileName        string     `json:"file_name"`
232
+	ExpiresAt       customTime `json:"expires_at"`
233
+	Type            string     `json:"type"`
234
+	VisibilityLevel int64      `json:"visibility_level"`
235
+}
236
+
237
+// User contains all of the GitLab user information
238
+type User struct {
239
+	Name      string `json:"name"`
240
+	UserName  string `json:"username"`
241
+	AvatarURL string `json:"avatar_url"`
242
+}
243
+
244
+// Project contains all of the GitLab project information
245
+type Project struct {
246
+	Name              string `json:"name"`
247
+	Description       string `json:"description"`
248
+	WebURL            string `json:"web_url"`
249
+	AvatarURL         string `json:"avatar_url"`
250
+	GitSSSHURL        string `json:"git_ssh_url"`
251
+	GitHTTPURL        string `json:"git_http_url"`
252
+	Namespace         string `json:"namespace"`
253
+	VisibilityLevel   int64  `json:"visibility_level"`
254
+	PathWithNamespace string `json:"path_with_namespace"`
255
+	DefaultBranch     string `json:"default_branch"`
256
+	Homepage          string `json:"homepage"`
257
+	URL               string `json:"url"`
258
+	SSHURL            string `json:"ssh_url"`
259
+	HTTPURL           string `json:"http_url"`
260
+}
261
+
262
+// Repository contains all of the GitLab repository information
263
+type Repository struct {
264
+	Name        string `json:"name"`
265
+	URL         string `json:"url"`
266
+	Description string `json:"description"`
267
+	Homepage    string `json:"homepage"`
268
+}
269
+
270
+// ObjectAttributes contains all of the GitLab object attributes information
271
+type ObjectAttributes struct {
272
+	ID              int64      `json:"id"`
273
+	Title           string     `json:"title"`
274
+	AssigneeID      int64      `json:"assignee_id"`
275
+	AuthorID        int64      `json:"author_id"`
276
+	ProjectID       int64      `json:"project_id"`
277
+	CreatedAt       customTime `json:"created_at"`
278
+	UpdatedAt       customTime `json:"updated_at"`
279
+	Position        int64      `json:"position"`
280
+	BranchName      string     `json:"branch_name"`
281
+	Description     string     `json:"description"`
282
+	MilestoneID     int64      `json:"milestone_id"`
283
+	State           string     `json:"state"`
284
+	IID             int64      `json:"iid"`
285
+	URL             string     `json:"url"`
286
+	Action          string     `json:"action"`
287
+	TargetBranch    string     `json:"target_branch"`
288
+	SourceBranch    string     `json:"source_branch"`
289
+	SourceProjectID int64      `json:"source_project_id"`
290
+	TargetProjectID int64      `json:"target_project_id"`
291
+	StCommits       string     `json:"st_commits"`
292
+	MergeStatus     string     `json:"merge_status"`
293
+	Content         string     `json:"content"`
294
+	Format          string     `json:"format"`
295
+	Message         string     `json:"message"`
296
+	Slug            string     `json:"slug"`
297
+	Ref             string     `json:"ref"`
298
+	Tag             bool       `json:"tag"`
299
+	SHA             string     `json:"sha"`
300
+	BeforeSHA       string     `json:"before_sha"`
301
+	Status          string     `json:"status"`
302
+	Stages          []string   `json:"stages"`
303
+	Duration        int64      `json:"duration"`
304
+	Note            string     `json:"note"`
305
+	NotebookType    string     `json:"noteable_type"`
306
+	At              customTime `json:"attachment"`
307
+	LineCode        string     `json:"line_code"`
308
+	CommitID        string     `json:"commit_id"`
309
+	NoteableID      int64      `json:"noteable_id"`
310
+	System          bool       `json:"system"`
311
+	WorkInProgress  bool       `json:"work_in_progress"`
312
+	StDiffs         []StDiff   `json:"st_diffs"`
313
+	Source          Source     `json:"source"`
314
+	Target          Target     `json:"target"`
315
+	LastCommit      LastCommit `json:"last_commit"`
316
+	Assignee        Assignee   `json:"assignee"`
317
+}
318
+
319
+// MergeRequest contains all of the GitLab merge request information
320
+type MergeRequest struct {
321
+	ID              int64      `json:"id"`
322
+	TargetBranch    string     `json:"target_branch"`
323
+	SourceBranch    string     `json:"source_branch"`
324
+	SourceProjectID int64      `json:"source_project_id"`
325
+	AssigneeID      int64      `json:"assignee_id"`
326
+	AuthorID        int64      `json:"author_id"`
327
+	Title           string     `json:"title"`
328
+	CreatedAt       customTime `json:"created_at"`
329
+	UpdatedAt       customTime `json:"updated_at"`
330
+	MilestoneID     int64      `json:"milestone_id"`
331
+	State           string     `json:"state"`
332
+	MergeStatus     string     `json:"merge_status"`
333
+	TargetProjectID int64      `json:"target_project_id"`
334
+	IID             int64      `json:"iid"`
335
+	Description     string     `json:"description"`
336
+	Position        int64      `json:"position"`
337
+	LockedAt        customTime `json:"locked_at"`
338
+	Source          Source     `json:"source"`
339
+	Target          Target     `json:"target"`
340
+	LastCommit      LastCommit `json:"last_commit"`
341
+	WorkInProgress  bool       `json:"work_in_progress"`
342
+	Assignee        Assignee   `json:"assignee"`
343
+}
344
+
345
+// Assignee contains all of the GitLab assignee information
346
+type Assignee struct {
347
+	Name      string `json:"name"`
348
+	Username  string `json:"username"`
349
+	AvatarURL string `json:"avatar_url"`
350
+}
351
+
352
+// StDiff contains all of the GitLab diff information
353
+type StDiff struct {
354
+	Diff        string `json:"diff"`
355
+	NewPath     string `json:"new_path"`
356
+	OldPath     string `json:"old_path"`
357
+	AMode       string `json:"a_mode"`
358
+	BMode       string `json:"b_mode"`
359
+	NewFile     bool   `json:"new_file"`
360
+	RenamedFile bool   `json:"renamed_file"`
361
+	DeletedFile bool   `json:"deleted_file"`
362
+}
363
+
364
+// Source contains all of the GitLab source information
365
+type Source struct {
366
+	Name              string `json:"name"`
367
+	Description       string `json:"description"`
368
+	WebURL            string `json:"web_url"`
369
+	AvatarURL         string `json:"avatar_url"`
370
+	GitSSHURL         string `json:"git_ssh_url"`
371
+	GitHTTPURL        string `json:"git_http_url"`
372
+	Namespace         string `json:"namespace"`
373
+	VisibilityLevel   int64  `json:"visibility_level"`
374
+	PathWithNamespace string `json:"path_with_namespace"`
375
+	DefaultBranch     string `json:"default_branch"`
376
+	Homepage          string `json:"homepage"`
377
+	URL               string `json:"url"`
378
+	SSHURL            string `json:"ssh_url"`
379
+	HTTPURL           string `json:"http_url"`
380
+}
381
+
382
+// Target contains all of the GitLab target information
383
+type Target struct {
384
+	Name              string `json:"name"`
385
+	Description       string `json:"description"`
386
+	WebURL            string `json:"web_url"`
387
+	AvatarURL         string `json:"avatar_url"`
388
+	GitSSHURL         string `json:"git_ssh_url"`
389
+	GitHTTPURL        string `json:"git_http_url"`
390
+	Namespace         string `json:"namespace"`
391
+	VisibilityLevel   int64  `json:"visibility_level"`
392
+	PathWithNamespace string `json:"path_with_namespace"`
393
+	DefaultBranch     string `json:"default_branch"`
394
+	Homepage          string `json:"homepage"`
395
+	URL               string `json:"url"`
396
+	SSHURL            string `json:"ssh_url"`
397
+	HTTPURL           string `json:"http_url"`
398
+}
399
+
400
+// LastCommit contains all of the GitLab last commit information
401
+type LastCommit struct {
402
+	ID        string     `json:"id"`
403
+	Message   string     `json:"message"`
404
+	Timestamp customTime `json:"timestamp"`
405
+	URL       string     `json:"url"`
406
+	Author    Author     `json:"author"`
407
+}
408
+
409
+// Author contains all of the GitLab author information
410
+type Author struct {
411
+	Name  string `json:"name"`
412
+	Email string `json:"email"`
413
+}
414
+
415
+// Changes contains all changes associated with a GitLab issue or MR
416
+type Changes struct {
417
+	LabelChanges LabelChanges `json:"labels"`
418
+}
419
+
420
+// LabelChanges contains changes in labels assocatiated with a GitLab issue or MR
421
+type LabelChanges struct {
422
+	Previous []Label `json:"previous"`
423
+	Current  []Label `json:"current"`
424
+}
425
+
426
+// Label contains all of the GitLab label information
427
+type Label struct {
428
+	Id          int64      `json:"id"`
429
+	Title       string     `json:"title"`
430
+	Color       string     `json:"color"`
431
+	ProjectId   int64      `json:"project_id"`
432
+	CreatedAt   customTime `json:"created_at"`
433
+	UpdatedAt   customTime `json:"updated_at"`
434
+	Template    bool       `json:"template"`
435
+	Description string     `json:"description"`
436
+	Type        string     `json:"type"`
437
+	GroupId     int64      `json:"group_id"`
438
+}

+ 44
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/logger.go Целия файл

@@ -0,0 +1,44 @@
1
+package webhooks
2
+
3
+import "log"
4
+
5
+// DefaultLog contains the default logger for webhooks, and prints only info and error messages by default
6
+// for debugs override DefaultLog or see NewLogger for creating one without debugs.
7
+var DefaultLog Logger = new(logger)
8
+
9
+// Logger allows for customizable logging
10
+type Logger interface {
11
+	// Info prints basic information.
12
+	Info(string)
13
+	// Error prints error information.
14
+	Error(string)
15
+	// Debug prints information usefull for debugging.
16
+	Debug(string)
17
+}
18
+
19
+// NewLogger returns a new logger for use.
20
+func NewLogger(debug bool) Logger {
21
+	return &logger{PrintDebugs: debug}
22
+}
23
+
24
+type logger struct {
25
+	PrintDebugs bool
26
+}
27
+
28
+// Info prints basic information.
29
+func (l *logger) Info(msg string) {
30
+	log.Println("INFO:", msg)
31
+}
32
+
33
+// v prints error information.
34
+func (l *logger) Error(msg string) {
35
+	log.Println("ERROR:", msg)
36
+}
37
+
38
+// Debug prints information usefull for debugging.
39
+func (l *logger) Debug(msg string) {
40
+	if !l.PrintDebugs {
41
+		return
42
+	}
43
+	log.Println("DEBUG:", msg)
44
+}

BIN
vendor/src/gopkg.in/go-playground/webhooks.v3/logo.png Целия файл


+ 121
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/webhooks.go Целия файл

@@ -0,0 +1,121 @@
1
+package webhooks
2
+
3
+import (
4
+	"fmt"
5
+	"net/http"
6
+)
7
+
8
+// Header provides http.Header to minimize imports
9
+type Header http.Header
10
+
11
+// Provider defines the type of webhook
12
+type Provider int
13
+
14
+func (p Provider) String() string {
15
+	switch p {
16
+	case GitHub:
17
+		return "GitHub"
18
+	case Bitbucket:
19
+		return "Bitbucket"
20
+	case GitLab:
21
+		return "GitLab"
22
+	default:
23
+		return "Unknown"
24
+	}
25
+}
26
+
27
+// webhooks available providers
28
+const (
29
+	GitHub Provider = iota
30
+	Bitbucket
31
+	GitLab
32
+)
33
+
34
+// Webhook interface defines a webhook to receive events
35
+type Webhook interface {
36
+	Provider() Provider
37
+	ParsePayload(w http.ResponseWriter, r *http.Request)
38
+}
39
+
40
+type server struct {
41
+	hook             Webhook
42
+	path             string
43
+	includePathCheck bool
44
+}
45
+
46
+// ProcessPayloadFunc is a common function for payload return values
47
+type ProcessPayloadFunc func(payload interface{}, header Header)
48
+
49
+// Handler returns the webhook http.Handler for use in your own Mux implementation
50
+func Handler(hook Webhook) http.Handler {
51
+	return &server{
52
+		hook: hook,
53
+	}
54
+}
55
+
56
+// Run runs a server
57
+func Run(hook Webhook, addr string, path string) error {
58
+	srv := &server{
59
+		hook:             hook,
60
+		path:             path,
61
+		includePathCheck: true,
62
+	}
63
+	s := &http.Server{Addr: addr, Handler: srv}
64
+
65
+	DefaultLog.Info(fmt.Sprintf("Listening on addr: %s path: %s", addr, path))
66
+	return s.ListenAndServe()
67
+}
68
+
69
+// RunServer runs a custom server.
70
+func RunServer(s *http.Server, hook Webhook, path string) error {
71
+
72
+	srv := &server{
73
+		hook:             hook,
74
+		path:             path,
75
+		includePathCheck: true,
76
+	}
77
+
78
+	s.Handler = srv
79
+	DefaultLog.Info(fmt.Sprintf("Listening on addr: %s path: %s", s.Addr, path))
80
+	return s.ListenAndServe()
81
+}
82
+
83
+// RunTLSServer runs a custom server with TLS configuration.
84
+// NOTE: http.Server Handler will be overridden by this library, just set it to nil.
85
+// Setting the Certificates can be done in the http.Server.TLSConfig.Certificates
86
+// see example here: https://github.com/go-playground/webhooks/blob/v2/webhooks_test.go#L178
87
+func RunTLSServer(s *http.Server, hook Webhook, path string) error {
88
+
89
+	srv := &server{
90
+		hook:             hook,
91
+		path:             path,
92
+		includePathCheck: true,
93
+	}
94
+
95
+	s.Handler = srv
96
+	DefaultLog.Info(fmt.Sprintf("Listening on addr: %s path: %s", s.Addr, path))
97
+	return s.ListenAndServeTLS("", "")
98
+}
99
+
100
+// ServeHTTP is the Handler for every posted WebHook Event
101
+func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
102
+	defer r.Body.Close()
103
+	DefaultLog.Info("Webhook received")
104
+
105
+	if r.Method != "POST" {
106
+		DefaultLog.Error(fmt.Sprintf("405 Method not allowed, attempt made using Method: %s", r.Method))
107
+		http.Error(w, "405 Method not allowed", http.StatusMethodNotAllowed)
108
+		return
109
+	}
110
+
111
+	DefaultLog.Debug(fmt.Sprintf("Include path check: %t", s.includePathCheck))
112
+	if s.includePathCheck {
113
+		if r.URL.Path != s.path {
114
+			DefaultLog.Error(fmt.Sprintf("404 Not found, POST made using path: %s, but expected %s", r.URL.Path, s.path))
115
+			http.Error(w, "404 Not found", http.StatusNotFound)
116
+			return
117
+		}
118
+	}
119
+
120
+	s.hook.ParsePayload(w, r)
121
+}

+ 280
- 0
vendor/src/gopkg.in/go-playground/webhooks.v3/webhooks_test.go Целия файл

@@ -0,0 +1,280 @@
1
+package webhooks
2
+
3
+import (
4
+	"bytes"
5
+	"crypto/tls"
6
+	"net/http"
7
+	"os"
8
+	"testing"
9
+	"time"
10
+
11
+	"net/http/httptest"
12
+
13
+	. "gopkg.in/go-playground/assert.v1"
14
+)
15
+
16
+// NOTES:
17
+// - Run "go test" to run tests
18
+// - Run "gocov test | gocov report" to report on test converage by file
19
+// - Run "gocov test | gocov annotate -" to report on all code and functions, those ,marked with "MISS" were never called
20
+//
21
+// or
22
+//
23
+// -- may be a good idea to change to output path to somewherelike /tmp
24
+// go test -coverprofile cover.out && go tool cover -html=cover.out -o cover.html
25
+//
26
+
27
+type FakeWebhook struct {
28
+	provider Provider
29
+}
30
+
31
+func (fhook FakeWebhook) Provider() Provider {
32
+	return fhook.provider
33
+}
34
+
35
+func (fhook FakeWebhook) ParsePayload(w http.ResponseWriter, r *http.Request) {
36
+}
37
+
38
+var fakeHook Webhook
39
+
40
+func TestMain(m *testing.M) {
41
+
42
+	// setup
43
+	fakeHook = &FakeWebhook{
44
+		provider: GitHub,
45
+	}
46
+
47
+	os.Exit(m.Run())
48
+
49
+	// teardown
50
+}
51
+
52
+func TestHandler(t *testing.T) {
53
+
54
+	mux := http.NewServeMux()
55
+	mux.Handle("/webhooks", Handler(fakeHook))
56
+
57
+	s := httptest.NewServer(Handler(fakeHook))
58
+	defer s.Close()
59
+
60
+	payload := "{}"
61
+
62
+	req, err := http.NewRequest("POST", s.URL+"/webhooks", bytes.NewBuffer([]byte(payload)))
63
+	req.Header.Set("Content-Type", "application/json")
64
+
65
+	Equal(t, err, nil)
66
+
67
+	client := &http.Client{}
68
+	resp, err := client.Do(req)
69
+	Equal(t, err, nil)
70
+
71
+	defer resp.Body.Close()
72
+
73
+	Equal(t, resp.StatusCode, http.StatusOK)
74
+
75
+	// Test BAD METHOD
76
+	req, err = http.NewRequest("GET", s.URL+"/webhooks", bytes.NewBuffer([]byte(payload)))
77
+	req.Header.Set("Content-Type", "application/json")
78
+
79
+	Equal(t, err, nil)
80
+
81
+	resp, err = client.Do(req)
82
+	Equal(t, err, nil)
83
+
84
+	defer resp.Body.Close()
85
+
86
+	Equal(t, resp.StatusCode, http.StatusMethodNotAllowed)
87
+}
88
+
89
+func TestRun(t *testing.T) {
90
+
91
+	go Run(fakeHook, "127.0.0.1:3006", "/webhooks")
92
+	time.Sleep(5000)
93
+
94
+	payload := "{}"
95
+
96
+	req, err := http.NewRequest("POST", "http://127.0.0.1:3006/webhooks", bytes.NewBuffer([]byte(payload)))
97
+	req.Header.Set("Content-Type", "application/json")
98
+
99
+	Equal(t, err, nil)
100
+
101
+	client := &http.Client{}
102
+	resp, err := client.Do(req)
103
+	Equal(t, err, nil)
104
+
105
+	defer resp.Body.Close()
106
+
107
+	Equal(t, resp.StatusCode, http.StatusOK)
108
+
109
+	// While HTTP Server is running test some bad input
110
+
111
+	// Test BAD URL
112
+	req, err = http.NewRequest("POST", "http://127.0.0.1:3006", bytes.NewBuffer([]byte(payload)))
113
+	req.Header.Set("Content-Type", "application/json")
114
+
115
+	Equal(t, err, nil)
116
+
117
+	resp, err = client.Do(req)
118
+	Equal(t, err, nil)
119
+
120
+	defer resp.Body.Close()
121
+
122
+	Equal(t, resp.StatusCode, http.StatusNotFound)
123
+
124
+	// Test BAD METHOD
125
+	req, err = http.NewRequest("GET", "http://127.0.0.1:3006/webhooks", bytes.NewBuffer([]byte(payload)))
126
+	req.Header.Set("Content-Type", "application/json")
127
+
128
+	Equal(t, err, nil)
129
+
130
+	resp, err = client.Do(req)
131
+	Equal(t, err, nil)
132
+
133
+	defer resp.Body.Close()
134
+
135
+	Equal(t, resp.StatusCode, http.StatusMethodNotAllowed)
136
+}
137
+
138
+func TestRunServer(t *testing.T) {
139
+	DefaultLog = NewLogger(true)
140
+	server := &http.Server{Addr: "127.0.0.1:3007", Handler: nil}
141
+	go RunServer(server, fakeHook, "/webhooks")
142
+	time.Sleep(5000)
143
+
144
+	payload := "{}"
145
+
146
+	req, err := http.NewRequest("POST", "http://127.0.0.1:3007/webhooks", bytes.NewBuffer([]byte(payload)))
147
+	req.Header.Set("Content-Type", "application/json")
148
+
149
+	Equal(t, err, nil)
150
+
151
+	client := &http.Client{}
152
+	resp, err := client.Do(req)
153
+	Equal(t, err, nil)
154
+
155
+	defer resp.Body.Close()
156
+
157
+	Equal(t, resp.StatusCode, http.StatusOK)
158
+
159
+	// While HTTP Server is running test some bad input
160
+
161
+	// Test BAD URL
162
+	req, err = http.NewRequest("POST", "http://127.0.0.1:3007", bytes.NewBuffer([]byte(payload)))
163
+	req.Header.Set("Content-Type", "application/json")
164
+
165
+	Equal(t, err, nil)
166
+
167
+	resp, err = client.Do(req)
168
+	Equal(t, err, nil)
169
+
170
+	defer resp.Body.Close()
171
+
172
+	Equal(t, resp.StatusCode, http.StatusNotFound)
173
+
174
+	// Test BAD METHOD
175
+	req, err = http.NewRequest("GET", "http://127.0.0.1:3007/webhooks", bytes.NewBuffer([]byte(payload)))
176
+	req.Header.Set("Content-Type", "application/json")
177
+
178
+	Equal(t, err, nil)
179
+
180
+	resp, err = client.Do(req)
181
+	Equal(t, err, nil)
182
+
183
+	defer resp.Body.Close()
184
+
185
+	Equal(t, resp.StatusCode, http.StatusMethodNotAllowed)
186
+}
187
+
188
+func TestRunTLSServer(t *testing.T) {
189
+
190
+	var err error
191
+
192
+	// can have certificates in static variables or load from disk
193
+	cert := `-----BEGIN CERTIFICATE-----
194
+MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
195
+BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
196
+aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF
197
+MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50
198
+ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ
199
+hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa
200
+rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv
201
+zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF
202
+MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW
203
+r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V
204
+-----END CERTIFICATE-----
205
+    `
206
+	key := `-----BEGIN RSA PRIVATE KEY-----
207
+MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo
208
+k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G
209
+6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N
210
+MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW
211
+SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T
212
+xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi
213
+D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g==
214
+-----END RSA PRIVATE KEY-----
215
+`
216
+
217
+	server := &http.Server{Addr: "127.0.0.1:3008", Handler: nil, TLSConfig: &tls.Config{}}
218
+	server.TLSConfig.Certificates = make([]tls.Certificate, 1)
219
+
220
+	server.TLSConfig.Certificates[0], err = tls.X509KeyPair([]byte(cert), []byte(key))
221
+	Equal(t, err, nil)
222
+
223
+	go RunTLSServer(server, fakeHook, "/webhooks")
224
+	time.Sleep(5000)
225
+
226
+	payload := "{}"
227
+
228
+	req, err := http.NewRequest("POST", "https://127.0.0.1:3008/webhooks", bytes.NewBuffer([]byte(payload)))
229
+	req.Header.Set("Content-Type", "application/json")
230
+
231
+	Equal(t, err, nil)
232
+
233
+	tr := &http.Transport{
234
+		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
235
+	}
236
+
237
+	client := &http.Client{Transport: tr}
238
+	resp, err := client.Do(req)
239
+	Equal(t, err, nil)
240
+
241
+	defer resp.Body.Close()
242
+
243
+	Equal(t, resp.StatusCode, http.StatusOK)
244
+
245
+	// While HTTP Server is running test some bad input
246
+
247
+	// Test BAD URL
248
+	req, err = http.NewRequest("POST", "https://127.0.0.1:3008", bytes.NewBuffer([]byte(payload)))
249
+	req.Header.Set("Content-Type", "application/json")
250
+
251
+	Equal(t, err, nil)
252
+
253
+	resp, err = client.Do(req)
254
+	Equal(t, err, nil)
255
+
256
+	defer resp.Body.Close()
257
+
258
+	Equal(t, resp.StatusCode, http.StatusNotFound)
259
+
260
+	// Test BAD METHOD
261
+	req, err = http.NewRequest("GET", "https://127.0.0.1:3008/webhooks", bytes.NewBuffer([]byte(payload)))
262
+	req.Header.Set("Content-Type", "application/json")
263
+
264
+	Equal(t, err, nil)
265
+
266
+	resp, err = client.Do(req)
267
+	Equal(t, err, nil)
268
+
269
+	defer resp.Body.Close()
270
+
271
+	Equal(t, resp.StatusCode, http.StatusMethodNotAllowed)
272
+}
273
+
274
+func TestProviderString(t *testing.T) {
275
+
276
+	Equal(t, GitHub.String(), "GitHub")
277
+	Equal(t, Bitbucket.String(), "Bitbucket")
278
+	Equal(t, GitLab.String(), "GitLab")
279
+	Equal(t, Provider(999999).String(), "Unknown")
280
+}