-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
347 lines (303 loc) · 7.86 KB
/
main.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package main
import (
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"gopkg.in/irc.v3"
)
const (
PRStartScan = 58805
)
var (
allowedCategories categorySlice
ircChannel *string
ircServer *string
ircUsername *string
ircPassword string
)
type categorySlice []string
const ctcpVersionReply = "Code available at https://github.com/coypoop/gnatsirc/"
func (i *categorySlice) String() string {
return "my string representation"
}
func (i *categorySlice) Set(value string) error {
*i = append(*i, value)
return nil
}
func main() {
flag.Var(&allowedCategories, "allow-category", "Only post PRs from these categories.")
ircServer = flag.String("irc-server", "irc-server", "Which IRC server to connect, for example irc.example.com:6667")
ircChannel = flag.String("irc-channel", "irc-channel", "Which IRC channel to join, for example #my-channel")
ircUsername = flag.String("irc-username", "irc-username", "Which username to use on IRC")
ircPassword = os.Getenv("IRC_PASSWORD")
flag.Parse()
if ircServer == nil ||
ircChannel == nil ||
ircUsername == nil {
usage()
}
if len(os.Args) < 4 {
usage()
}
config := irc.ClientConfig{
Nick: *ircUsername,
Pass: ircPassword,
User: *ircUsername,
Name: "GNATS urls on demand",
Handler: irc.HandlerFunc(func(c *irc.Client, m *irc.Message) {
if m.Command == "001" {
log.Printf("Connected to server %s", *ircServer)
// 001 is a welcome event, so we identify join channels now
if ircPassword != "" {
c.WriteMessage(&irc.Message{
Command: "PRIVMSG",
Params: []string{
"NickServ",
"IDENTIFY " + *ircUsername + " " + ircPassword,
},
})
}
c.Write("JOIN " + *ircChannel)
log.Printf("Joined %s", *ircChannel)
go observeNewPRs(c, *ircChannel)
} else if m.Command == "PRIVMSG" && c.FromChannel(m) {
if selfMsg(m.Trailing()) {
return
}
prNum, err := findPR(m.Trailing())
if err == nil {
var outText string
prUrl := toGnatsUrl(prNum)
prText, err := getPRText(prUrl)
if err != nil {
return
}
prSynopsis, err := findPRSynopsis(prText)
if err != nil {
return
}
prState, err := findPRState(prText)
if err != nil {
return
}
outText = prUrl + " (" + prState + ") " + prSynopsis
c.WriteMessage(&irc.Message{
Command: "PRIVMSG",
Params: []string{
m.Params[0],
outText,
},
})
}
} else if isCTCP(m) {
requestingUser := m.Prefix.Name
switch ctcpType(m) {
case "VERSION":
c.WriteMessage(ctcpReply(requestingUser, "VERSION", ctcpVersionReply))
break
default:
break
}
}
}),
}
for {
conn, err := net.Dial("tcp", *ircServer)
if err != nil {
time.Sleep(1 * time.Minute)
continue
}
client := irc.NewClient(conn, config)
err = client.Run()
if err != nil {
log.Println(err)
}
}
}
func observeNewPRs(c *irc.Client, ircChan string) {
latestGoodPR := PRStartScan
lastPostedPR := PRStartScan
synopses := make(map[int]string)
for {
for currentPR := latestGoodPR; currentPR-latestGoodPR < 20; currentPR++ {
prUrl := toGnatsUrl(currentPR)
prText, err := getPRText(prUrl)
if err != nil {
log.Printf("getPRText returned err %+v for PR URL #%s", err, prUrl)
continue
}
currentSynopsis, err := findPRSynopsis(prText)
if err != nil {
log.Printf("findPRSynopsis returned err %+v for prText %s", err, prText)
continue
}
currentCategory, err := findPRCategory(prText)
if err != nil {
log.Printf("findPRCategory returned err %+v for prText %s", err, prText)
continue
}
if !allowedCategory(currentCategory) {
continue
}
latestGoodPR = currentPR
synopses[currentPR] = currentSynopsis
}
// First run, stay silent.
if lastPostedPR == PRStartScan {
lastPostedPR = latestGoodPR
}
// Don't spam too much...
if latestGoodPR-lastPostedPR > 5 {
lastPostedPR = latestGoodPR - 5
}
for ; lastPostedPR < latestGoodPR; lastPostedPR++ {
if synopsis, ok := synopses[lastPostedPR+1]; ok {
outText := "new " + toGnatsUrl(lastPostedPR+1) + " " + synopsis
c.WriteMessage(&irc.Message{
Command: "PRIVMSG",
Params: []string{
ircChan,
outText,
},
})
}
}
time.Sleep(10 * time.Minute)
}
}
func allowedCategory(testedCategory string) bool {
if allowedCategories == nil {
return true
}
for _, allowedCategory := range allowedCategories {
if testedCategory == allowedCategory {
return true
}
}
return false
}
func toGnatsUrl(prNum int) string {
return fmt.Sprintf("https://gnats.netbsd.org/%d", prNum)
}
// does it look like a message that we sent?
func selfMsg(msg string) bool {
rs := selfMsgRegexp.FindStringSubmatch(msg)
if len(rs) > 1 {
return true
}
return false
}
const ctcpDelimiter = "\001"
func isCTCP(m *irc.Message) bool {
if m.Command != "PRIVMSG" {
return false
}
message := m.Trailing()
if !strings.HasPrefix(message, ctcpDelimiter) {
return false
}
if !strings.HasSuffix(message, ctcpDelimiter) {
return false
}
return true
}
func ctcpType(m *irc.Message) string {
msg := m.Trailing()
return strings.TrimSuffix(strings.TrimPrefix(msg, ctcpDelimiter), ctcpDelimiter)
}
func ctcpReply(user, ctcpType, reply string) *irc.Message {
ctcpEscapedReply := ctcpDelimiter + ctcpType + " " + reply + ctcpDelimiter
return &irc.Message{
Command: "NOTICE",
Params: []string{
user,
ctcpEscapedReply,
},
}
}
func findFirstSubmatch(prText string, rgx *regexp.Regexp) (string, error) {
rs := rgx.FindStringSubmatch(prText)
if len(rs) == 0 {
return "", errors.New("Regex not found in PR body")
}
return rs[1], nil
}
func getPRText(prUrl string) (string, error) {
resp, err := http.Get(prUrl)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return undoHtmlSanitize(string(body)), nil
}
func findPRCategory(prText string) (string, error) {
return findFirstSubmatch(prText, categoryRegexp)
}
func findPRSynopsis(prText string) (string, error) {
return findFirstSubmatch(prText, synopsisRegexp)
}
func findPRState(prText string) (string, error) {
return findFirstSubmatch(prText, stateRegexp)
}
func findPR(msg string) (int, error) {
for _, rgx := range prRegexps {
rs := rgx.FindStringSubmatch(msg)
if len(rs) > 1 {
prString := rs[1]
prNum, err := strconv.Atoi(prString)
if err != nil {
return 0, err
}
return prNum, nil
}
}
return 0, errors.New("PR number not found")
}
func undoHtmlSanitize(msg string) string {
msg = strings.ReplaceAll(msg, ">", ">")
msg = strings.ReplaceAll(msg, "<", "<")
msg = strings.ReplaceAll(msg, "&", "&")
msg = strings.ReplaceAll(msg, """, `"`)
return msg
}
var prRegexps []*regexp.Regexp
var synopsisRegexp *regexp.Regexp
var categoryRegexp *regexp.Regexp
var stateRegexp *regexp.Regexp
var selfMsgRegexp *regexp.Regexp
func init() {
selfMsgRegexp = regexp.MustCompile(`https://gnats.netbsd.org`)
synopsisRegexp = regexp.MustCompile(`.*Synopsis:.... *(.*)`)
categoryRegexp = regexp.MustCompile(`.*Category:.... *(.*)`)
stateRegexp = regexp.MustCompile(`.*State:.... *(.*)`)
prRegexps = []*regexp.Regexp{
regexp.MustCompile("PR [a-z]*/([0-9]{4,5})"),
regexp.MustCompile("PR ([0-9]{4,5})"),
regexp.MustCompile("PR#([0-9]{4,5})"),
regexp.MustCompile("PR/([0-9]{4,5})"),
regexp.MustCompile("[^a-z]pr/([0-9]{4,5})"),
regexp.MustCompile("[^a-z]pr ([0-9]{4,5})"),
regexp.MustCompile("[^a-z]pr#([0-9]{4,5})"),
regexp.MustCompile("^pr ([0-9]{4,5})"),
regexp.MustCompile("^pr#([0-9]{4,5})"),
regexp.MustCompile("^pr/([0-9]{4,5})"),
}
}
func usage() {
fmt.Printf("Usage: [IRC_PASSWORD=password] \t%s -irc-server irc.example.com:6667 -irc-channel -irc-username gnat #netbsd [-allow-category pkg]\n", os.Args[0])
flag.PrintDefaults()
os.Exit(1)
}