-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgithook.go
208 lines (177 loc) · 5.97 KB
/
githook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/*
* This file handles GitHub webhooks. For more information on GitHub webhooks
* go to https://developer.github.com/webhooks/, and for information on their
* payloads, go to https://developer.github.com/v3/activity/events/types.
* For information on the hookserve module which deals with receiving and
* parsing the hooks, see https://github.com/TalkTakesTime/hookserve
*
* Note that the bot will panic if the port given in config.yaml is already
* in use, so be careful.
*
* Copyright 2015 (c) Ben Frengley (TalkTakesTime)
*/
package gobot
import (
"errors"
"fmt"
"github.com/TalkTakesTime/hookserve/hookserve" // credits to phayes for the original
"github.com/tonnerre/golang-pretty"
"html"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
const (
GitIOBase = "http://git.io/"
GitIOCreate = "http://git.io/create"
// template for push messages
// [repo] user pushed number new commits? to branch: URL
PushTemplate = "[%s] %s pushed %s new commit%s to %s: %s"
// template for commit messages
// repo/branch SHA user: commit message
CommitTemplate = "%s/%s %s %s: %s"
// template for pull request messages
// [repo] user action pull request #number: message (upstream...base) URL
PullReqTemplate = "[%s] %s %s pull request #%s: %s (%s...%s) %s"
)
var (
ErrShortenURL = errors.New("could not shorten the URL")
)
// Error encountered when a URL can't be shortened using a URL shortener
// such as git.io or goo.gl
type ShortURLError struct {
URL string // the URL trying to be shortened
Err error
}
func (e *ShortURLError) Error() string {
return e.URL + ": " + e.Err.Error()
}
// Generates the GitHub webhook receiver and starts a goroutine to deal
// with received events
func (bot *Bot) CreateHook() {
bot.hookServer = hookserve.NewServer()
bot.hookServer.Port = bot.config.HookPort
bot.hookServer.Secret = bot.config.HookSecret
bot.hookServer.GoListenAndServe()
go bot.ListenForHooks()
}
// Listens for GitHub webhook events and delegates them to handlers, such as
// `HandlePushHook`. Currently only push and pull_request events are supported
func (bot *Bot) ListenForHooks() {
for {
select {
case event := <-bot.hookServer.Events:
pretty.Log(event)
switch event.Type {
case "push":
bot.HandlePushHook(event)
case "pull_request":
bot.HandlePullHook(event)
default:
// do nothing for now
}
default:
time.Sleep(100 * time.Millisecond)
}
}
}
// Sends messages to all relevant rooms updating them when a push event
// is received. Tells how many commits were pushed, and gives a description
// of each individual commit, as given in the commit message
func (bot *Bot) HandlePushHook(event hookserve.Event) {
// we don't care about 0 commit pushes
if event.Size == 0 {
return
}
// attempt to shorten the URL using git.io
shortURL, err := ShortenURL(event.URL)
if err != nil {
shortURL = event.URL
}
plural := ""
if event.Size > 1 {
plural = "s"
}
msg := fmt.Sprintf(PushTemplate, FormatRepo(event.Repo),
FormatName(event.By), FormatSize(event.Size), plural,
FormatBranch(event.Branch), FormatURL(shortURL))
// send to all githook rooms
// for _, r := range bot.config.HookRooms {
// bot.QueueMessage(msg, r)
// }
// add messages for individual commits too
for i := 0; i < event.Size; i++ {
msgParts := strings.Split(event.Commits[i].Message, "\n")
msg += "<br />" + fmt.Sprintf(CommitTemplate, FormatRepo(event.Repo),
FormatBranch(event.Branch), FormatSHA(event.Commits[i].SHA[:7]),
FormatName(event.Commits[i].By), msgParts[0])
}
msg = "!htmlbox " + msg
for _, r := range bot.config.HookRooms {
bot.QueueMessage(msg, r)
}
}
// Sends messages to all relevant rooms updating them when a pull_request
// event is received. Still in beta
func (bot *Bot) HandlePullHook(event hookserve.Event) {
// attempt to shorten the URL using git.io
shortURL, err := ShortenURL(event.URL)
if err != nil {
shortURL = event.URL
}
msgParts := strings.Split(event.Message, "\n")
if event.Action == "synchronize" {
event.Action = "synchronized"
}
msg := fmt.Sprintf(PullReqTemplate, FormatRepo(event.BaseRepo),
FormatName(event.By), event.Action, event.Number, msgParts[0],
FormatBranch(event.BaseBranch), FormatBranch(event.Branch),
FormatURL(shortURL))
for _, r := range bot.config.HookRooms {
bot.QueueMessage("!htmlbox "+msg, r)
}
}
// FormatRepo formats a repo name for !htmlbox using #FF00FF.
func FormatRepo(repo string) string {
return fmt.Sprintf("<font color=\"#FF00FF\">%s</font>", html.EscapeString(repo))
}
// FormatBranch formats a branch for !htmlbox using #9C009C.
func FormatBranch(branch string) string {
return fmt.Sprintf("<font color=\"#9C009C\">%s</font>", html.EscapeString(branch))
}
// FormatName formats a name for !htmlbox using #7F7F7F. Note that it uses a
// different colour to the IRC version due to PS' background colour.
func FormatName(name string) string {
return fmt.Sprintf("<font color=\"#6F6F6F\">%s</font>", html.EscapeString(name))
}
// FormatURL formats a URL for !htmlbox.
func FormatURL(url string) string {
return fmt.Sprintf("<a href=\"%s\">%s</a>", html.EscapeString(url), html.EscapeString(url))
}
// FormatSHA formats a commit SHA for !htmlbox using #7F7F7F.
func FormatSHA(sha string) string {
return fmt.Sprintf("<font color=\"#7F7F7F\">%s</font>", html.EscapeString(sha))
}
// FormatSize formats an event size for !htmlbox using <strong>.
func FormatSize(size int) string {
return fmt.Sprintf("<strong>%d</strong>", size)
}
// Utility to shorten a URL using http://git.io/
// Returns an empty string and ErrShortenURL if something goes wrong,
// otherwise returns the shortened URL and nil
func ShortenURL(longURL string) (string, error) {
response, err := http.PostForm(GitIOCreate, url.Values{
"url": []string{longURL},
})
if err != nil {
return "", &ShortURLError{longURL, ErrShortenURL}
}
extension, err := ioutil.ReadAll(response.Body)
response.Body.Close()
if err != nil {
return "", &ShortURLError{longURL, ErrShortenURL}
}
return GitIOBase + string(extension), nil
}