-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathindex.ts
More file actions
460 lines (408 loc) · 15.7 KB
/
index.ts
File metadata and controls
460 lines (408 loc) · 15.7 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
import { executeDiff } from '../../utils/diff/diff'
import { Flags, Args } from '@oclif/core'
import { uniqBy } from 'lodash'
import { executeFileDiff } from '../../utils/diff/fileDiff'
import { parseFiles } from '../../utils/diff/parse'
import { VariableDiffMatch } from '../../utils/parsers/types'
import Base from '../base'
import { sha256 } from 'js-sha256'
import { createHash } from 'node:crypto'
import { fetchVariableByKey } from '../../api/variables'
import ClientNameFlag, { getClientNames } from '../../flags/client-name'
import MatchPatternFlag, { getMatchPatterns } from '../../flags/match-pattern'
import VarAliasFlag, { getVariableAliases } from '../../flags/var-alias'
import ShowRegexFlag, { showRegex } from '../../flags/show-regex'
import { Variable } from '../../api/schemas'
import { FileFilters } from '../../utils/FileFilters'
const EMOJI = {
add: '🟢',
remove: '🔴',
notice: '⚠️',
cleanup: '🧹',
}
type MatchesByType = {
add: Record<string, VariableDiffMatch[]>
remove: Record<string, VariableDiffMatch[]>
addUnknown: Record<string, VariableDiffMatch[]>
removeUnknown: Record<string, VariableDiffMatch[]>
}
type MatchEnriched = {
variable: Variable | null
matches: VariableDiffMatch[]
}
type MatchesByTypeEnriched = {
add: Record<string, MatchEnriched>
remove: Record<string, MatchEnriched>
notFoundAdd: Record<string, MatchEnriched>
notFoundRemove: Record<string, MatchEnriched>
addUnknown: Record<string, MatchEnriched>
removeUnknown: Record<string, MatchEnriched>
}
export default class Diff extends Base {
static hidden = false
authSuggested = true
static description =
'Print a diff of DevCycle variable usage between two versions of your code.'
static examples = [
'<%= config.bin %> <%= command.id %>',
'<%= config.bin %> <%= command.id %> ' +
'--match-pattern js="dvcClient\\.variable\\(\\s*["\']([^"\']*)["\']"',
]
static flags = {
...Base.flags,
include: Flags.string({
description:
'Files to include in the diff. By default all files are included. ' +
'Accepts multiple glob patterns.',
multiple: true,
}),
exclude: Flags.string({
description:
'Files to exclude in the diff. By default all files are included. ' +
'Accepts multiple glob patterns.',
multiple: true,
}),
file: Flags.string({
char: 'f',
description: 'File path of existing diff file to inspect.',
}),
'client-name': ClientNameFlag,
'match-pattern': MatchPatternFlag,
'var-alias': VarAliasFlag,
'pr-link': Flags.string({
hidden: true,
description:
'Link to the PR to use for formatting the line number outputs with clickable links.',
}),
format: Flags.string({
default: 'console',
options: ['console', 'markdown', 'markdown-no-html'],
description: 'Format to use when outputting the diff results.',
}),
'show-regex': ShowRegexFlag,
}
static args = {
'diff-pattern': Args.string({
name: 'diff-pattern',
description:
'A "git diff"-compatible diff pattern, eg. "branch1 branch2"',
}),
}
useMarkdown = false
useHTML = false
public async run(): Promise<void> {
const { args, flags } = await this.parse(Diff)
if (!flags.file && !args['diff-pattern']) {
this.writer.showError('Must provide a diff pattern')
return
}
const codeInsightsConfig = this.repoConfig?.codeInsights || {}
this.useMarkdown = flags.format.includes('markdown')
this.useHTML = flags.format === 'markdown'
let parsedDiff = flags.file
? executeFileDiff(flags.file)
: args['diff-pattern']
? executeDiff(args['diff-pattern'])
: []
const fileFilter = new FileFilters(flags, codeInsightsConfig)
parsedDiff = parsedDiff.filter(({ from = '', to = '' }) => {
return (
fileFilter.shouldIncludeFile(from) ||
fileFilter.shouldIncludeFile(to)
)
})
const matchesBySdk = parseFiles(parsedDiff, {
clientNames: getClientNames(flags, this.repoConfig),
matchPatterns: getMatchPatterns(flags, this.repoConfig),
printPatterns: showRegex(flags),
})
const variableAliases = getVariableAliases(flags, this.repoConfig)
const matchesByType = this.getMatchesByType(
matchesBySdk,
variableAliases,
)
const matchesByTypeEnriched =
await this.fetchVariableData(matchesByType)
this.formatOutput(matchesByTypeEnriched, flags['pr-link'])
}
private useApi() {
return this.hasToken() && this.projectKey !== '' && this.noApi !== true
}
private getMatchesByType(
matchesBySdk: Record<string, VariableDiffMatch[]>,
aliasMap: Record<string, string>,
): MatchesByType {
const matchesByType: MatchesByType = {
add: {},
remove: {},
addUnknown: {},
removeUnknown: {},
}
Object.values(matchesBySdk).forEach((matches) => {
matches.forEach((m) => {
const match = { ...m }
const aliasedName = aliasMap[match.name]
if (match.isUnknown && aliasedName) {
match.alias = match.name
match.name = aliasedName
delete match.isUnknown
}
const mode: keyof MatchesByType = `${match.mode}${match.isUnknown ? 'Unknown' : ''}`
matchesByType[mode] ??= {}
matchesByType[mode][match.name] ??= []
matchesByType[mode][match.name].push(match)
matchesByType[mode][match.name] = uniqBy(
matchesByType[mode][match.name],
(m) => `${m.fileName}:${m.line}`,
)
})
})
return matchesByType
}
private async fetchVariableData(
matchesByType: MatchesByType,
): Promise<MatchesByTypeEnriched> {
const categories: MatchesByTypeEnriched = {
add: {},
remove: {},
notFoundAdd: {},
notFoundRemove: {},
addUnknown: {},
removeUnknown: {},
}
const fetchAndCategorize = async (
matches: Record<string, VariableDiffMatch[]>,
category: 'add' | 'remove',
) => {
const keys = Object.keys(matches)
const variablesByKey: Record<string, Variable | null> = {}
if (this.useApi()) {
const token = this.authToken
const projectKey = this.projectKey
await Promise.all(
keys.map(async (key: string) => {
variablesByKey[key] = await fetchVariableByKey(
token,
projectKey,
key,
)
}),
)
}
for (const key of Object.keys(matches)) {
categories[category][key] = {
variable: variablesByKey[key],
matches: matches[key],
}
if (!variablesByKey[key] && this.useApi()) {
categories[
category === 'add' ? 'notFoundAdd' : 'notFoundRemove'
][key] = {
variable: null,
matches: matches[key],
}
}
}
}
await Promise.all([
fetchAndCategorize(matchesByType.add, 'add'),
fetchAndCategorize(matchesByType.remove, 'remove'),
])
const enrichedAddUnknown: Record<string, MatchEnriched> = {}
const enrichedRemoveUnknown: Record<string, MatchEnriched> = {}
for (const [key, matches] of Object.entries(matchesByType.addUnknown)) {
enrichedAddUnknown[key] = {
variable: null,
matches,
}
}
for (const [key, matches] of Object.entries(
matchesByType.removeUnknown,
)) {
enrichedRemoveUnknown[key] = {
variable: null,
matches,
}
}
categories.addUnknown = enrichedAddUnknown
categories.removeUnknown = enrichedRemoveUnknown
return categories
}
private formatOutput(
matchesByTypeEnriched: MatchesByTypeEnriched,
prLink?: string,
) {
const additions = {
...matchesByTypeEnriched.add,
...matchesByTypeEnriched.addUnknown,
}
const deletions = {
...matchesByTypeEnriched.remove,
...matchesByTypeEnriched.removeUnknown,
}
const totalAdditions = Object.keys(additions).length
const totalDeletions = Object.keys(deletions).length
const totalNotices =
Object.keys(matchesByTypeEnriched.notFoundAdd).length +
Object.keys(matchesByTypeEnriched.addUnknown).length +
Object.keys(matchesByTypeEnriched.removeUnknown).length
const totalCleanup = Object.keys(
matchesByTypeEnriched.notFoundRemove,
).length
const headerPrefix = this.useMarkdown ? '## ' : ''
const headerText = 'DevCycle Variable Changes:\n'
const subHeaderPrefix = this.useMarkdown ? '### ' : ''
let headerIcon = ''
if (this.useHTML) {
const lightTogglebot = 'togglebot.svg#gh-light-mode-only'
const darkTogglebot = 'togglebot-white.svg#gh-dark-mode-only'
const buildIcon = (icon: string) =>
`<img src="https://github.com/DevCycleHQ/cli/raw/main/assets/${icon}" height="31px" align="center"/>`
headerIcon = `${buildIcon(lightTogglebot)}${buildIcon(darkTogglebot)} `
}
const totalChanges =
totalAdditions + totalDeletions + totalNotices + totalCleanup
if (totalChanges === 0) {
this.log(
`\n${subHeaderPrefix}${headerIcon}No DevCycle Variables Changed\n`,
)
return
}
this.log(`\n${headerPrefix}${headerIcon}${headerText}`)
if (totalNotices) {
this.log(
`${EMOJI.notice} ${totalNotices} Variable${totalNotices === 1 ? '' : 's'} With Notices`,
)
}
this.log(
`${EMOJI.add} ${totalAdditions} Variable${totalAdditions === 1 ? '' : 's'} Added`,
)
this.log(
`${EMOJI.remove} ${totalDeletions} Variable${totalDeletions === 1 ? '' : 's'} Removed`,
)
if (totalCleanup) {
this.log(
`${EMOJI.cleanup} ${totalCleanup} Variable${totalCleanup === 1 ? '' : 's'} Cleaned up`,
)
}
if (totalNotices) {
this.log(`\n${subHeaderPrefix}${EMOJI.notice} Notices\n`)
this.logNotices(matchesByTypeEnriched)
}
if (totalAdditions) {
this.log(`\n${subHeaderPrefix}${EMOJI.add} Added\n`)
this.logMatches(additions, 'add', prLink)
}
if (totalDeletions) {
this.log(`\n${subHeaderPrefix}${EMOJI.remove} Removed\n`)
this.logMatches(deletions, 'remove', prLink)
}
if (totalCleanup) {
this.log(`\n${subHeaderPrefix}${EMOJI.cleanup} Cleaned Up\n`)
this.log(
'The following variables that do not exist in DevCycle were cleaned up:\n',
)
this.logCleanup(matchesByTypeEnriched)
}
}
private logNotices(matchesByTypeEnriched: MatchesByTypeEnriched) {
let offset = 0
Object.entries(matchesByTypeEnriched.notFoundAdd).forEach(
([variableName], idx) => {
this.log(
` ${idx + 1}. Variable "${variableName}" does not exist on DevCycle`,
)
offset = idx + 1
},
)
Object.entries({
...matchesByTypeEnriched.addUnknown,
...matchesByTypeEnriched.removeUnknown,
}).forEach(([variableName], idx) => {
this.log(
` ${offset + idx + 1}. ` +
`Variable "${variableName}" could not be identified. Try adding an alias.`,
)
})
}
private logCleanup(matchesByTypeEnriched: MatchesByTypeEnriched) {
Object.entries(matchesByTypeEnriched.notFoundRemove).forEach(
([variableName], idx) => {
this.log(` ${idx + 1}. ${variableName}`)
},
)
}
private logMatches(
matchesByVariable: Record<string, MatchEnriched>,
mode: 'add' | 'remove',
prLink?: string,
) {
Object.entries(matchesByVariable).forEach(
([variableName, enriched], idx) => {
const matches = enriched.matches
const notFound = this.useApi() && !enriched.variable
const isUnknown = enriched.matches.some(
(match) => match.isUnknown,
)
const hasNotice =
(mode === 'add' && (notFound || isUnknown)) ||
(mode === 'remove' && isUnknown)
const hasCleanup = mode === 'remove' && notFound
const formattedName = this.useMarkdown
? `**${variableName}**`
: variableName
this.log(
` ${idx + 1}. ${formattedName}` +
`${hasNotice ? ` ${EMOJI.notice}` : ''}${hasCleanup ? ` ${EMOJI.cleanup}` : ''}`,
)
if (enriched.variable?.type) {
this.log(`\t Type: ${enriched.variable.type}`)
}
this.logLocations(matches, mode, prLink)
},
)
}
private logLocations(
matches: VariableDiffMatch[],
mode: 'add' | 'remove',
prLink?: string,
) {
const formatPrLink = (fileName: string, line: number) => {
const displayName = `${fileName}:L${line}`
let link = ''
if (prLink?.includes('bitbucket')) {
link = `${prLink}#L${fileName}${mode === 'add' ? 'T' : 'F'}${line}`
} else if (prLink?.includes('gitlab')) {
// TODO: include line number in link if possible
const sha1Hash = createHash('sha1')
.update(fileName)
.digest('hex')
link = `${prLink}/diffs#diff-content-${sha1Hash}`
} else {
link = `${prLink}/files#diff-${sha256(fileName)}${mode === 'add' ? 'R' : 'L'}${line}`
}
return `[${displayName}](${link})`
}
matches.sort((a, b) => {
if (a.fileName === b.fileName) return a.line > b.line ? 1 : -1
return a.fileName > b.fileName ? 1 : -1
})
if (matches.length === 1) {
const { fileName, line } = matches[0]
if (prLink) {
this.log(`\t Location: ${formatPrLink(fileName, line)}`)
} else {
this.log(`\t Location: ${fileName}:L${line}`)
}
} else {
this.log('\t Locations:')
matches.forEach(({ fileName, line }) => {
if (prLink) {
this.log(`\t - ${formatPrLink(fileName, line)}`)
} else {
this.log(`\t - ${fileName}:L${line}`)
}
})
}
}
}