forked from bryanmacfarlane/project-reports-action
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproject-reports-lib.ts
563 lines (463 loc) · 13.4 KB
/
project-reports-lib.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
import clone from 'clone'
import moment from 'moment'
import * as os from 'os'
import * as url from 'url'
// TODO: separate npm module. for now it's a file till we flush out
export * from './project-reports-schemes'
export interface RepoProps {
owner: string
repo: string
}
export function repoPropsFromUrl(htmlUrl: string): RepoProps {
const rUrl = new url.URL(htmlUrl)
const parts = rUrl.pathname.split('/').filter(e => e)
return <RepoProps>{
owner: parts[0],
repo: parts[1]
}
}
//
// filter cards by label
//
export function filterByLabel(issues: ProjectIssue[], name: string): ProjectIssue[] {
return issues.filter(
card => card.labels.findIndex(label => label.name.trim().toLowerCase() === name.toLowerCase()) >= 0
)
}
//
// Get number from a label by regex.
// e.g. get 2 from label "2-wip", new RegExp("(\\d+)-wip")
// returns NaN if no labels match
//
export function getCountFromLabel(card: ProjectIssue, re: RegExp): number {
let num = NaN
for (const label of card.labels) {
const matches = label.name.match(re)
if (matches && matches.length > 0) {
num = parseInt(matches[1])
if (num) {
break
}
}
}
return num
}
export function getStringFromLabel(card: ProjectIssue, re: RegExp): string {
let str = ''
for (const label of card.labels) {
const matches = label.name.trim().match(re)
if (matches && matches.length > 0) {
str = matches[0]
if (str) {
break
}
}
}
if (str) {
str = str.trim()
}
return str
}
//
// Will read a value from a field in the form of a key: value
//
// somekey: some value
//
// or, a heading key with the value being the next non empty line.
// for example, if the key was '### somekey'
//
// ### somekey
//
// some value
//
export function readFieldFromBody(key: string, body: string): string {
let val = ''
let headerMatch = false
if (!body || body.length === 0) {
return val
}
const lines = body.split(os.EOL)
for (let i = 0; i < lines.length; i++) {
let line = lines[i]
if (headerMatch && line.trim().length > 0) {
// previous non empty line was the key as a heading
return line.trim()
}
line = line.trim()
const parts = line.split(':')
if (parts.length === 2 && fuzzyMatch(parts[0], key)) {
val = parts[1].trim()
break
} else if (line.toLowerCase() === key.toLowerCase()) {
headerMatch = true
}
}
return val
}
//
// reads a fields value an issue by reading issue body first and then the comment bodies from last to first
//
export function getLastCommentField(issue: ProjectIssue, field: string): string {
let val = ''
if (!issue.comments) {
return ''
}
val = readFieldFromBody(field, issue.body)
for (let i = issue.comments.length - 1; i >= 0; i--) {
const comment = issue.comments[i]
if (!comment) {
break
}
const commentValue = readFieldFromBody(field, comment.body)
if (commentValue) {
val = commentValue
break
}
}
return val
}
// returns a valid date field value from a comment field
export function getLastCommentDateField(issue: ProjectIssue, field: string): Date {
let d: Date = null
const val = getLastCommentField(issue, field)
if (val) {
d = new Date(val)
}
return d
}
export function sumCardProperty(cards: ProjectIssue[], prop: string): number {
return cards.reduce((a, b) => a + (b[prop] || 0), 0)
}
export function fuzzyMatch(content: string, match: string): boolean {
let matchWords = match.match(/[a-zA-Z0-9]+/g)
matchWords = matchWords.map(item => item.toLowerCase())
let contentWords = content.match(/[a-zA-Z0-9]+/g)
contentWords = contentWords.map(item => item.toLowerCase())
let isMatch = true
for (const matchWord of matchWords) {
if (contentWords.indexOf(matchWord) === -1) {
isMatch = false
break
}
}
return isMatch
}
export function extractUrlsFromChecklist(body: string): string[] {
return body?.match(/(?<=-\s*\[.*?\].*?)(https?:\/{2}(?:[/-\w.]|(?:%[\da-fA-F]{2}))+)/g) || []
}
// Project issues keyed by the stage they are in
export interface ProjectIssues {
stages: {[key: string]: ProjectIssue[]}
}
export interface ProjectColumn {
cards_url: string
id: number
name: string
}
// stages more discoverable
export const ProjectStages = {
Proposed: 'Proposed',
Accepted: 'Accepted',
InProgress: 'In-Progress',
Done: 'Done',
Missing: 'Missing'
}
export type ProjectStageIssues = {[key: string]: ProjectIssue[]}
export function getProjectStageIssues(issues: ProjectIssue[]) {
const projIssues = <ProjectStageIssues>{}
for (const projIssue of issues) {
const stage = projIssue['project_stage']
if (!stage) {
// the engine will handle and add to an issues list
continue
}
if (!projIssues[stage]) {
projIssues[stage] = []
}
projIssues[stage].push(projIssue)
}
return projIssues
}
export interface IssueLabel {
name: string
color: string
}
export interface IssueCardEventProject {
project_id: number
column_name: string
previous_column_name: string
stage_name: string
previous_stage_name: string
}
export interface IssueEvent {
created_at: Date
event: string
assignee: IssueUser
label: IssueLabel
project_card: IssueCardEventProject
//data: any
}
export interface IssueUser {
login: string
id: number
avatar_url: string
url: string
html_url: string
}
export interface IssueMilestone {
title: string
description: string
due_on: Date
}
export interface IssueComment {
body: string
user: IssueUser
created_at: Date
updated_at: Date
}
export interface ProjectIssue {
title: string
body: string
number: number
html_url: string
state: string
labels: IssueLabel[]
assignee: IssueUser
assignees: IssueUser[]
user: IssueUser
milestone: IssueMilestone
closed_at: Date
created_at: Date
updated_at: Date
comments: IssueComment[]
events: IssueEvent[]
//
// project stage fields we decorate on issues
//
// first added to the board on any column (no "from" column)
project_added_at: Date
// last occurence of moving to these columns from a lesser or no column
// example. if moved to accepted from proposed (or less),
// then in-progress (greater) and then back to accepted, first wins
project_proposed_at: Date
project_accepted_at: Date
project_in_progress_at: Date
// cleared if not currently blocked
project_blocked_at: Date
// cleared if it moves out of done. e.g. current state has to be done for this to be set
project_done_at: Date
// current stage of this card on the board
project_stage: string
// current column of this card on the board
project_column: string
}
const stageLevel = {
None: 0,
Proposed: 1,
Accepted: 2,
'In-Progress': 3,
Done: 4,
Unmapped: 5
}
export class IssueList {
private seen
private identifier
private items: ProjectIssue[]
private processed: ProjectIssue[]
// keep in order indexed by level above
// TODO: unify both to avoid out of sync problems
stageAtNames = ['none', 'project_proposed_at', 'project_accepted_at', 'project_in_progress_at', 'project_done_at']
constructor(identifier: (item) => any) {
this.seen = new Map()
this.identifier = identifier
this.items = []
}
// returns whether any were added
public add(data: any | any[]): boolean {
this.processed = null
let added = false
if (Array.isArray(data)) {
for (const item of data) {
const res = this.add_item(item)
if (!added) {
added = res
}
}
} else {
return this.add_item(data)
}
return added
}
private add_item(item: any): boolean {
const id = this.identifier(item)
if (!this.seen.has(id)) {
this.items.push(item)
this.seen.set(id, item)
return true
}
return false
}
public getItem(identifier: any): ProjectIssue {
return this.seen.get(identifier)
}
public getItems(): ProjectIssue[] {
if (this.processed) {
return this.processed
}
// call process
for (const item of this.items) {
this.processStages(item)
}
this.processed = this.items
return this.processed
}
public getItemsAsof(datetime: Date): ProjectIssue[] {
const issues: ProjectIssue[] = []
for (const item of this.items) {
const id = this.identifier(item)
issues.push(this.getItemAsof(id, datetime))
}
return issues
}
//
// Gets an issue from a number of days, hours ago.
// Clones the issue and Replays events (labels, column moves, milestones)
// and reprocesses the stages.
// If the issue doesn't exist in the list, returns null
//
public getItemAsof(identifier: any, datetime: string | Date): ProjectIssue {
console.log(`getting asof ${datetime} : ${identifier}`)
let issue = this.getItem(identifier)
if (!issue) {
return issue
}
issue = clone(issue)
const momentAgo = moment(datetime)
// clear everything we're going to re-apply
issue.labels = []
delete issue.project_column
delete issue.project_added_at
delete issue.project_proposed_at
delete issue.project_in_progress_at
delete issue.project_accepted_at
delete issue.project_done_at
delete issue.project_stage
delete issue.closed_at
// stages and labels
const filteredEvents: IssueEvent[] = []
const labelMap: {[name: string]: IssueLabel} = {}
if (issue.events) {
for (const event of issue.events) {
if (moment(event.created_at).isAfter(momentAgo)) {
continue
}
filteredEvents.push(event)
if (event.event === 'labeled') {
labelMap[event.label.name] = event.label
} else if (event.event === 'unlabeled') {
delete labelMap[event.label.name]
}
if (event.event === 'closed') {
issue.closed_at = event.created_at
}
if (event.event === 'reopened') {
delete issue.closed_at
}
}
}
issue.events = filteredEvents
for (const labelName in labelMap) {
issue.labels.push(labelMap[labelName])
}
this.processStages(issue)
// comments
const filteredComments: IssueComment[] = []
for (const comment of issue.comments) {
if (moment(comment.created_at).isAfter(momentAgo)) {
continue
}
filteredComments.push(comment)
}
issue.comments = filteredComments
return issue
}
//
// Process the events to set project specific fields like project_done_at, project_in_progress_at, etc
// Call initially and then call again if events are filtered (get issue asof)
//
private processStages(issue: ProjectIssue): void {
console.log()
console.log(`Processing stages for ${issue.html_url}`)
// card events should be in order chronologically
let currentStage: string
let currentColumn: string
let doneTime: Date
let addedTime: Date
const tempLabels = {}
if (issue.events) {
for (const event of issue.events) {
let eventDateTime: Date
if (event.created_at) {
eventDateTime = event.created_at
}
//
// Process Project Stages
//
let toStage: string
let toLevel: number
let fromStage: string
let fromLevel = 0
if (event.project_card && event.project_card.column_name) {
if (!addedTime) {
addedTime = eventDateTime
}
if (issue.project_stage !== 'None' && !event.project_card.stage_name) {
throw new Error(`stage_name should have been set already for ${event.project_card.column_name}`)
}
toStage = event.project_card.stage_name
toLevel = stageLevel[toStage]
currentStage = toStage
currentColumn = event.project_card.column_name
}
if (issue.project_stage !== 'None' && event.project_card && event.project_card.previous_column_name) {
if (!event.project_card.previous_stage_name) {
throw new Error(
`previous_stage_name should have been set already for ${event.project_card.previous_column_name}`
)
}
fromStage = event.project_card.previous_stage_name
fromLevel = stageLevel[fromStage]
}
// last occurence of moving to a stage from a lesser stage
// example: if an item is not blocked but put on hold for 6 months,
// then the in-progress date will be when it went back in progress
// moving forward
if (fromLevel < toLevel) {
issue[this.stageAtNames[toLevel]] = eventDateTime
}
//moving back, clear the stage at dates up to fromLevel
else if (fromLevel > toLevel) {
for (let i = toLevel + 1; i <= fromLevel; i++) {
delete issue[this.stageAtNames[i]]
}
}
}
if (addedTime) {
issue.project_added_at = addedTime
console.log(`project_added_at: ${issue.project_added_at}`)
}
// current board processing does by column so we already know these
// asof replays events and it's possible to have the same time and therefore can be out of order.
// only take that fragility during narrow asof cases.
// asof clears these
if (!issue.project_column) {
issue.project_column = currentColumn
}
if (!issue.project_stage) {
issue.project_stage = currentStage
}
console.log(`project_stage: ${issue.project_stage}`)
console.log(`project_column: ${issue.project_column}`)
}
}
}