-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgithub.tcl
More file actions
1709 lines (1584 loc) · 58 KB
/
github.tcl
File metadata and controls
1709 lines (1584 loc) · 58 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# github.tcl --
#
# This script receives GitHub webhook events. It creates a partial HTTPd
# and waits for events getting pushed to it from GitHub. You need to have
# access to the webhook settings of the repository you wish to get
# notifications from on GitHub. Scroll down to change some basic settings.
# The majority of the settings for this script are available via the
# ".github" command from the partyline.
#
# Copyright (c) 2016, 2020 Rickard Utgren <rutgren@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# v0.5 by Pixelz (rutgren@gmail.com), January 28, 2020
#
# Changes:
#
# v0.5. January 28, 2020:
# - Added caching for git.io URLs
# - Fixed an error with loading the settings file.
#
# v0.4. December 12, 2016:
# - Use SNI in http requests to git.io and api.github.com.
# - Made URL shortening a lot more error-resistant.
# - Added more robustness around writing the settings file.
#
# v0.3. October 30, 2016:
# - Added support for pull_request_review event.
# - Added rudimentary support for milestone event.
# - Fixed pull request comments being reported as issue comments.
# - Fixed a bug with renamed labels being reported incorrectly.
#
# v0.2. October 29, 2016:
# - Added support for label event.
# - Added support for milestoned & demilestoned actions for issue event.
# - Added delayed output (10 seconds) for issue events. The script will now
# fit all changes done to an issue in the same announcement.
# - Added support for status events.
# - Added a setting to enable (off by default) showing individual commits to
# a non-default branch.
# - Added number of bytes changed in an issue comment edit.
# - The script will now ignore push events for creating or deleting branches
# or tags since there's another event that handles those.
# - More readable output for '.github list'
# - Fixed the issue linker not linking to issues with really low numbers.
# - Fixed issue comment event so that it doesn't always say "commented" even
# if the action was edited or closed.
# - Strip newlines from issue comments for more meaningful output.
# - Fixed problem that caused commits not to show if the committer didn't
# have an account on github.
# - Fixed a bug that caused multiple repositories to not work properly.
# - Fixed a bug that caused events to be sent to all channels that had that
# event configured.
#
# v0.1. January 31, 2016:
# - Initial release.
#
# ToDo:
# - Add support for libcurl
# - Make the http fetching not block (coroutines?)
# - Rethink the whole output selection logic. I would like it to be more fine-tuned.
# - Make the dcc command more understandable
# - Add ability to set events to output the same way that chanset works
# - Change the way settings are stored so that the linker settings doesn't require special handling
# - Write help & documentation in general
# - Add msgcat support? might be difficult with the dynamic nature of some of the output
# - Restructure the parseJson proc & possibly other procs
# some of these might be able to go lower, these are what the script was tested on
package require Tcl 8.6 ;# 8.6 needed
package require eggdrop 1.6.21
package require http 2.8.8
package require tls 1.6.4
package require json 1.3.3 ;# I think 1.3.3 is needed
package require sha1 2.0.3
package require base64 2.4.2
namespace eval ::github {
### Settings:
# Listen port for the built-in HTTPd. You probably want to change this.
# Changing this when the script is loaded requires a RESTART (not a rehash).
set port 52525
# This is how many channels the bot will output to in a single command. The
# more that your IRC server supports, the better. You can figure this out
# by sending "/quote VERSION" to the server and find the part starting with
# "TARGMAX=" or possibly "MAXTARGETS=". If you're unsure, set it to 1. At
# the time of writing, freenode supports 4.
# Additionally, some networks have channel modes that prevent sending
# multi-target PRIVMSGs. If the bot is on a channel with such a mode set,
# set this to 1.
set privmsgTargMax 4
# Shorten URLs using git.io?
set shortenUrls 1
# Show "pending" status events. These are events showing the status of a
# commit. They are sent via github's API from a 3rd party, for example
# Jenkins, etc. Pending means that the commit has been queued for building
# or similar. There will be other events sent after the pending one(s) that
# are generally more interesting.
set showPendingStatus 0
# Show individual commits pushed to a non-default branch. This will
# potentially result in walls of text whenever a branch is synchronized
# with the default branch.
set showNonDefaultCommits 0
### More settings, you probably don't need to change these:
# User-flags required to use the .github partyline command.
# Note that ANY of these flags would be required (not all).
# Changing this requires a restart.
set dccFlags "n"
# path to settings file
set settingsFile "scripts/github.tcl.settings"
# maximum length of payload in bytes
set payloadLimit 10485760;# 10MB
# maximum length of headers in bytes
set headerLimit 5242880; # 5MB
# rough time in seconds until a git.io url expires from the cache (+ 0-10 minutes)
set gitioCacheTime 21600; # 6 hours
# store JSON payload to a file, for reviewing later
set storeJson 0
### End of settings
# load local settings if they exist
if {[file exists scripts/github.tcl.local] && [file readable scripts/github.tcl.local]} {
source scripts/github.tcl.local
putlog "Loaded local settings from github.tcl.local"
}
# Not supported:
# membership (organization hooks only)
# page_build (github pages crap - some website thing)
# public (seems kind of useless)
# repository (repositories being deleted and created etc)
# team_add (when a repository is added to a team)
#
# ToDo: add support:
# deployment (what is it and how is it different from status event?)
# deployment_status
set validEvents [list commit_comment create delete fork gollum issue_comment issues label member milestone \
pull_request pull_request_review_comment pull_request_review push release status watch]
variable state
variable settings
variable delayedSendIds
variable gitioCache
}
# rfc1459 channel name comparison
# Note: []\^ (uppers) == {}|~ (lowers)
proc ::github::ircstreql {string1 string2} {
string equal -nocase [string map [list \{ \[ \} \] ~ ^ | \\] $string1] [string map [list \{ \[ \} \] ~ ^ | \\] $string2]
}
# callback for tls::socket, outputs debug info
proc ::github::tlsCommand {args} {
foreach arg $args {
foreach line [split $arg "\n"] {
putloglev 8 * "github.tcl tls state: $line"
}
}
return
}
# Expire cached URLs
# called every 10 minutes by bind cron
proc ::github::gitioCacheCleanup {args} {
variable gitioCache
variable gitioCacheTime
if {[info exists gitioCache]} {
foreach longUrl [dict keys $gitioCache] {
lassign [dict get $gitioCache $longUrl] shortUrl timeCreated
if {([clock seconds] - $timeCreated) > $gitioCacheTime} {
putloglev d * "github.tcl: URL expired from the cache: $longUrl -> $shortUrl"
dict unset gitioCache $longUrl
}
}
}
return
}
# Store a short URL in the cache
proc ::github::gitioCacheStore {longUrl shortUrl} {
variable gitioCache
dict set gitioCache $longUrl $shortUrl [clock seconds]
putloglev d * "github.tcl: new URL added to cache $longUrl -> $shortUrl"
return
}
# Retrieve a short URL from the cache
# returns the short url if it exists, "" if not.
proc ::github::gitioCacheGet {longUrl} {
variable gitioCache
if {[info exists gitioCache] && [dict exists $gitioCache $longUrl]} {
lassign [dict get $gitioCache $longUrl] shortUrl timeCreated
putloglev d * "github.tcl: found cached URL: $longUrl -> $shortUrl"
return $shortUrl
} else {
putloglev d * "github.tcl: $longUrl is not cached"
return
}
}
proc ::github::gitio {url} {
variable shortenUrls
if {[info exists shortenUrls] && $shortenUrls != 1} { return $url }
# check if we already have it cached
if {[set shortUrl [gitioCacheGet $url]] ne ""} {
return $shortUrl
}
::http::register https 443 [list ::tls::socket -command ::github::tlsCommand -request 0 -require 0 -servername "git.io"]
set url [regsub -- {^http://} $url {https://}]
# this god forsaken thing can't be trusted not to spew errors everywhere
if {[catch { ::http::geturl https://git.io -query [::http::formatQuery url $url] } token]} {
putlog "github.tcl http error:"
foreach line [split $token "\n"] {
putlog "github.tcl http error: $line"
}
return $url
}
upvar #0 $token state
# "clean up" http::register for the benefit of legacy scripts
::http::register https 443 [list ::tls::socket]
if {[info exists state(error)]} { set error $state(error) }
array set meta $state(meta)
catch { ::http::cleanup $token }
if {[info exists error]} {
putlog "github.tcl Error: git.io http error: $error"
return $url
} elseif {![info exists meta(Status)]} {
putlog "github.tcl Error: git.io http error, meta status does not exist, possibly ssl error?"
putlog "gibhub.tcl git.io meta: [array get meta]"
return $url
} elseif {![info exists meta(Location)]} {
putlog "github.tcl Error: git.io http error, meta location does not exist, possibly ssl error?"
putlog "github.tcl git.io meta: [array get meta]"
return $url
} elseif {[string equal "201 Created" $meta(Status)] && [string match "https://git.io/*" $meta(Location)] && [string length $meta(Location)] > 15} {
gitioCacheStore $url $meta(Location)
return $meta(Location)
} else {
putlog "github.tcl Error: git.io URL shortening failed."
putlog "github.tcl git.io meta: [array get meta]"
return $url
}
}
proc ::github::issueLinker {nick uhost hand chan text} {
variable settings
# cheap way to filter out most things we don't care about
if {(![string match -nocase {*#[0-9][0-9]*} $text]) && (![string match -nocase "*http*github.com*" $text])} {
return 1
}
# check if this channel has a repo associated with it
foreach {setChan repo} [dict get $settings linker] {
if {[ircstreql $setChan $chan]} { set foundRepo 1; break }
}
if {![info exists foundRepo]} {
return 1
}
putloglev d * "found repo for $chan: $repo"
# extract IDs from the text
foreach {- a b} [regexp -all -nocase -inline "(?:\#(\[0-9\]+)|https?://github.com${repo}/(?:issues|pull)/(\[0-9\]+))" $text] {
if {![string equal "" $a]} {
lappend ids $a
} elseif {![string equal "" $b]} {
lappend ids $b
}
}
if {![info exists ids]} {
return 1
} else {
set ids [lsort -unique $ids]
}
putloglev d * "found ID(s): $ids"
# FixMe: make this a setting?
if {[llength $ids] > 3} {
putlog "github.tcl: $nick tried to flood me with [llength $ids] IDs. Not outputting."
return 1
}
foreach id $ids {
# https://api.github.com/repos/eggheads/eggdrop/issues/
# pull request: https://api.github.com/repos/eggheads/eggdrop/issues/156
# issue: https://api.github.com/repos/eggheads/eggdrop/issues/151
::http::register https 443 [list ::tls::socket -command ::github::tlsCommand -request 0 -require 0 -servername "api.github.com"]
set token [::http::geturl https://api.github.com/repos${repo}/issues/${id}]
upvar #0 $token state
set status [string tolower $state(status)]
if {[info exists state(error)]} { set error $state(error) }
array set meta $state(meta)
set body [encoding convertfrom utf-8 $state(body)]
catch { ::http::cleanup $token }
# "clean up" http::register for the benefit of legacy scripts
::http::register https 443 [list ::tls::socket]
switch -exact -- $status {
reset {
putlog "github.tcl Error: issueLinker http error: connection reset"
}
timeout {
putlog "github.tcl Error: issueLinker http error: connection timeout"
}
error {
putlog "github.tcl Error: issueLinker http error: $error"
}
ok {
if {[catch {::json::json2dict $body} jdict]} {
putlog "github.tcl Error: issueLinker error parsing json: $jdict"
return 1
} elseif {[dict exists $jdict message] && [string equal -nocase "not found" [dict get $jdict message]]} {
return 1
} else {
if {[dict exists $jdict pull_request]} {
# this is a pull request
putserv "PRIVMSG $chan :[gitio [dict get $jdict html_url]] pull request #${id} \"[dict get $jdict title]\" ([dict get $jdict state])"
} else {
# this is an issue
putserv "PRIVMSG $chan :[gitio [dict get $jdict html_url]] issue #${id} \"[dict get $jdict title]\" ([dict get $jdict state])"
}
}
}
default {
putlog "github.tcl Error: issueLinker unknown http status: $status"
return 1
}
}
}
return
}
proc ::github::plural {word count} {
if {$count > 1} {
return "${word}s"
} else {
return $word
}
}
proc ::github::shortenBody {string {length 64}} {
set string [string map [list \r ""] $string]
set firstLine [lindex [split $string \n] 0]
set retval [string range $firstLine 0 $length]
if {[string length $firstLine] > $length || [llength [split $string \n]] > 1} {
set retval "[string trim [string range $retval 0 ${length}-3]]..."
}
return $retval
}
proc ::github::formatRef {ref} {
# refs/heads/master
# refs/heads/bug/encodings
# refs/tags/v1.8.0rc1
if {[regexp -- {^refs/(?:heads|tags)/(.+)$} $ref - branch]} {
return "/$branch"
} else {
return
}
}
# this is unused at the moment
proc ::github::getRefType {ref} {
# this is a branch: refs/heads/release/1.8.0
# this is a tag: refs/tags/v1.8.0rc1
if {[regexp -- {^refs/(head|tag)s/.+$} $ref - type]} {
if {[string equal $type "head"]} { set type "branch" }
return $type
} else {
return
}
}
# by BEO http://wiki.tcl.tk/10874
proc ::github::format_1024_units {value} {
set len [string length $value]
if {$value < 1024} {
format "%s [plural "byte" $value]" $value
} else {
set unit [expr {($len - 1) / 3}]
format "%.1f %s" [expr {$value / pow(1024,$unit)}] [lindex [list B KiB MiB GiB TiB PiB EiB ZiB YiB] $unit]
}
}
proc ::github::parseJson {event json} {
variable showPendingStatus
variable showNonDefaultCommits
upvar 1 delayedSend delayedSend
set jdict [::json::json2dict $json]
putloglev d * "github.tcl: parseJson event: $event"
switch -- $event {
ping {
putlog "github.tcl: Got ping event, ignoring"
}
commit_comment {
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "commented on commit [string range [dict get $jdict comment commit_id] 0 6]: "
append msg "[shortenBody [dict get $jdict comment body]] "
append msg "[gitio [dict get $jdict comment html_url]]"
return [list $msg]
}
create {
# branch or tag was created, webhooks will not receive the event for created repositories
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "created [dict get $jdict ref_type] [dict get $jdict ref]"
if {[string equal [dict get $jdict description] ""]} {
append msg " "
} else {
append msg ": [shortenBody [dict get $jdict description]] "
}
append msg "[gitio [dict get $jdict repository html_url]]"
return [list $msg]
}
delete {
# branch or tag was deleted
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "deleted [dict get $jdict ref_type] [dict get $jdict ref] "
append msg "[gitio [dict get $jdict repository html_url]]"
return [list $msg]
}
fork {
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "has forked [dict get $jdict repository full_name] "
append msg "to [dict get $jdict forkee full_name]: "
append msg "[gitio [dict get $jdict forkee html_url]]"
return [list $msg]
}
gollum {
# Triggered when a Wiki page is created or updated
foreach page [dict get $jdict pages] {
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "[dict get $page action] wiki page [dict get $page page_name]: "
append msg "[gitio [dict get $page html_url]]"
lappend retval $msg
}
return $retval
}
issue_comment {
# this includes comments on pull requests
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
set bytes ""
switch -- [dict get $jdict action] {
created {
set action "commented on"
}
edited {
set oldLen [string bytelength [dict get $jdict changes body from]]
set newLen [string bytelength [dict get $jdict comment body]]
if {$oldLen > $newLen} {
set bytes " ([format_1024_units [expr $oldLen - $newLen]] removed)"
} elseif {$newLen > $oldLen} {
set bytes " ([format_1024_units [expr $newLen - $oldLen]] added)"
}
set action "edited comment on"
}
deleted {
set action "deleted comment on"
}
default {
# this should not happen unless the API changes
set action [dict get $jdict action]
}
}
append msg "$action "
if {[dict exists $jdict issue pull_request]} {
append msg "pull request "
} else {
append msg "issue "
}
append msg "\#[dict get $jdict issue number]${bytes}: "
# strip newlines for more meaningful output
append msg "[shortenBody [join [regexp -all -inline {\S+} [dict get $jdict comment body]]]] "
append msg "[gitio [dict get $jdict issue html_url]]"
return [list $msg]
}
issues {
set action [dict get $jdict action]
set repName [dict get $jdict repository name]
set issueNum [dict get $jdict issue number]
set senderLogin [dict get $jdict sender login]
set issueTitle [dict get $jdict issue title]
set url [dict get $jdict issue html_url]
set delayedSend 1
switch -- $action {
assigned -
unassigned {
return [list $repName $issueNum $action $senderLogin $issueTitle $url [dict get $jdict assignee login]]
}
labeled -
unlabeled {
return [list $repName $issueNum $action $senderLogin $issueTitle $url [dict get $jdict label name]]
}
milestoned {
return [list $repName $issueNum $action $senderLogin $issueTitle $url [dict get $jdict issue milestone title]]
}
opened -
closed -
reopened -
demilestoned {
return [list $repName $issueNum $action $senderLogin $issueTitle $url]
}
default {
# this should not happen unless new actions are added to the API
set msg "\[${repName}\] $senderLogin $action issue #${issueNum} (${issueTitle}) [gitio $url]"
set delayedSend 0
}
}
return [list $msg]
}
label {
set action [dict get $jdict action]
set repName [dict get $jdict repository name]
set senderLogin [dict get $jdict sender login]
set labelName [dict get $jdict label name]
set url [gitio [dict get $jdict repository html_url]]
if {[string equal $action "edited"]} {
if {[dict exists $jdict changes name from]} {
# name was changed
set msg "\[${repName}\] $senderLogin renamed label \"[dict get $jdict changes name from]\" to \"${labelName}\" $url"
} elseif {[dict exists $jdict changes color from]} {
# color was changed
set msg "\[${repName}\] $senderLogin changed the color of label \"${labelName}\" $url"
} else {
# something else was changed that's not currently in the API
set msg "\[${repName}\] $senderLogin $action label \"${labelName}\" $url"
}
} else {
# created, deleted
set msg "\[${repName}\] $senderLogin $action label \"${labelName}\" $url"
}
return [list $msg]
}
member {
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "[dict get $jdict action] member [dict get $jdict member login] "
append msg "to [dict get $jdict repository full_name]: "
append msg "[gitio [dict get $jdict repository html_url]]"
return [list $msg]
}
milestone {
# action - "created", "closed", "opened", "edited", or "deleted".
# milestone - The milestone itself.
# changes - The changes to the milestone if the action was "edited".
# changes[description][from] - The previous version of the description if the action was "edited".
# changes[due_on][from] - The previous version of the due date if the action was "edited".
# changes[title][from] - The previous version of the title if the action was "edited".
set action [dict get $jdict action]
set repName [dict get $jdict repository name]
set senderLogin [dict get $jdict sender login]
set milestoneUrl [gitio [dict get $jdict milestone html_url]]
set milestoneTitle [dict get $jdict milestone title]
#set milestoneDesc [dict get $jdict milestone description]
set msg "\[${repName}\] $senderLogin $action milestone \"${milestoneTitle}\" $milestoneUrl"
return [list $msg]
}
pull_request {
# If the action is "closed" and the merged key is "false", the pull request was closed with unmerged commits.
# If the action is "closed" and the merged key is "true", the pull request was merged.
set action [dict get $jdict action]
if {[string equal $action "closed"] && [string equal [dict get $jdict pull_request merged] "true"]} {
set action "merged"
}
# set description for some actions
# this wording is a little weird but I can't come up with a better way of formulating it
set actionDescription ""
if {[string equal $action "assigned"]} {
set actionDescription " to [dict get $jdict assignee login]"
} elseif {[string equal $action "unassigned"]} {
set actionDescription " from [dict get $jdict assignee login]"
} elseif {[string equal $action "labeled"] || [string equal $action "unlabeled"]} {
set actionDescription " with \"[dict get $jdict label name]\""
}
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "$action pull request${actionDescription} #[dict get $jdict number]: "
append msg "[dict get $jdict pull_request title] "
append msg "([dict get $jdict pull_request base ref]...[dict get $jdict pull_request head ref]) "
append msg "[gitio [dict get $jdict pull_request html_url]]"
return [list $msg]
}
pull_request_review_comment {
# Triggered when a comment on a Pull Request's unified diff is created, edited, or deleted (in the Files Changed tab).
# um wat, there's no way to comment there? is this outdated now?
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "commented on pull request #[dict get $jdict pull_request number]: "
append msg "[shortenBody [dict get $jdict comment body]] "
append msg "[gitio [dict get $jdict comment html_url]]"
return [list $msg]
}
pull_request_review {
# Triggered when a pull request review is submitted into a non-pending state.
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "[dict get $jdict action] a review for pull request #[dict get $jdict pull_request number]"
# review state can be commented, approved or changes_requested
if {[string equal [dict get $jdict review state] "approved"]} {
append msg " and approved it"
} elseif {[string equal [dict get $jdict review state] "changes_requested"]} {
append msg " and requested changes"
}
if {[dict exists $jdict review body]} {
append msg ": [shortenBody [dict get $jdict review body]]"
}
append msg " [gitio [dict get $jdict review html_url]]"
return [list $msg]
}
push {
set msg "\[[dict get $jdict repository name]\] [dict get $jdict pusher name] "
if {[string equal [dict get $jdict created] "true"]} {
# this is a created branch or tag
putloglev d * "github.tcl: got a push event for a created branch or tag - ignoring"
return
#append msg "created [getRefType [dict get $jdict ref]] [dict get $jdict repository name][formatRef [dict get $jdict ref]]"
#lappend retval $msg
} elseif {[string equal [dict get $jdict deleted] "true"]} {
# this is a deleted branch or tag
putloglev d * "github.tcl: got a push event for a deleted branch or tag - ignoring"
return
#append msg "deleted [getRefType [dict get $jdict ref]] [dict get $jdict repository name][formatRef [dict get $jdict ref]]"
#lappend retval $msg
} else {
# this is a normal push
if {[llength [dict get $jdict commits]] == 0} {
# no commits were pushed
putloglev d * "github.tcl: got a push event with 0 commits - ignoring"
return
}
append msg "pushed [llength [dict get $jdict commits]] "
append msg "[plural "commit" [llength [dict get $jdict commits]]] "
append msg "to [dict get $jdict repository name][formatRef [dict get $jdict ref]]: "
append msg "[gitio [dict get $jdict compare]]"
lappend retval $msg
# only show individual commits if they're pushed to the default branch, unless setting enabled
if {[string equal [dict get $jdict repository default_branch] [string trimleft [formatRef [dict get $jdict ref]] "/"]] || $showNonDefaultCommits == 1} {
foreach commit [dict get $jdict commits] {
set msg "[dict get $jdict repository name][formatRef [dict get $jdict ref]] "
append msg "[string range [dict get $commit id] 0 6] "
if {[dict exists $commit author username]} {
append msg "[dict get $commit author username]: "
} else {
append msg "[dict get $commit author name]: "
}
append msg "[shortenBody [dict get $commit message]]"
lappend retval $msg
}
}
}
return $retval
}
release {
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "[dict get $jdict action] release "
putloglev d * "github.tcl release name: [dict get $jdict release name]"
if {![string equal -nocase [dict get $jdict release name] "null"]} {
append msg "[dict get $jdict release name]"
} else {
append msg "[dict get $jdict repository name][dict get $jdict release tag_name]"
}
putloglev d * "github.tcl release body: [dict get $jdict release body]"
if {![string equal -nocase [dict get $jdict release body] "null"]} {
append msg ": [shortenBody [dict get $jdict release body]] "
} else {
append msg ": "
}
append msg "[gitio [dict get $jdict release html_url]]"
return [list $msg]
}
status {
# The status of a commit changed, these are triggered via the API from jenkins, etc
# The new state. Can be pending, success, failure, or error.
if {$showPendingStatus != 1 && [string equal [dict get $jdict state] "pending"]} {
putloglev d * "github.tcl: got \"pending\" status event, ignoring"
return
}
set msg "\[[dict get $jdict repository name]\] [string range [dict get $jdict sha] 0 6] "
if {[dict exists $jdict commit author login]} {
append msg "[dict get $jdict commit author login]"
} elseif {[dict exists $jdict commit commit author name]} {
append msg "[dict get $jdict commit commit author name]"
} else {
append msg "[dict get $jdict sender login]"
}
if {[dict exists $jdict commit commit message] && ![string equal [dict get $jdict commit commit message] "null"]} {
append msg " ([shortenBody [dict get $jdict commit commit message]])"
}
append msg ". Status: [string toupper [dict get $jdict state]]"
if {![string equal [dict get $jdict description] "null"]} {
append msg ": [shortenBody [string trim [dict get $jdict description]]]"
}
if {[dict exists $jdict target_url] && ![string equal [dict get $jdict target_url] "null"]} {
append msg ". [dict get $jdict target_url]"
} elseif {[dict exists $jdict commit commit url]} {
append msg ". [gitio [dict get $jdict commit commit url]]"
} else {
append msg "."
}
return [list $msg]
}
watch {
# when someone STARS a repository (not watches it)
set msg "\[[dict get $jdict repository name]\] [dict get $jdict sender login] "
append msg "starred [dict get $jdict repository full_name]: "
append msg "[gitio [dict get $jdict repository html_url]]"
return [list $msg]
}
default {
putlog "github.tcl: Got unhandled event: $event, ignoring"
}
}
return
}
# further processing of some events that belong together but gets sent separately by github
# FixMe: this could probably grow into a too long line if a lot of different stuff was done to an issue at the same time
proc ::github::delayedSend {event path directChan id len} {
variable delayedSendIds
putloglev d * "github.tcl: enter delayedSend: $event <> $path <> $directChan <> $id <> $len"
putloglev d * "[lindex $delayedSendIds($id) 0] != $len"
if {[info exists delayedSendIds($id)] && [lindex $delayedSendIds($id) 0] != $len} {
# there's more coming
putloglev d * "github.tcl: more coming, returning"
return
} else {
putloglev d * "github.tcl: delayedSend started parsing for id: $id"
switch -- $event {
issues {
# output == $repName $issueNum $action $senderLogin $issueTitle $url [action-specific]
foreach output [lrange $delayedSendIds($id) 1 end] {
lassign $output repName issueNum action senderLogin issueTitle url -
switch -- $action {
assigned {
lappend actionAssigned [lindex $output end]
}
unassigned {
lappend actionUnassigned [lindex $output end]
}
labeled {
lappend actionLabeled [lindex $output end]
}
unlabeled {
lappend actionUnlabeled [lindex $output end]
}
milestoned {
lappend actionMilestoned [lindex $output end]
}
demilestoned {
lappend actionDemilestoned [lindex $output end]
}
opened {
lappend mainAction "opened"
}
closed {
lappend mainAction "closed"
}
reopened {
lappend mainAction "reopened"
}
}
}
if {[info exists mainAction] && [llength $mainAction] > 1} {
set mainAction [join $mainAction ", "]
}
if {![info exists mainAction]} {
if {[info exists actionAssigned]} {
set mainAction "assigned"
} elseif {[info exists actionUnassigned]} {
set mainAction "unassigned"
} elseif {[info exists actionLabeled]} {
set mainAction "labeled"
} elseif {[info exists actionUnlabeled]} {
set mainAction "unlabeled"
} elseif {[info exists actionMilestoned]} {
set mainAction "milestoned"
} elseif {[info exists actionDemilestoned]} {
set mainAction "demilestoned"
} else {
# this should never happen
set mainAction ""
}
}
set extraActions ""
# assigned
if {[info exists actionAssigned]} {
if {![string equal $mainAction "assigned"]} {
append extraActions " and assigned it"
}
append extraActions " to [join $actionAssigned ", "]"
}
# unassigned
if {[info exists actionUnassigned]} {
if {![string equal $mainAction "unassigned"]} {
if {[info exists actionAssigned]} {
append extraActions ", unassigned it"
} else {
append extraActions " and unassigned it"
}
}
append extraActions " from [join $actionUnassigned ", "]"
}
# labeled
if {[info exists actionLabeled]} {
if {![string equal $mainAction "labeled"]} {
if {[info exists actionAssigned] || [info exists actionUnassigned]} {
append extraActions ", labeled it"
} else {
append extraActions " and labeled it"
}
}
append extraActions " with [join $actionLabeled ", "]"
}
# unlabeled
if {[info exists actionUnlabeled]} {
if {![string equal $mainAction "unlabeled"]} {
if {[info exists actionAssigned] || [info exists actionUnassigned] || [info exists actionLabeled]} {
append extraActions ", unlabeled it"
} else {
append extraActions " and unlabeled it"
}
}
append extraActions " with [join $actionUnlabeled ", "]"
}
# milestoned
if {[info exists actionMilestoned]} {
if {![string equal $mainAction "milestoned"]} {
if {[info exists actionAssigned] || [info exists actionUnassigned] || [info exists actionLabeled] || [info exists actionUnlabeled]} {
append extraActions ", milestoned it"
} else {
append extraActions " and milestoned it"
}
}
append extraActions " with [join $actionMilestoned ", "]"
}
# demilestoned
if {[info exists actionDemilestoned]} {
if {![string equal $mainAction "demilestoned"]} {
if {[info exists actionAssigned] || [info exists actionUnassigned] || [info exists actionLabeled] || [info exists actionUnlabeled] || [info exists actionMilestoned]} {
append extraActions ", demilestoned it"
} else {
append extraActions " and demilestoned it"
}
}
}
set msg "\[${repName}\] $senderLogin $mainAction issue #${issueNum} (${issueTitle})${extraActions} [gitio $url]"
putloglev d * "github.tcl: msg: $msg"
outputMsg $event $path [list $msg] $directChan
unset delayedSendIds($id)
return
}
default {
putlog "github.tcl error: delayedSend for unhandled event: $event"
return
}
}
}
}
# main parsing proc that gets called after a new payload is received
proc ::github::processData {event path data {directChan ""}} {
variable delayedSendIds
set delayedSend 0; # this is upvar'd from parseJson
set output [parseJson $event $data]
if {$delayedSend} {
switch -- $event {
issues {
# output == $repName $issueNum $action $senderLogin $issueTitle $url [action-specific]
lassign $output repName issueNum -
set id "$repName,$issueNum"
}
default {
putlog "github.tcl error: processData for unhandled event: $event"
return
}
}
if {![info exists delayedSendIds($id)]} {
set delayedSendIds($id) 0
}
lappend delayedSendIds($id) $output
set delayedSendIds($id) [lreplace $delayedSendIds($id) 0 0 [llength $delayedSendIds($id)]]
putloglev d * "github.tcl: calling utimer with $event <> $path <> $directChan <> $id <> [llength $delayedSendIds($id)]"
# FixMe: I don't like this, if there's any error in the proc then delayedSendIds will grow forever. Maybe add some short proc
# in between that's responsible for calling delayedSend and unsetting delayedSendIds
utimer 10 [list ::github::delayedSend $event $path $directChan $id [llength $delayedSendIds($id)]]
return
}
outputMsg $event $path $output $directChan
return
}
# output to IRC
proc ::github::outputMsg {event path output {directChan ""}} {
variable settings
variable privmsgTargMax
if {![string equal $output ""]} {
if {![string equal $directChan ""]} {
foreach line $output {
putserv "PRIVMSG $directChan :$line"
}
return
}
# find channels to output to and stick them in $targets
foreach name [dict keys $settings] {
if {[dict exists $settings $name path] && [string equal [dict get $settings $name path] $path]} {
foreach c [channels] {
if {[dict exists $settings $name channels $c]} {
foreach {setChan setEvents} [dict get $settings $name channels] {
if {([ircstreql $c $setChan]) && ([lsearch -exact $setEvents $event] != -1)} {
lappend targets $c
}
}
}
}
}
}
# output to the appropriate channels
foreach line $output {
if {[info exists targets]} {
foreach target $targets {
if {[llength [lappend outChans $target]] == $privmsgTargMax} {
putserv "PRIVMSG [join $outChans ","] :$line"
unset outChans
}
if {[info exists outChans]} {
putserv "PRIVMSG [join $outChans ","] :$line"
}
}
} else {
putloglev d * "github.tcl processed \"${event}\" event but found no channels to output to: $line"
}
}
}
return
}
proc ::github::cleanup {sock} {
variable state
set state [dict remove $state $sock]
catch { chan flush $sock }
catch { chan close $sock }
return
}
proc ::github::sendError {sock code errmsg} {
variable state
array set errors {
400 {Bad Request}
401 {Unauthorized}