forked from todogroup/repolinter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-contents.js
646 lines (611 loc) · 22.8 KB
/
file-contents.js
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
// Copyright 2017 TODO Group. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// eslint-disable-next-line no-unused-vars
const Result = require('../lib/result')
// eslint-disable-next-line no-unused-vars
const FileSystem = require('../lib/file_system')
const simpleGit = require('simple-git')
function getContent(options) {
return options['human-readable-content'] !== undefined
? options['human-readable-content']
: options.content
}
function getContext(matchedLine, regexMatch, contextLength) {
const matchStart = regexMatch.index
const contextStart =
matchStart - contextLength > 0 ? matchStart - contextLength : 0
const contextEnd = Math.min(
regexMatch.index + regexMatch[0].length + contextLength,
matchedLine.length
)
return matchedLine.substring(contextStart, contextEnd)
}
/**
* Check if a list of files contains a regular expression.
*
* @param {FileSystem} fs A filesystem object configured with filter paths and target directories
* @param {object} options The rule configuration
* @param {boolean} not Whether or not to invert the result (not contents instead of contents)
* @param {boolean} any Whether to check if the regular expression is contained by at least one of the files in the list
* @returns {Promise<Result>} The lint rule result
* @ignore
*/
async function fileContents(fs, options, not = false, any = false) {
// support legacy configuration keys
const fileList = (any ? options.globsAny : options.globsAll) || options.files
const files = await fs.findAllFiles(fileList, !!options.nocase)
const regexFlags = options.flags || ''
const branchOptionEnabled = isBranchOptionEnabled(options)
if (branchOptionEnabled) {
return await fileContentsWithBranchOption(fs, options, not, any, undefined)
}
if (files.length === 0) {
return new Result(
'Did not find file matching the specified patterns',
fileList.map(f => {
return { passed: !options['fail-on-non-existent'], pattern: f }
}),
!options['fail-on-non-existent']
)
}
const regex = new RegExp(options.content, regexFlags)
let results
if (!options['display-result-context']) {
/**
* Default "Contains" / "Doesn't contain"
* @ignore
*/
results = await Promise.all(
files.map(async file => {
const fileContents = await fs.getFileContents(file)
if (!fileContents) return null
const passed = fileContents.search(regex) >= 0
const message = `${
passed ? 'Contains' : "Doesn't contain"
} ${getContent(options)}`
return {
passed: not ? !passed : passed,
path: file,
message
}
})
)
} else {
/**
* Add regular expression matched content context into result.
* Added contexts includes:
* - line # of the regular expression.
* - 'options.context-char-length' number of characters before and after the regex match.
* The added context will be in result.message.
*
* Note: if 'g' is not presented in 'options.flags',
* the regular expression will only display the first match context.
* @ignore
*/
results = (
await Promise.all(
files.map(async file => {
const fileContents = await fs.getFileContents(file)
if (!fileContents) return null
const optionContextCharLength = options['context-char-length'] || 50
const split = fileContents.split(regex)
const regexHasMatch = split.length > 1
if (!regexHasMatch) {
return {
passed: not ? !regexHasMatch : regexHasMatch,
path: file,
contextLines: [],
message: `Doesn't contain '${getContent(options)}'`
}
}
const fileLines = fileContents.split('\n')
const contextLines = split
/**
* @return sum of line numbers in each regexp split chunks.
* @ignore
*/
.map(fileChunk => {
/**
* Note: Handle *undefined* in regex split result issue
* by treating *undefined* as ''
* @ignore
*/
if (fileChunk !== undefined) return fileChunk.split('\n').length
return 1
})
/**
* Get lines of regexp match
* @return list of lines contains regexp matchs
* @ignore
*/
.reduce((previous, current, index, array) => {
/**
* Push number of lines before the first regex match to the result array.
* @ignore
*/
if (previous.length === 0) {
previous.push(current)
} else if (current === 1 || index === array.length - 1) {
/**
* We don't need to count multiple times if one line contains multiple regex match.
* We don't need to count rest of lines after last regex match.
* @ignore
*/
} else {
/**
* Add *relative number of lines* between this regex match and last regex match (current-1)
* to the last *absolute number of lines* of last regex match to the top of file (previous[lastElement])
* to get the *absolute number of lines* of current regex match.
* @ignore
*/
previous.push(current - 1 + previous[previous.length - 1])
}
return previous
}, [])
/**
* @return lines and contexts of every regex matches.
* @ignore
*/
.reduce((previous, current) => {
const matchedLine = fileLines[current - 1]
/**
* We can't do multi-line match on a single line context,
* so we try to detect a match on the line
* and print helpful info if there is none.
*
* Note: multi-line output context can be challenging to read.
* So instead of print unpredictable context in the output,
* we just print line number.
* @ignore
*/
if (regexFlags.includes('m')) {
let currentMatch = regex.exec(matchedLine)
/**
* Found no match, the regex match was multi-line.
* Print info in context instead of actual context.
* @ignore
*/
if (currentMatch === null) {
previous.push({
line: current,
context:
'-- This is a multi-line regex match so we only displaying line number --'
})
return previous
}
/**
* Find a match, so we try to find all matches.
* Reset regex.lastIndex to start from beginning.
* @ignore
*/
regex.lastIndex = 0
while ((currentMatch = regex.exec(matchedLine)) !== null) {
previous.push({
line: current,
context: getContext(
matchedLine,
currentMatch,
optionContextCharLength
)
})
if (regex.lastIndex === 0) break
}
return previous
}
/**
* No *global* flag means regex.lastIndex will not advance.
* We just need to run regex.exec once
* @ignore
*/
if (!regexFlags.includes('g')) {
const currentMatch = regex.exec(matchedLine)
/**
* Found a match! Put it in the result
* @ignore
*/
if (currentMatch != null) {
previous.push({
line: current,
context: getContext(
matchedLine,
currentMatch,
optionContextCharLength
)
})
return previous
}
/**
* User should never reach here, throw an error when that happens.
* @ignore
*/
console.trace('Error trace:')
throw new Error(
'Please open an issue on https://github.com/todogroup/repolinter'
)
}
/**
* Find all matches on the string with non-multi-line regex
* @ignore
*/
let currentMatch
while ((currentMatch = regex.exec(matchedLine)) !== null) {
previous.push({
line: current,
context: getContext(
matchedLine,
currentMatch,
optionContextCharLength
)
})
}
return previous
}, [])
return {
passed: not ? !regexHasMatch : regexHasMatch,
path: file,
contextLines,
message: `Contains '${getContent(options)}'`
}
})
)
)
.filter(result => result && (not ? !result.passed : result.passed))
.reduce((previous, current) => {
current.contextLines.forEach(lineContext => {
previous.push({
passed: current.passed,
path: current.path,
message: `${current.message} on line ${lineContext.line}, context: \n\t|${lineContext.context}`
})
})
return previous
}, [])
}
const filteredResults = results.filter(r => r !== null)
const passed = any
? filteredResults.some(r => r.passed)
: !filteredResults.find(r => !r.passed)
return new Result('', filteredResults, passed)
}
/**
* Check if a list of files in one or more branches contains a regular expression.
*
* @param {FileSystem} fs A filesystem object configured with filter paths and target directories
* @param {object} options The rule configuration
* @param {boolean} not Whether or not to invert the result (not contents instead of contents)
* @param {boolean} any Whether to check if the regular expression is contained by at least one of the files in the list
* @param {SimpleGit} git A simple-git object configured correct path
* @returns {Promise<Result>} The lint rule result
* @ignore
*/
async function fileContentsWithBranchOption(
fs,
options,
not = false,
any = false,
git
) {
// support legacy configuration keys
const fileList = (any ? options.globsAny : options.globsAll) || options.files
const regexFlags = options.flags || ''
const regex = new RegExp(options.content, regexFlags)
if (git === undefined) {
git = simpleGit({
progress({ method, stage, progress }) {
console.log(`git.${method} ${stage} stage ${progress}% complete`)
},
baseDir: fs.targetDir
})
}
const defaultBranch = (await git.branchLocal()).current
const branches = options.branches
if (!options.skipDefaultBranch) {
branches.unshift(defaultBranch)
}
const defaultRemote = (await git.getRemotes())[0]
await fetchAllBranchesRemote(git, defaultRemote.name)
let results = []
let noMatchingFileFoundCount = 0
let switchedBranch = false
for (let index = 0; index < branches.length; index++) {
const branch = branches[index]
if (
!(await doesBranchExist(git, branch)) &&
!(await doesBranchExist(git, `${defaultRemote.name}/${branch}`))
) {
noMatchingFileFoundCount++
continue
}
// if branch name is the default branch from clone, ignore and do not checkout.
if (branch !== defaultBranch) {
// perform git checkout of the target branch
await gitCheckout(git, branch, defaultRemote.name)
switchedBranch = true
}
const files = await fs.findAllFiles(fileList, !!options.nocase)
if (files.length === 0) {
noMatchingFileFoundCount++
continue
}
if (!options['display-result-context']) {
/**
* Default "Contains" / "Doesn't contain"
* @ignore
*/
results = results.concat(
await Promise.all(
files.map(async file => {
const fileContents = await fs.getFileContents(file)
if (!fileContents) return null
const passed = fileContents.search(regex) >= 0
const message = `${
passed ? 'Contains' : "Doesn't contain"
} ${getContent(options)}`
// TODO: Might need to increase noMatchingFileFoundCount here instead of returning if it did not find a file
return {
passed: not ? !passed : passed,
path: file,
message
}
})
)
)
} else {
/**
* Add regular expression matched content context into result.
* Added contexts includes:
* - line # of the regular expression.
* - 'options.context-char-length' number of characters before and after the regex match.
* The added context will be in result.message.
*
* Note: if 'g' is not presented in 'options.flags',
* the regular expression will only display the first match context.
* @ignore
*/
results = results
.concat(
await Promise.all(
files.map(async file => {
const fileContents = await fs.getFileContents(file)
if (!fileContents) return null
const optionContextCharLength =
options['context-char-length'] || 50
const split = fileContents.split(regex)
const regexHasMatch = split.length > 1
if (!regexHasMatch) {
return {
passed: not ? !regexHasMatch : regexHasMatch,
path: file,
contextLines: [],
message: `Doesn't contain '${getContent(options)}'`
}
}
const fileLines = fileContents.split('\n')
const contextLines = split
/**
* @return sum of line numbers in each regexp split chunks.
* @ignore
*/
.map(fileChunk => {
/**
* Note: Handle *undefined* in regex split result issue
* by treating *undefined* as ''
* @ignore
*/
if (fileChunk !== undefined)
return fileChunk.split('\n').length
return 1
})
/**
* Get lines of regexp match
* @return list of lines contains regexp matchs
* @ignore
*/
.reduce((previous, current, index, array) => {
/**
* Push number of lines before the first regex match to the result array.
* @ignore
*/
if (previous.length === 0) {
previous.push(current)
} else if (current === 1 || index === array.length - 1) {
/**
* We don't need to count multiple times if one line contains multiple regex match.
* We don't need to count rest of lines after last regex match.
* @ignore
*/
} else {
/**
* Add *relative number of lines* between this regex match and last regex match (current-1)
* to the last *absolute number of lines* of last regex match to the top of file (previous[lastElement])
* to get the *absolute number of lines* of current regex match.
* @ignore
*/
previous.push(current - 1 + previous[previous.length - 1])
}
return previous
}, [])
/**
* @return lines and contexts of every regex matches.
* @ignore
*/
.reduce((previous, current) => {
const matchedLine = fileLines[current - 1]
/**
* We can't do multi-line match on a single line context,
* so we try to detect a match on the line
* and print helpful info if there is none.
*
* Note: multi-line output context can be challenging to read.
* So instead of print unpredictable context in the output,
* we just print line number.
* @ignore
*/
if (regexFlags.includes('m')) {
let currentMatch = regex.exec(matchedLine)
/**
* Found no match, the regex match was multi-line.
* Print info in context instead of actual context.
* @ignore
*/
if (currentMatch === null) {
previous.push({
line: current,
context:
'-- This is a multi-line regex match so we only displaying line number --'
})
return previous
}
/**
* Find a match, so we try to find all matches.
* Reset regex.lastIndex to start from beginning.
* @ignore
*/
regex.lastIndex = 0
while ((currentMatch = regex.exec(matchedLine)) !== null) {
previous.push({
line: current,
context: getContext(
matchedLine,
currentMatch,
optionContextCharLength
)
})
if (regex.lastIndex === 0) break
}
return previous
}
/**
* No *global* flag means regex.lastIndex will not advance.
* We just need to run regex.exec once
* @ignore
*/
if (!regexFlags.includes('g')) {
const currentMatch = regex.exec(matchedLine)
/**
* Found a match! Put it in the result
* @ignore
*/
if (currentMatch != null) {
previous.push({
line: current,
context: getContext(
matchedLine,
currentMatch,
optionContextCharLength
)
})
return previous
}
/**
* User should never reach here, throw an error when that happens.
* @ignore
*/
console.trace('Error trace:')
throw new Error(
'Please open an issue on https://github.com/todogroup/repolinter'
)
}
/**
* Find all matches on the string with non-multi-line regex
* @ignore
*/
let currentMatch
while ((currentMatch = regex.exec(matchedLine)) !== null) {
previous.push({
line: current,
context: getContext(
matchedLine,
currentMatch,
optionContextCharLength
)
})
}
return previous
}, [])
return {
passed: not ? !regexHasMatch : regexHasMatch,
path: file,
contextLines,
message: `Contains '${getContent(options)}'`
}
})
)
)
.filter(result => result && (not ? !result.passed : result.passed))
.reduce((previous, current) => {
current.contextLines.forEach(lineContext => {
previous.push({
passed: current.passed,
path: current.path,
message: `${current.message} on line ${lineContext.line}, context: \n\t|${lineContext.context}`
})
})
return previous
}, [])
}
}
if (switchedBranch) {
// Make sure we are back using the default branch
await gitCheckout(git, defaultBranch, defaultRemote.name)
}
if (noMatchingFileFoundCount === branches.length) {
return new Result(
'Did not find file matching the specified patterns',
fileList.map(f => {
return { passed: false, pattern: f }
}),
!options['fail-on-non-existent']
)
}
const filteredResults = results.filter(r => r !== null)
const passed = any
? filteredResults.some(r => r.passed)
: !filteredResults.find(r => !r.passed)
return new Result('', filteredResults, passed)
}
module.exports = fileContents
// isBranchesOptionEnabled returns true if the branches option is enabled.
function isBranchOptionEnabled(options) {
if (
options.branches !== undefined &&
options.branches !== null &&
options.branches !== [] &&
options.branches.length > 0
) {
return true
}
return false
}
// Fetch all remote branches, fetches just the names on remote.
// Needs to be done since we did a shallow checkout
async function fetchAllBranchesRemote(git, defaultRemote) {
// Since we do a shallow clone, we need to first retrieve the branches
await git.addConfig(
`remote.${defaultRemote}.fetch`,
`+refs/heads/*:refs/remotes/${defaultRemote}/*`
)
await git.remote(['update'])
}
// Check if branch exists
async function doesBranchExist(git, branch) {
const branches = (await git.branch(['-r'])).all
if (branches.find(v => v === branch)) {
return true
}
return false
}
// Helper method to quickly checkout to a different branch
async function gitCheckout(git, branch, defaultRemote) {
const checkoutResult = await git.checkout(branch)
if (checkoutResult) {
const checkoutResultWithDefaultOrigin = await git.checkout(
`${defaultRemote}/${branch}`
)
if (checkoutResultWithDefaultOrigin) {
console.error(checkoutResult)
process.exitCode = 1
throw new Error(`Failed checking out branch: ${defaultRemote}/${branch}`)
}
}
}