-
Notifications
You must be signed in to change notification settings - Fork 2
/
github-issues-notice.ts
615 lines (553 loc) · 15.6 KB
/
github-issues-notice.ts
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
/**
* GitHub issues notice
*
* Copyright (c) 2018 Tomohisa Oda
*/
import { Github, Issue, PullRequest } from './github'
import { Slack, Attachment } from './slack'
/**
* GithubIssuesNotice
*/
export class GithubIssuesNotice {
private get slack(): Slack {
if (this.pSlack === undefined) {
this.pSlack = new Slack(this.config.slack.token)
}
return this.pSlack
}
private get github(): Github {
if (this.pGithub === undefined) {
if (this.config.github.apiEndpoint) {
this.pGithub = new Github(
this.config.github.token,
this.config.github.apiEndpoint
)
} else {
this.pGithub = new Github(this.config.github.token)
}
}
return this.pGithub
}
private get sheet(): GoogleAppsScript.Spreadsheet.Sheet {
if (this.pSheet === undefined) {
const s = SpreadsheetApp.openById(this.config.spreadsheets.id)
this.pSheet = s.getSheetByName('config')
}
return this.pSheet
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private get data(): any[][] {
if (this.pData === undefined) {
const startRow = 2
const startColumn = 1
const numRow = this.sheet.getLastRow()
const numColumn = this.sheet.getLastColumn()
this.pData = this.sheet.getSheetValues(
startRow,
startColumn,
numRow,
numColumn
)
}
return this.pData
}
private get isHoliday(): boolean {
if (this.pIsHoliday === undefined) {
const date = this.config.now
const startWeek = 0
const endWeek = 6
const weekInt = date.getDay()
if (weekInt <= startWeek || endWeek <= weekInt) {
this.pIsHoliday = true
} else {
const calendarId = 'ja.japanese#holiday@group.v.calendar.google.com'
const calendar = CalendarApp.getCalendarById(calendarId)
const events = calendar.getEventsForDay(date)
this.pIsHoliday = events.length > 0
}
}
return this.pIsHoliday
}
public config: Config
private pSheet: GoogleAppsScript.Spreadsheet.Sheet
private pSlack: Slack
private pGithub: Github
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private pData: any[][]
private pIsHoliday: boolean
constructor(c: Config) {
this.config = c
}
public static CAPITALIZE(word: string): string {
if (!word) {
return word
}
return word.replace(/\w\S*/g, t => {
return `${t.charAt(0).toUpperCase()}${t.substr(1).toLowerCase()}`
})
}
public static NORMALIZE(str: string): string[] {
const arr = str.split('\n')
for (let v of arr) {
v = v.trim()
}
return arr.filter(v => v)
}
private static statsEmoji(r: number): string {
const danger = 90
const caution = 80
const ng = 70
const warn = 60
const ok = 50
const good = 40
const great = 30
switch (true) {
case r > danger:
return ':skull:'
case r > caution:
return ':fire:'
case r > ng:
return ':jack_o_lantern:'
case r > warn:
return ':space_invader:'
case r > ok:
return ':surfer:'
case r > good:
return ':palm_tree:'
case r > great:
return ':helicopter:'
default:
return ':rocket:'
}
}
private static buildStatsAttachment(task: Task): Attachment {
const p = task.stats.pulls
const i = task.stats.issues
const a = task.stats.proactive
const hundred = 100
const r = hundred - Math.floor((a / (a + (i - a))) * hundred)
const url =
'https://github.com/linyows/github-issues-notice/blob/master/docs/reactive-per.md'
const m =
'--% :point_right: Please applying `proactive` label to voluntary issues'
const info = r === hundred ? m : `${GithubIssuesNotice.statsEmoji(r)} ${r}%`
return {
title: `Stats for ${task.repos.length} repositories`,
color: '#000000',
text: '',
footer: `Stats | <${url}|What is this?>`,
footer_icon: 'https://octodex.github.com/images/surftocat.png',
fields: [
{ title: 'Reactive Per', value: `${info}`, short: false },
{ title: 'Open Issues Total', value: `${i - p}`, short: true },
{ title: 'Open Pulls Total', value: `${p}`, short: true },
],
}
}
public doJob(): void {
const job = this.getJobByMatchedTime()
for (const t of job) {
this.doTask(t)
}
}
private tidyUpIssues(repo: string, task: Task) {
const oneD = 24
const oneH = 3600
const oneS = 1000
const now = this.config.now
const period = now.getTime() - task.idle.period * oneD * oneH * oneS
const displayRepo = task.repos.length > 1 ? ` (${task.showOrg ? repo : repo.split('/').pop()})` : ``
try {
const issues = this.github.issues(repo, {
sort: 'asc',
direction: 'updated',
})
for (const i of issues) {
if (Date.parse(i.updated_at) > period) {
continue
}
this.github.closeIssue(repo, i.number)
task.idle.issueTitles.push(
`<${i.html_url}|${i.title}>${displayRepo} by ${i.user.login}`
)
}
} catch (e) {
console.error(e)
}
}
private doTask(task: Task) {
for (const repo of task.repos) {
if (repo === '') {
continue
}
if (task.idle.period > 0) {
this.tidyUpIssues(repo, task)
}
if (task.stats.enabled) {
const i = this.github.issues(repo)
const p = this.github.pulls(repo)
const splited = repo.split('/')
const issueTotal = (i.length === 100) ? this.github.issueTotal(splited[0], splited[1]) : i.length
const labels = 'proactive'
const a = this.github.issues(repo, { labels })
task.stats.issues = task.stats.issues + issueTotal
task.stats.pulls = task.stats.pulls + p.length
task.stats.proactive = task.stats.proactive + a.length
}
const displayRepo = task.repos.length > 1 ? ` (${task.showOrg ? repo : repo.split('/').pop()})` : ``
for (const l of task.labels) {
try {
const labels = l.name
if (!task.onlyPulls) {
// Issues without Pull Request
const state = task.labelProtection ? 'all' : 'open'
const issues = this.github.issues(repo, { labels, state })
for (const i of issues) {
if (Github.IsPullRequestIssue(i)) {
continue
}
for (const ll of i.labels) {
if (l.name === ll.name) {
l.color = ll.color
}
}
const warn =
task.labelProtection && i.state === 'closed'
? ':warning: Closed: '
: ''
l.issueTitles.push(
`${warn}<${i.html_url}|${i.title}>${displayRepo} by ${
i.user.login
}${task.relations ? this.buildIssueRelations(i) : ''}`
)
}
}
// Pull Requests without Draft
const pulls = this.github.pullsWithoutDraftAndOnlySpecifiedLabels(
repo,
{ labels }
)
for (const i of pulls) {
for (const ll of i.labels) {
if (l.name === ll.name) {
l.color = ll.color
}
}
l.issueTitles.push(
`<${i.html_url}|${i.title}>${displayRepo} by ${i.user.login}${
task.relations ? this.buildPullRelations(i) : ''
}`
)
}
} catch (e) {
console.error(e)
}
}
}
this.notify(task)
}
private buildIssueRelations(i: Issue): string {
if (i.assignees.length == 0) {
return ''
}
return ` (Assignees: ${i.assignees
.map(u => {
return u.login
})
.join(', ')})`
}
private buildPullRelations(i: PullRequest): string {
if (i.assignees.length == 0 && i.requested_reviewers.length == 0) {
return ''
}
const r = []
if (i.assignees.length > 0) {
r.push(
'Assignees: ' +
i.assignees
.map(u => {
return u.login
})
.join(', ')
)
}
if (i.requested_reviewers.length > 0) {
r.push(
'Reviewers: ' +
i.requested_reviewers
.map(u => {
return u.login
})
.join(', ')
)
}
return ` (${r.join(', ')})`
}
private getTsIfDuplicated(channel: string): string {
const msgs = this.slack.conversationsHistory({ channel })
const msg = msgs[0]
return msg.username === this.config.slack.username &&
msg.text.indexOf(this.config.slack.textEmpty) !== -1
? msg.ts
: ''
}
private postMessageOrUpdate(channel: string) {
const ts = this.getTsIfDuplicated(channel)
if (ts === '') {
this.slack.postMessage({
channel,
username: this.config.slack.username,
icon_emoji: ':octocat:',
link_names: 1,
text: `${this.config.slack.textEmpty}${this.config.slack.textSuffix}`,
})
} else {
const updatedAt = ` -- :hourglass: last updated at: ${this.config.now}`
this.slack.chatUpdate({
channel,
text: `${this.config.slack.textEmpty}${this.config.slack.textSuffix}${updatedAt}`,
ts: ts,
})
}
}
private notify(task: Task) {
const attachments = []
const mention = ` ${task.mentions.join(' ')} `
let empty = true
if (task.stats.enabled) {
attachments.push(GithubIssuesNotice.buildStatsAttachment(task))
}
for (const l of task.labels) {
if (l.issueTitles.length === 0) {
continue
}
const h = l.name.replace(/-/g, ' ')
const m =
l.issueTitles.length > l.threshold
? `${l.name.length > 0 ? ' -- ' : ''}${l.message}`
: ''
empty = false
attachments.push({
title: `${
h.toUpperCase() === h ? h : GithubIssuesNotice.CAPITALIZE(h)
}${m}`,
color: l.color,
text: l.issueTitles.join('\n'),
})
}
if (task.idle.issueTitles.length > 0) {
const url =
'https://github.com/linyows/github-issues-notice/blob/master/docs/idle-period.md'
empty = false
attachments.push({
title: `Closed with no change over ${task.idle.period}days`,
color: '#CCCCCC',
text: task.idle.issueTitles.join('\n'),
footer: `Idle Period | <${url}|What is this?>`,
footer_icon:
'https://octodex.github.com/images/Sentrytocat_octodex.jpg',
fields: [
{
title: 'Closed Total',
value: `${task.idle.issueTitles.length}`,
short: true,
},
],
})
}
const messages = []
if (!empty) {
messages.push(this.config.slack.textDefault)
}
for (const channel of task.channels) {
try {
if (empty) {
this.postMessageOrUpdate(channel)
} else {
this.slack.postMessage({
channel,
username: this.config.slack.username,
icon_emoji: ':octocat:',
link_names: 1,
text: `${mention}${messages.join(' ')}${
this.config.slack.textSuffix
}`,
attachments: JSON.stringify(attachments),
})
}
} catch (e) {
console.error(e)
}
}
}
private getJobByMatchedTime(): Task[] {
const enabledColumn = 0
const channelColumn = 1
const timeColumn = 2
const mentionColumn = 3
const repoColumn = 4
const labelColumn = 5
const statsColumn = 6
const idleColumn = 7
const relationsColumn = 8
const onlyPullsColumn = 9
const labelProtectionColumn = 10
const showOrgColumn = 11
const noHolidayColumn = 12
const nameField = 0
const thresholdField = 1
const messageField = 2
const job: Task[] = []
const timeLength = 2
const timeFullLength = 4
const minStart = 2
const nowH = `0${this.config.now.getHours()}`.slice(-timeLength)
const nowM = `00${this.config.now.getMinutes()}`.slice(-timeLength)
for (const task of this.data) {
const repos = GithubIssuesNotice.NORMALIZE(`${task[repoColumn]}`)
if (repos.length === 0) {
continue
}
const enabled = task[enabledColumn]
if (typeof enabled === 'boolean') {
if (!enabled) {
continue
}
} else {
console.error(`"enabled" columns must be of type boolean: ${enabled}`)
}
const channels = GithubIssuesNotice.NORMALIZE(`${task[channelColumn]}`)
const times = GithubIssuesNotice.NORMALIZE(`${task[timeColumn]}`)
const mentions = GithubIssuesNotice.NORMALIZE(`${task[mentionColumn]}`)
const labelsWithInfo = GithubIssuesNotice.NORMALIZE(
`${task[labelColumn]}`
)
let relations = task[relationsColumn]
if (typeof relations !== 'boolean') {
relations = false
}
let onlyPulls = task[onlyPullsColumn]
if (typeof onlyPulls !== 'boolean') {
onlyPulls = false
}
let labelProtection = task[labelProtectionColumn]
if (typeof labelProtection !== 'boolean') {
labelProtection = false
}
let showOrg = task[showOrgColumn]
if (typeof showOrg !== 'boolean') {
showOrg = false
}
let noHoliday = task[noHolidayColumn]
if (typeof noHoliday !== 'boolean') {
noHoliday = false
}
let s = task[statsColumn]
if (typeof s !== 'boolean') {
s = false
}
const stats: Stats = {
enabled: s,
issues: 0,
pulls: 0,
proactive: 0,
}
let idlePeriod = task[idleColumn]
if (typeof idlePeriod !== 'number') {
idlePeriod = 0
}
const idle: Idle = {
period: idlePeriod,
issueTitles: [],
}
for (const time of times) {
const hour = time.substr(0, timeLength)
const min =
time.length === timeFullLength
? time.substr(minStart, timeLength)
: '00'
if (hour === nowH && min === nowM) {
const labels: Label[] = []
for (const l of labelsWithInfo) {
const arr = `${l}`.split('/')
labels.push({
name: arr[nameField],
threshold: +arr[thresholdField],
message: arr[messageField],
color: '',
issueTitles: [],
})
}
if (this.isHoliday && !noHoliday) {
continue
}
job.push({
channels,
times,
mentions,
repos,
labels,
stats,
idle,
relations,
onlyPulls,
labelProtection,
showOrg,
})
}
}
}
return job
}
}
type GithubConfig = {
token: string
apiEndpoint?: string
}
type SlackConfig = {
token: string
username: string
textSuffix: string
textEmpty: string
textDefault: string
}
type SpreadsheetsConfig = {
id: string
url: string
}
type Config = {
now: Date
slack: SlackConfig
github: GithubConfig
spreadsheets: SpreadsheetsConfig
}
type Task = {
channels: string[]
times: string[]
mentions: string[]
repos: string[]
labels: Label[]
stats: Stats
idle: Idle
relations: boolean
onlyPulls: boolean
labelProtection: boolean
showOrg: boolean
}
type Idle = {
period: number
issueTitles: string[]
}
type Stats = {
enabled: boolean
issues: number
pulls: number
proactive: number
}
type Label = {
name: string
threshold: number
message: string
color: string
issueTitles: string[]
}