-
Notifications
You must be signed in to change notification settings - Fork 30.5k
/
Copy pathfileSearch.ts
760 lines (646 loc) · 24.9 KB
/
fileSearch.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
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as childProcess from 'child_process';
import * as fs from 'fs';
import * as path from '../../../../base/common/path.js';
import { Readable } from 'stream';
import { StringDecoder } from 'string_decoder';
import * as arrays from '../../../../base/common/arrays.js';
import { toErrorMessage } from '../../../../base/common/errorMessage.js';
import * as glob from '../../../../base/common/glob.js';
import * as normalization from '../../../../base/common/normalization.js';
import { isEqualOrParent } from '../../../../base/common/extpath.js';
import * as platform from '../../../../base/common/platform.js';
import { StopWatch } from '../../../../base/common/stopwatch.js';
import * as strings from '../../../../base/common/strings.js';
import * as types from '../../../../base/common/types.js';
import { URI } from '../../../../base/common/uri.js';
import { Promises } from '../../../../base/node/pfs.js';
import { IFileQuery, IFolderQuery, IProgressMessage, ISearchEngineStats, IRawFileMatch, ISearchEngine, ISearchEngineSuccess, isFilePatternMatch, hasSiblingFn } from '../common/search.js';
import { spawnRipgrepCmd } from './ripgrepFileSearch.js';
import { prepareQuery } from '../../../../base/common/fuzzyScorer.js';
interface IDirectoryEntry extends IRawFileMatch {
base: string;
basename: string;
}
interface IDirectoryTree {
rootEntries: IDirectoryEntry[];
pathToEntries: { [relativePath: string]: IDirectoryEntry[] };
}
const killCmds = new Set<() => void>();
process.on('exit', () => {
killCmds.forEach(cmd => cmd());
});
export class FileWalker {
private config: IFileQuery;
private filePattern: string;
private normalizedFilePatternLowercase: string | null = null;
private includePattern: glob.ParsedExpression | undefined;
private maxResults: number | null;
private exists: boolean;
private maxFilesize: number | null = null;
private isLimitHit: boolean;
private resultCount: number;
private isCanceled = false;
private fileWalkSW: StopWatch | null = null;
private directoriesWalked: number;
private filesWalked: number;
private errors: string[];
private cmdSW: StopWatch | null = null;
private cmdResultCount: number = 0;
private folderExcludePatterns: Map<string, AbsoluteAndRelativeParsedExpression>;
private globalExcludePattern: glob.ParsedExpression | undefined;
private walkedPaths: { [path: string]: boolean };
constructor(config: IFileQuery) {
this.config = config;
this.filePattern = config.filePattern || '';
this.includePattern = config.includePattern && glob.parse(config.includePattern);
this.maxResults = config.maxResults || null;
this.exists = !!config.exists;
this.walkedPaths = Object.create(null);
this.resultCount = 0;
this.isLimitHit = false;
this.directoriesWalked = 0;
this.filesWalked = 0;
this.errors = [];
if (this.filePattern) {
this.normalizedFilePatternLowercase = config.shouldGlobMatchFilePattern ? null : prepareQuery(this.filePattern).normalizedLowercase;
}
this.globalExcludePattern = config.excludePattern && glob.parse(config.excludePattern);
this.folderExcludePatterns = new Map<string, AbsoluteAndRelativeParsedExpression>();
config.folderQueries.forEach(folderQuery => {
const folderExcludeExpression: glob.IExpression = {}; // todo: consider exclude baseURI
folderQuery.excludePattern?.forEach(excludePattern => {
Object.assign(folderExcludeExpression, excludePattern.pattern || {}, this.config.excludePattern || {});
});
if (!folderQuery.excludePattern?.length) {
Object.assign(folderExcludeExpression, this.config.excludePattern || {});
}
// Add excludes for other root folders
const fqPath = folderQuery.folder.fsPath;
config.folderQueries
.map(rootFolderQuery => rootFolderQuery.folder.fsPath)
.filter(rootFolder => rootFolder !== fqPath)
.forEach(otherRootFolder => {
// Exclude nested root folders
if (isEqualOrParent(otherRootFolder, fqPath)) {
folderExcludeExpression[path.relative(fqPath, otherRootFolder)] = true;
}
});
this.folderExcludePatterns.set(fqPath, new AbsoluteAndRelativeParsedExpression(folderExcludeExpression, fqPath));
});
}
cancel(): void {
this.isCanceled = true;
killCmds.forEach(cmd => cmd());
}
walk(folderQueries: IFolderQuery[], extraFiles: URI[], numThreads: number | undefined, onResult: (result: IRawFileMatch) => void, onMessage: (message: IProgressMessage) => void, done: (error: Error | null, isLimitHit: boolean) => void): void {
this.fileWalkSW = StopWatch.create(false);
// Support that the file pattern is a full path to a file that exists
if (this.isCanceled) {
return done(null, this.isLimitHit);
}
// For each extra file
extraFiles.forEach(extraFilePath => {
const basename = path.basename(extraFilePath.fsPath);
if (this.globalExcludePattern && this.globalExcludePattern(extraFilePath.fsPath, basename)) {
return; // excluded
}
// File: Check for match on file pattern and include pattern
this.matchFile(onResult, { relativePath: extraFilePath.fsPath /* no workspace relative path */, searchPath: undefined });
});
this.cmdSW = StopWatch.create(false);
// For each root folder
this.parallel<IFolderQuery, void>(folderQueries, (folderQuery: IFolderQuery, rootFolderDone: (err: Error | null, result: void) => void) => {
this.call(this.cmdTraversal, this, folderQuery, numThreads, onResult, onMessage, (err?: Error) => {
if (err) {
const errorMessage = toErrorMessage(err);
console.error(errorMessage);
this.errors.push(errorMessage);
rootFolderDone(err, undefined);
} else {
rootFolderDone(null, undefined);
}
});
}, (errors, _result) => {
this.fileWalkSW!.stop();
const err = errors ? arrays.coalesce(errors)[0] : null;
done(err, this.isLimitHit);
});
}
private parallel<T, E>(list: T[], fn: (item: T, callback: (err: Error | null, result: E | null) => void) => void, callback: (err: Array<Error | null> | null, result: E[]) => void): void {
const results = new Array(list.length);
const errors = new Array<Error | null>(list.length);
let didErrorOccur = false;
let doneCount = 0;
if (list.length === 0) {
return callback(null, []);
}
list.forEach((item, index) => {
fn(item, (error, result) => {
if (error) {
didErrorOccur = true;
results[index] = null;
errors[index] = error;
} else {
results[index] = result;
errors[index] = null;
}
if (++doneCount === list.length) {
return callback(didErrorOccur ? errors : null, results);
}
});
});
}
private call<F extends Function>(fun: F, that: any, ...args: any[]): void {
try {
fun.apply(that, args);
} catch (e) {
args[args.length - 1](e);
}
}
private cmdTraversal(folderQuery: IFolderQuery, numThreads: number | undefined, onResult: (result: IRawFileMatch) => void, onMessage: (message: IProgressMessage) => void, cb: (err?: Error) => void): void {
const rootFolder = folderQuery.folder.fsPath;
const isMac = platform.isMacintosh;
const killCmd = () => cmd && cmd.kill();
killCmds.add(killCmd);
let done = (err?: Error) => {
killCmds.delete(killCmd);
done = () => { };
cb(err);
};
let leftover = '';
const tree = this.initDirectoryTree();
const ripgrep = spawnRipgrepCmd(this.config, folderQuery, this.config.includePattern, this.folderExcludePatterns.get(folderQuery.folder.fsPath)!.expression, numThreads);
const cmd = ripgrep.cmd;
const noSiblingsClauses = !Object.keys(ripgrep.siblingClauses).length;
const escapedArgs = ripgrep.rgArgs.args
.map(arg => arg.match(/^-/) ? arg : `'${arg}'`)
.join(' ');
let rgCmd = `${ripgrep.rgDiskPath} ${escapedArgs}\n - cwd: ${ripgrep.cwd}`;
if (ripgrep.rgArgs.siblingClauses) {
rgCmd += `\n - Sibling clauses: ${JSON.stringify(ripgrep.rgArgs.siblingClauses)}`;
}
onMessage({ message: rgCmd });
this.cmdResultCount = 0;
this.collectStdout(cmd, 'utf8', onMessage, (err: Error | null, stdout?: string, last?: boolean) => {
if (err) {
done(err);
return;
}
if (this.isLimitHit) {
done();
return;
}
// Mac: uses NFD unicode form on disk, but we want NFC
const normalized = leftover + (isMac ? normalization.normalizeNFC(stdout || '') : stdout);
const relativeFiles = normalized.split('\n');
if (last) {
const n = relativeFiles.length;
relativeFiles[n - 1] = relativeFiles[n - 1].trim();
if (!relativeFiles[n - 1]) {
relativeFiles.pop();
}
} else {
leftover = relativeFiles.pop() || '';
}
if (relativeFiles.length && relativeFiles[0].indexOf('\n') !== -1) {
done(new Error('Splitting up files failed'));
return;
}
this.cmdResultCount += relativeFiles.length;
if (noSiblingsClauses) {
for (const relativePath of relativeFiles) {
this.matchFile(onResult, { base: rootFolder, relativePath, searchPath: this.getSearchPath(folderQuery, relativePath) });
if (this.isLimitHit) {
killCmd();
break;
}
}
if (last || this.isLimitHit) {
done();
}
return;
}
// TODO: Optimize siblings clauses with ripgrep here.
this.addDirectoryEntries(folderQuery, tree, rootFolder, relativeFiles, onResult);
if (last) {
this.matchDirectoryTree(tree, rootFolder, onResult);
done();
}
});
}
/**
* Public for testing.
*/
spawnFindCmd(folderQuery: IFolderQuery) {
const excludePattern = this.folderExcludePatterns.get(folderQuery.folder.fsPath)!;
const basenames = excludePattern.getBasenameTerms();
const pathTerms = excludePattern.getPathTerms();
const args = ['-L', '.'];
if (basenames.length || pathTerms.length) {
args.push('-not', '(', '(');
for (const basename of basenames) {
args.push('-name', basename);
args.push('-o');
}
for (const path of pathTerms) {
args.push('-path', path);
args.push('-o');
}
args.pop();
args.push(')', '-prune', ')');
}
args.push('-type', 'f');
return childProcess.spawn('find', args, { cwd: folderQuery.folder.fsPath });
}
/**
* Public for testing.
*/
readStdout(cmd: childProcess.ChildProcess, encoding: BufferEncoding, cb: (err: Error | null, stdout?: string) => void): void {
let all = '';
this.collectStdout(cmd, encoding, () => { }, (err: Error | null, stdout?: string, last?: boolean) => {
if (err) {
cb(err);
return;
}
all += stdout;
if (last) {
cb(null, all);
}
});
}
private collectStdout(cmd: childProcess.ChildProcess, encoding: BufferEncoding, onMessage: (message: IProgressMessage) => void, cb: (err: Error | null, stdout?: string, last?: boolean) => void): void {
let onData = (err: Error | null, stdout?: string, last?: boolean) => {
if (err || last) {
onData = () => { };
this.cmdSW?.stop();
}
cb(err, stdout, last);
};
let gotData = false;
if (cmd.stdout) {
// Should be non-null, but #38195
this.forwardData(cmd.stdout, encoding, onData);
cmd.stdout.once('data', () => gotData = true);
} else {
onMessage({ message: 'stdout is null' });
}
let stderr: Buffer[];
if (cmd.stderr) {
// Should be non-null, but #38195
stderr = this.collectData(cmd.stderr);
} else {
onMessage({ message: 'stderr is null' });
}
cmd.on('error', (err: Error) => {
onData(err);
});
cmd.on('close', (code: number) => {
// ripgrep returns code=1 when no results are found
let stderrText: string;
if (!gotData && (stderrText = this.decodeData(stderr, encoding)) && rgErrorMsgForDisplay(stderrText)) {
onData(new Error(`command failed with error code ${code}: ${this.decodeData(stderr, encoding)}`));
} else {
if (this.exists && code === 0) {
this.isLimitHit = true;
}
onData(null, '', true);
}
});
}
private forwardData(stream: Readable, encoding: BufferEncoding, cb: (err: Error | null, stdout?: string) => void): StringDecoder {
const decoder = new StringDecoder(encoding);
stream.on('data', (data: Buffer) => {
cb(null, decoder.write(data));
});
return decoder;
}
private collectData(stream: Readable): Buffer[] {
const buffers: Buffer[] = [];
stream.on('data', (data: Buffer) => {
buffers.push(data);
});
return buffers;
}
private decodeData(buffers: Buffer[], encoding: BufferEncoding): string {
const decoder = new StringDecoder(encoding);
return buffers.map(buffer => decoder.write(buffer)).join('');
}
private initDirectoryTree(): IDirectoryTree {
const tree: IDirectoryTree = {
rootEntries: [],
pathToEntries: Object.create(null)
};
tree.pathToEntries['.'] = tree.rootEntries;
return tree;
}
private addDirectoryEntries(folderQuery: IFolderQuery, { pathToEntries }: IDirectoryTree, base: string, relativeFiles: string[], onResult: (result: IRawFileMatch) => void) {
// Support relative paths to files from a root resource (ignores excludes)
if (relativeFiles.indexOf(this.filePattern) !== -1) {
this.matchFile(onResult, {
base,
relativePath: this.filePattern,
searchPath: this.getSearchPath(folderQuery, this.filePattern)
});
}
const add = (relativePath: string) => {
const basename = path.basename(relativePath);
const dirname = path.dirname(relativePath);
let entries = pathToEntries[dirname];
if (!entries) {
entries = pathToEntries[dirname] = [];
add(dirname);
}
entries.push({
base,
relativePath,
basename,
searchPath: this.getSearchPath(folderQuery, relativePath),
});
};
relativeFiles.forEach(add);
}
private matchDirectoryTree({ rootEntries, pathToEntries }: IDirectoryTree, rootFolder: string, onResult: (result: IRawFileMatch) => void) {
const self = this;
const excludePattern = this.folderExcludePatterns.get(rootFolder)!;
const filePattern = this.filePattern;
function matchDirectory(entries: IDirectoryEntry[]) {
self.directoriesWalked++;
const hasSibling = hasSiblingFn(() => entries.map(entry => entry.basename));
for (let i = 0, n = entries.length; i < n; i++) {
const entry = entries[i];
const { relativePath, basename } = entry;
// Check exclude pattern
// If the user searches for the exact file name, we adjust the glob matching
// to ignore filtering by siblings because the user seems to know what they
// are searching for and we want to include the result in that case anyway
if (excludePattern.test(relativePath, basename, filePattern !== basename ? hasSibling : undefined)) {
continue;
}
const sub = pathToEntries[relativePath];
if (sub) {
matchDirectory(sub);
} else {
self.filesWalked++;
if (relativePath === filePattern) {
continue; // ignore file if its path matches with the file pattern because that is already matched above
}
self.matchFile(onResult, entry);
}
if (self.isLimitHit) {
break;
}
}
}
matchDirectory(rootEntries);
}
getStats(): ISearchEngineStats {
return {
cmdTime: this.cmdSW!.elapsed(),
fileWalkTime: this.fileWalkSW!.elapsed(),
directoriesWalked: this.directoriesWalked,
filesWalked: this.filesWalked,
cmdResultCount: this.cmdResultCount
};
}
private doWalk(folderQuery: IFolderQuery, relativeParentPath: string, files: string[], onResult: (result: IRawFileMatch) => void, done: (error?: Error) => void): void {
const rootFolder = folderQuery.folder;
// Execute tasks on each file in parallel to optimize throughput
const hasSibling = hasSiblingFn(() => files);
this.parallel(files, (file: string, clb: (error: Error | null, _?: any) => void): void => {
// Check canceled
if (this.isCanceled || this.isLimitHit) {
return clb(null);
}
// Check exclude pattern
// If the user searches for the exact file name, we adjust the glob matching
// to ignore filtering by siblings because the user seems to know what they
// are searching for and we want to include the result in that case anyway
const currentRelativePath = relativeParentPath ? [relativeParentPath, file].join(path.sep) : file;
if (this.folderExcludePatterns.get(folderQuery.folder.fsPath)!.test(currentRelativePath, file, this.config.filePattern !== file ? hasSibling : undefined)) {
return clb(null);
}
// Use lstat to detect links
const currentAbsolutePath = [rootFolder.fsPath, currentRelativePath].join(path.sep);
fs.lstat(currentAbsolutePath, (error, lstat) => {
if (error || this.isCanceled || this.isLimitHit) {
return clb(null);
}
// If the path is a link, we must instead use fs.stat() to find out if the
// link is a directory or not because lstat will always return the stat of
// the link which is always a file.
this.statLinkIfNeeded(currentAbsolutePath, lstat, (error, stat) => {
if (error || this.isCanceled || this.isLimitHit) {
return clb(null);
}
// Directory: Follow directories
if (stat.isDirectory()) {
this.directoriesWalked++;
// to really prevent loops with links we need to resolve the real path of them
return this.realPathIfNeeded(currentAbsolutePath, lstat, (error, realpath) => {
if (error || this.isCanceled || this.isLimitHit) {
return clb(null);
}
realpath = realpath || '';
if (this.walkedPaths[realpath]) {
return clb(null); // escape when there are cycles (can happen with symlinks)
}
this.walkedPaths[realpath] = true; // remember as walked
// Continue walking
return Promises.readdir(currentAbsolutePath).then(children => {
if (this.isCanceled || this.isLimitHit) {
return clb(null);
}
this.doWalk(folderQuery, currentRelativePath, children, onResult, err => clb(err || null));
}, error => {
clb(null);
});
});
}
// File: Check for match on file pattern and include pattern
else {
this.filesWalked++;
if (currentRelativePath === this.filePattern) {
return clb(null, undefined); // ignore file if its path matches with the file pattern because checkFilePatternRelativeMatch() takes care of those
}
if (this.maxFilesize && types.isNumber(stat.size) && stat.size > this.maxFilesize) {
return clb(null, undefined); // ignore file if max file size is hit
}
this.matchFile(onResult, {
base: rootFolder.fsPath,
relativePath: currentRelativePath,
searchPath: this.getSearchPath(folderQuery, currentRelativePath),
});
}
// Unwind
return clb(null, undefined);
});
});
}, (error: Array<Error | null> | null): void => {
const filteredErrors = error ? arrays.coalesce(error) : error; // find any error by removing null values first
return done(filteredErrors && filteredErrors.length > 0 ? filteredErrors[0] : undefined);
});
}
private matchFile(onResult: (result: IRawFileMatch) => void, candidate: IRawFileMatch): void {
if (this.isFileMatch(candidate) && (!this.includePattern || this.includePattern(candidate.relativePath, path.basename(candidate.relativePath)))) {
this.resultCount++;
if (this.exists || (this.maxResults && this.resultCount > this.maxResults)) {
this.isLimitHit = true;
}
if (!this.isLimitHit) {
onResult(candidate);
}
}
}
private isFileMatch(candidate: IRawFileMatch): boolean {
// Check for search pattern
if (this.filePattern) {
if (this.filePattern === '*') {
return true; // support the all-matching wildcard
}
if (this.normalizedFilePatternLowercase) {
return isFilePatternMatch(candidate, this.normalizedFilePatternLowercase);
} else if (this.filePattern) {
return isFilePatternMatch(candidate, this.filePattern, false);
}
}
// No patterns means we match all
return true;
}
private statLinkIfNeeded(path: string, lstat: fs.Stats, clb: (error: Error | null, stat: fs.Stats) => void): void {
if (lstat.isSymbolicLink()) {
return fs.stat(path, clb); // stat the target the link points to
}
return clb(null, lstat); // not a link, so the stat is already ok for us
}
private realPathIfNeeded(path: string, lstat: fs.Stats, clb: (error: Error | null, realpath?: string) => void): void {
if (lstat.isSymbolicLink()) {
return fs.realpath(path, (error, realpath) => {
if (error) {
return clb(error);
}
return clb(null, realpath);
});
}
return clb(null, path);
}
/**
* If we're searching for files in multiple workspace folders, then better prepend the
* name of the workspace folder to the path of the file. This way we'll be able to
* better filter files that are all on the top of a workspace folder and have all the
* same name. A typical example are `package.json` or `README.md` files.
*/
private getSearchPath(folderQuery: IFolderQuery, relativePath: string): string {
if (folderQuery.folderName) {
return path.join(folderQuery.folderName, relativePath);
}
return relativePath;
}
}
export class Engine implements ISearchEngine<IRawFileMatch> {
private folderQueries: IFolderQuery[];
private extraFiles: URI[];
private walker: FileWalker;
private numThreads?: number;
constructor(config: IFileQuery, numThreads?: number) {
this.folderQueries = config.folderQueries;
this.extraFiles = config.extraFileResources || [];
this.numThreads = numThreads;
this.walker = new FileWalker(config);
}
search(onResult: (result: IRawFileMatch) => void, onProgress: (progress: IProgressMessage) => void, done: (error: Error | null, complete: ISearchEngineSuccess) => void): void {
this.walker.walk(this.folderQueries, this.extraFiles, this.numThreads, onResult, onProgress, (err: Error | null, isLimitHit: boolean) => {
done(err, {
limitHit: isLimitHit,
stats: this.walker.getStats(),
messages: [],
});
});
}
cancel(): void {
this.walker.cancel();
}
}
/**
* This class exists to provide one interface on top of two ParsedExpressions, one for absolute expressions and one for relative expressions.
* The absolute and relative expressions don't "have" to be kept separate, but this keeps us from having to path.join every single
* file searched, it's only used for a text search with a searchPath
*/
class AbsoluteAndRelativeParsedExpression {
private absoluteParsedExpr: glob.ParsedExpression | undefined;
private relativeParsedExpr: glob.ParsedExpression | undefined;
constructor(public expression: glob.IExpression, private root: string) {
this.init(expression);
}
/**
* Split the IExpression into its absolute and relative components, and glob.parse them separately.
*/
private init(expr: glob.IExpression): void {
let absoluteGlobExpr: glob.IExpression | undefined;
let relativeGlobExpr: glob.IExpression | undefined;
Object.keys(expr)
.filter(key => expr[key])
.forEach(key => {
if (path.isAbsolute(key)) {
absoluteGlobExpr = absoluteGlobExpr || glob.getEmptyExpression();
absoluteGlobExpr[key] = expr[key];
} else {
relativeGlobExpr = relativeGlobExpr || glob.getEmptyExpression();
relativeGlobExpr[key] = expr[key];
}
});
this.absoluteParsedExpr = absoluteGlobExpr && glob.parse(absoluteGlobExpr, { trimForExclusions: true });
this.relativeParsedExpr = relativeGlobExpr && glob.parse(relativeGlobExpr, { trimForExclusions: true });
}
test(_path: string, basename?: string, hasSibling?: (name: string) => boolean | Promise<boolean>): string | Promise<string | null> | undefined | null {
return (this.relativeParsedExpr && this.relativeParsedExpr(_path, basename, hasSibling)) ||
(this.absoluteParsedExpr && this.absoluteParsedExpr(path.join(this.root, _path), basename, hasSibling));
}
getBasenameTerms(): string[] {
const basenameTerms: string[] = [];
if (this.absoluteParsedExpr) {
basenameTerms.push(...glob.getBasenameTerms(this.absoluteParsedExpr));
}
if (this.relativeParsedExpr) {
basenameTerms.push(...glob.getBasenameTerms(this.relativeParsedExpr));
}
return basenameTerms;
}
getPathTerms(): string[] {
const pathTerms: string[] = [];
if (this.absoluteParsedExpr) {
pathTerms.push(...glob.getPathTerms(this.absoluteParsedExpr));
}
if (this.relativeParsedExpr) {
pathTerms.push(...glob.getPathTerms(this.relativeParsedExpr));
}
return pathTerms;
}
}
function rgErrorMsgForDisplay(msg: string): string | undefined {
const lines = msg.trim().split('\n');
const firstLine = lines[0].trim();
if (firstLine.startsWith('Error parsing regex')) {
return firstLine;
}
if (firstLine.startsWith('regex parse error')) {
return strings.uppercaseFirstLetter(lines[lines.length - 1].trim());
}
if (firstLine.startsWith('error parsing glob') ||
firstLine.startsWith('unsupported encoding')) {
// Uppercase first letter
return firstLine.charAt(0).toUpperCase() + firstLine.substr(1);
}
if (firstLine === `Literal '\\n' not allowed.`) {
// I won't localize this because none of the Ripgrep error messages are localized
return `Literal '\\n' currently not supported`;
}
if (firstLine.startsWith('Literal ')) {
// Other unsupported chars
return firstLine;
}
return undefined;
}