ripgrepTextSearch.ts 16.6 KB
Newer Older
R
Rob Lourens 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

R
💄  
Rob Lourens 已提交
7
import { EventEmitter } from 'events';
8
import * as path from 'path';
9
import { StringDecoder, NodeStringDecoder } from 'string_decoder';
R
💄  
Rob Lourens 已提交
10

R
Rob Lourens 已提交
11 12 13
import * as cp from 'child_process';
import { rgPath } from 'vscode-ripgrep';

R
Rob Lourens 已提交
14
import objects = require('vs/base/common/objects');
15
import platform = require('vs/base/common/platform');
16
import * as strings from 'vs/base/common/strings';
17
import * as paths from 'vs/base/common/paths';
18
import * as extfs from 'vs/base/node/extfs';
19
import * as encoding from 'vs/base/node/encoding';
R
Rob Lourens 已提交
20
import * as glob from 'vs/base/common/glob';
21
import { ILineMatch, ISearchLog } from 'vs/platform/search/common/search';
22
import { TPromise } from 'vs/base/common/winjs.base';
R
Rob Lourens 已提交
23

R
Rob Lourens 已提交
24
import { ISerializedFileMatch, ISerializedSearchComplete, IRawSearch, IFolderSearch } from './search';
R
Rob Lourens 已提交
25

26
export class RipgrepEngine {
R
Rob Lourens 已提交
27 28
	private isDone = false;
	private rgProc: cp.ChildProcess;
29
	private killRgProcFn: Function;
30
	private postProcessExclusions: glob.ParsedExpression;
R
Rob Lourens 已提交
31

R
💄  
Rob Lourens 已提交
32
	private ripgrepParser: RipgrepParser;
R
Rob Lourens 已提交
33

34
	private resultsHandledP: TPromise<any> = TPromise.wrap(null);
35

R
Rob Lourens 已提交
36
	constructor(private config: IRawSearch) {
37
		this.killRgProcFn = () => this.rgProc && this.rgProc.kill();
R
Rob Lourens 已提交
38 39 40 41
	}

	cancel(): void {
		this.isDone = true;
R
💄  
Rob Lourens 已提交
42
		this.ripgrepParser.cancel();
R
Rob Lourens 已提交
43 44 45
		this.rgProc.kill();
	}

46
	// TODO@Rob - make promise-based once the old search is gone, and I don't need them to have matching interfaces anymore
47
	search(onResult: (match: ISerializedFileMatch) => void, onMessage: (message: ISearchLog) => void, done: (error: Error, complete: ISerializedSearchComplete) => void): void {
48
		if (!this.config.folderQueries.length && !this.config.extraFiles.length) {
49
			process.removeListener('exit', this.killRgProcFn);
50 51 52 53 54 55 56
			done(null, {
				limitHit: false,
				stats: null
			});
			return;
		}

57
		const rgArgs = getRgArgs(this.config);
58 59 60
		if (rgArgs.siblingClauses) {
			this.postProcessExclusions = glob.parseToAsync(rgArgs.siblingClauses, { trimForExclusions: true });
		}
R
💄  
Rob Lourens 已提交
61

62
		const cwd = platform.isWindows ? 'c:/' : '/';
R
Rob Lourens 已提交
63
		process.nextTick(() => { // Allow caller to register progress callback
64
			const escapedArgs = rgArgs.globArgs
65 66 67
				.map(arg => arg.match(/^-/) ? arg : `'${arg}'`)
				.join(' ');

68
			const rgCmd = `rg ${escapedArgs}\n - cwd: ${cwd}\n`;
69
			onMessage({ message: rgCmd });
70 71 72
			if (rgArgs.siblingClauses) {
				onMessage({ message: ` - Sibling clauses: ${JSON.stringify(rgArgs.siblingClauses)}\n` });
			}
73
		});
74
		this.rgProc = cp.spawn(rgPath, rgArgs.globArgs, { cwd });
75
		process.once('exit', this.killRgProcFn);
R
💄  
Rob Lourens 已提交
76

77
		this.ripgrepParser = new RipgrepParser(this.config.maxResults, cwd);
78 79
		this.ripgrepParser.on('result', (match: ISerializedFileMatch) => {
			if (this.postProcessExclusions) {
80
				const handleResultP = (<TPromise<string>>this.postProcessExclusions(match.path, undefined, () => getSiblings(match.path)))
81 82 83 84 85
					.then(globMatch => {
						if (!globMatch) {
							onResult(match);
						}
					});
86 87

				this.resultsHandledP = TPromise.join([this.resultsHandledP, handleResultP]);
88 89 90 91
			} else {
				onResult(match);
			}
		});
R
💄  
Rob Lourens 已提交
92 93
		this.ripgrepParser.on('hitLimit', () => {
			this.cancel();
94
			process.removeListener('exit', this.killRgProcFn);
R
💄  
Rob Lourens 已提交
95 96 97 98 99
			done(null, {
				limitHit: true,
				stats: null
			});
		});
R
Rob Lourens 已提交
100 101

		this.rgProc.stdout.on('data', data => {
R
💄  
Rob Lourens 已提交
102
			this.ripgrepParser.handleData(data);
R
Rob Lourens 已提交
103 104
		});

105 106 107 108
		let gotData = false;
		this.rgProc.stdout.once('data', () => gotData = true);

		let stderr = '';
R
Rob Lourens 已提交
109
		this.rgProc.stderr.on('data', data => {
110 111 112
			const message = data.toString();
			onMessage({ message });
			stderr += message;
R
Rob Lourens 已提交
113 114 115
		});

		this.rgProc.on('close', code => {
116 117
			// Trigger last result, then wait on async result handling
			this.ripgrepParser.flush();
118
			this.resultsHandledP.then(() => {
119 120 121
				this.rgProc = null;
				if (!this.isDone) {
					this.isDone = true;
122
					let displayMsg: string;
123
					process.removeListener('exit', this.killRgProcFn);
124 125
					if (stderr && !gotData && (displayMsg = this.rgErrorMsgForDisplay(stderr))) {
						done(new Error(displayMsg), {
126 127 128 129 130 131 132 133 134
							limitHit: false,
							stats: null
						});
					} else {
						done(null, {
							limitHit: false,
							stats: null
						});
					}
135 136
				}
			});
R
Rob Lourens 已提交
137 138
		});
	}
139

140 141 142 143 144 145
	/**
	 * Read the first line of stderr and return an error for display or undefined, based on a whitelist.
	 * Ripgrep produces stderr output which is not from a fatal error, and we only want the search to be
	 * "failed" when a fatal error was produced.
	 */
	private rgErrorMsgForDisplay(msg: string): string | undefined {
146 147
		const firstLine = msg.split('\n')[0];

148 149 150 151 152 153 154 155 156
		if (strings.startsWith(firstLine, 'Error parsing regex')) {
			return firstLine;
		}

		if (strings.startsWith(firstLine, 'error parsing glob')) {
			return firstLine;
		}

		return undefined;
157
	}
R
💄  
Rob Lourens 已提交
158 159 160
}

export class RipgrepParser extends EventEmitter {
R
Rob Lourens 已提交
161
	private static RESULT_REGEX = /^\u001b\[m(\d+)\u001b\[m:(.*)(\r?)/;
R
💄  
Rob Lourens 已提交
162 163
	private static FILE_REGEX = /^\u001b\[m(.+)\u001b\[m$/;

R
Rob Lourens 已提交
164 165
	public static MATCH_START_MARKER = '\u001b[m\u001b[31m';
	public static MATCH_END_MARKER = '\u001b[m';
R
💄  
Rob Lourens 已提交
166 167 168 169

	private fileMatch: FileMatch;
	private remainder: string;
	private isDone: boolean;
170
	private stringDecoder: NodeStringDecoder;
R
💄  
Rob Lourens 已提交
171 172 173

	private numResults = 0;

174
	constructor(private maxResults: number, private rootFolder: string) {
R
💄  
Rob Lourens 已提交
175
		super();
176
		this.stringDecoder = new StringDecoder();
R
💄  
Rob Lourens 已提交
177
	}
R
Rob Lourens 已提交
178

R
💄  
Rob Lourens 已提交
179 180 181
	public cancel(): void {
		this.isDone = true;
	}
R
Rob Lourens 已提交
182

R
Rob Lourens 已提交
183
	public flush(): void {
184 185
		this.handleDecodedData(this.stringDecoder.end());

R
Rob Lourens 已提交
186 187 188 189 190
		if (this.fileMatch) {
			this.onResult();
		}
	}

191 192 193 194 195 196
	public handleData(data: Buffer | string): void {
		const dataStr = typeof data === 'string' ? data : this.stringDecoder.write(data);
		this.handleDecodedData(dataStr);
	}

	private handleDecodedData(decodedData: string): void {
R
Rob Lourens 已提交
197
		// If the previous data chunk didn't end in a newline, prepend it to this chunk
R
💄  
Rob Lourens 已提交
198
		const dataStr = this.remainder ?
199 200
			this.remainder + decodedData :
			decodedData;
R
Rob Lourens 已提交
201

R
💄  
Rob Lourens 已提交
202 203
		const dataLines: string[] = dataStr.split(/\r\n|\n/);
		this.remainder = dataLines[dataLines.length - 1] ? dataLines.pop() : null;
R
Rob Lourens 已提交
204

R
💄  
Rob Lourens 已提交
205 206 207 208
		for (let l = 0; l < dataLines.length; l++) {
			const outputLine = dataLines[l].trim();
			if (this.isDone) {
				break;
R
Rob Lourens 已提交
209 210
			}

R
💄  
Rob Lourens 已提交
211
			let r: RegExpMatchArray;
R
Rob Lourens 已提交
212
			if (r = outputLine.match(RipgrepParser.RESULT_REGEX)) {
R
Rob Lourens 已提交
213 214 215 216 217 218 219 220 221
				const lineNum = parseInt(r[1]) - 1;
				let matchText = r[2];

				// workaround https://github.com/BurntSushi/ripgrep/issues/416
				// If the match line ended with \r, append a match end marker so the match isn't lost
				if (r[3]) {
					matchText += RipgrepParser.MATCH_END_MARKER;
				}

R
💄  
Rob Lourens 已提交
222
				// Line is a result - add to collected results for the current file path
R
Rob Lourens 已提交
223
				this.handleMatchLine(outputLine, lineNum, matchText);
R
💄  
Rob Lourens 已提交
224 225 226 227 228 229
			} else if (r = outputLine.match(RipgrepParser.FILE_REGEX)) {
				// Line is a file path - send all collected results for the previous file path
				if (this.fileMatch) {
					this.onResult();
				}

R
Rob Lourens 已提交
230
				this.fileMatch = new FileMatch(path.isAbsolute(r[1]) ? r[1] : path.join(this.rootFolder, r[1]));
R
💄  
Rob Lourens 已提交
231
			} else {
R
Rob Lourens 已提交
232
				// Line is empty (or malformed)
R
💄  
Rob Lourens 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246
			}
		}
	}

	private handleMatchLine(outputLine: string, lineNum: number, text: string): void {
		const lineMatch = new LineMatch(text, lineNum);
		this.fileMatch.addMatch(lineMatch);

		let lastMatchEndPos = 0;
		let matchTextStartPos = -1;

		// Track positions with color codes subtracted - offsets in the final text preview result
		let matchTextStartRealIdx = -1;
		let textRealIdx = 0;
247
		let hitLimit = false;
R
💄  
Rob Lourens 已提交
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

		const realTextParts: string[] = [];

		for (let i = 0; i < text.length - (RipgrepParser.MATCH_END_MARKER.length - 1);) {
			if (text.substr(i, RipgrepParser.MATCH_START_MARKER.length) === RipgrepParser.MATCH_START_MARKER) {
				// Match start
				const chunk = text.slice(lastMatchEndPos, i);
				realTextParts.push(chunk);
				i += RipgrepParser.MATCH_START_MARKER.length;
				matchTextStartPos = i;
				matchTextStartRealIdx = textRealIdx;
			} else if (text.substr(i, RipgrepParser.MATCH_END_MARKER.length) === RipgrepParser.MATCH_END_MARKER) {
				// Match end
				const chunk = text.slice(matchTextStartPos, i);
				realTextParts.push(chunk);
263 264 265 266
				if (!hitLimit) {
					lineMatch.addMatch(matchTextStartRealIdx, textRealIdx - matchTextStartRealIdx);
				}

R
💄  
Rob Lourens 已提交
267 268 269 270 271 272
				matchTextStartPos = -1;
				matchTextStartRealIdx = -1;
				i += RipgrepParser.MATCH_END_MARKER.length;
				lastMatchEndPos = i;
				this.numResults++;

273 274
				// Check hit maxResults limit
				if (this.numResults >= this.maxResults) {
275 276
					// Finish the line, then report the result below
					hitLimit = true;
277
				}
R
Rob Lourens 已提交
278
			} else {
R
💄  
Rob Lourens 已提交
279 280
				i++;
				textRealIdx++;
R
Rob Lourens 已提交
281 282 283
			}
		}

R
💄  
Rob Lourens 已提交
284 285 286
		const chunk = text.slice(lastMatchEndPos);
		realTextParts.push(chunk);

287
		// Replace preview with version without color codes
R
💄  
Rob Lourens 已提交
288 289
		const preview = realTextParts.join('');
		lineMatch.preview = preview;
290 291 292 293 294 295

		if (hitLimit) {
			this.cancel();
			this.onResult();
			this.emit('hitLimit');
		}
R
💄  
Rob Lourens 已提交
296
	}
R
Rob Lourens 已提交
297

R
💄  
Rob Lourens 已提交
298 299 300 301
	private onResult(): void {
		this.emit('result', this.fileMatch.serialize());
		this.fileMatch = null;
	}
R
Rob Lourens 已提交
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
}

export class FileMatch implements ISerializedFileMatch {
	path: string;
	lineMatches: LineMatch[];

	constructor(path: string) {
		this.path = path;
		this.lineMatches = [];
	}

	addMatch(lineMatch: LineMatch): void {
		this.lineMatches.push(lineMatch);
	}

	isEmpty(): boolean {
		return this.lineMatches.length === 0;
	}

	serialize(): ISerializedFileMatch {
		let lineMatches: ILineMatch[] = [];
		let numMatches = 0;

		for (let i = 0; i < this.lineMatches.length; i++) {
			numMatches += this.lineMatches[i].offsetAndLengths.length;
			lineMatches.push(this.lineMatches[i].serialize());
		}

		return {
			path: this.path,
			lineMatches,
			numMatches
		};
	}
}

export class LineMatch implements ILineMatch {
	preview: string;
	lineNumber: number;
	offsetAndLengths: number[][];

	constructor(preview: string, lineNumber: number) {
		this.preview = preview.replace(/(\r|\n)*$/, '');
		this.lineNumber = lineNumber;
		this.offsetAndLengths = [];
	}

	getText(): string {
		return this.preview;
	}

	getLineNumber(): number {
		return this.lineNumber;
	}

	addMatch(offset: number, length: number): void {
		this.offsetAndLengths.push([offset, length]);
	}

	serialize(): ILineMatch {
		const result = {
			preview: this.preview,
			lineNumber: this.lineNumber,
			offsetAndLengths: this.offsetAndLengths
		};

		return result;
	}
R
💄  
Rob Lourens 已提交
370 371
}

372
export interface IRgGlobResult {
R
Rob Lourens 已提交
373
	globArgs: string[];
374
	siblingClauses: glob.IExpression;
R
Rob Lourens 已提交
375 376
}

377
export function foldersToRgExcludeGlobs(folderQueries: IFolderSearch[], globalExclude: glob.IExpression, excludesToSkip?: Set<string>, absoluteGlobs = true): IRgGlobResult {
R
Rob Lourens 已提交
378
	const globArgs: string[] = [];
379
	let siblingClauses: glob.IExpression = {};
R
Rob Lourens 已提交
380
	folderQueries.forEach(folderQuery => {
381
		const totalExcludePattern = objects.assign({}, folderQuery.excludePattern || {}, globalExclude || {});
382
		const result = globExprsToRgGlobs(totalExcludePattern, absoluteGlobs && folderQuery.folder, excludesToSkip);
R
Rob Lourens 已提交
383
		globArgs.push(...result.globArgs);
384 385 386
		if (result.siblingClauses) {
			siblingClauses = objects.assign(siblingClauses, result.siblingClauses);
		}
R
Rob Lourens 已提交
387 388 389 390 391
	});

	return { globArgs, siblingClauses };
}

392
export function foldersToIncludeGlobs(folderQueries: IFolderSearch[], globalInclude: glob.IExpression, absoluteGlobs = true): string[] {
393
	const globArgs: string[] = [];
394 395
	folderQueries.forEach(folderQuery => {
		const totalIncludePattern = objects.assign({}, globalInclude || {}, folderQuery.includePattern || {});
396
		const result = globExprsToRgGlobs(totalIncludePattern, absoluteGlobs && folderQuery.folder);
397 398 399 400 401 402
		globArgs.push(...result.globArgs);
	});

	return globArgs;
}

403
function globExprsToRgGlobs(patterns: glob.IExpression, folder?: string, excludesToSkip?: Set<string>): IRgGlobResult {
R
💄  
Rob Lourens 已提交
404
	const globArgs: string[] = [];
405
	let siblingClauses: glob.IExpression = null;
R
💄  
Rob Lourens 已提交
406 407
	Object.keys(patterns)
		.forEach(key => {
408 409 410 411
			if (excludesToSkip && excludesToSkip.has(key)) {
				return;
			}

412 413 414 415
			if (!key) {
				return;
			}

R
💄  
Rob Lourens 已提交
416
			const value = patterns[key];
417
			key = trimTrailingSlash(folder ? getAbsoluteGlob(folder, key) : key);
R
Rob Lourens 已提交
418

R
💄  
Rob Lourens 已提交
419
			if (typeof value === 'boolean' && value) {
420
				globArgs.push(fixDriveC(key));
R
💄  
Rob Lourens 已提交
421
			} else if (value && value.when) {
422 423 424 425 426
				if (!siblingClauses) {
					siblingClauses = {};
				}

				siblingClauses[key] = value;
R
💄  
Rob Lourens 已提交
427 428 429 430 431 432
			}
		});

	return { globArgs, siblingClauses };
}

433 434
/**
 * Resolves a glob like "node_modules/**" in "/foo/bar" to "/foo/bar/node_modules/**".
R
Rob Lourens 已提交
435 436 437
 * Special cases C:/foo paths to write the glob like /foo instead - see https://github.com/BurntSushi/ripgrep/issues/530.
 *
 * Exported for testing
438
 */
R
Rob Lourens 已提交
439
export function getAbsoluteGlob(folder: string, key: string): string {
440
	return paths.isAbsolute(key) ?
441 442
		key :
		path.join(folder, key);
443
}
R
Rob Lourens 已提交
444

445 446 447
function trimTrailingSlash(str: string): string {
	str = strings.rtrim(str, '\\');
	return strings.rtrim(str, '/');
448
}
449

450 451
export function fixDriveC(path: string): string {
	const root = paths.getRoot(path);
452
	return root.toLowerCase() === 'c:/' ?
453 454
		path.replace(/^c:[/\\]/i, '/') :
		path;
455 456
}

R
Rob Lourens 已提交
457
function getRgArgs(config: IRawSearch): IRgGlobResult {
R
Rob Lourens 已提交
458
	const args = ['--hidden', '--heading', '--line-number', '--color', 'ansi', '--colors', 'path:none', '--colors', 'line:none', '--colors', 'match:fg:red', '--colors', 'match:style:nobold'];
R
💄  
Rob Lourens 已提交
459 460
	args.push(config.contentPattern.isCaseSensitive ? '--case-sensitive' : '--ignore-case');

461
	// includePattern can't have siblingClauses
462 463 464 465 466
	foldersToIncludeGlobs(config.folderQueries, config.includePattern).forEach(globArg => {
		args.push('-g', globArg);
	});

	let siblingClauses: glob.IExpression;
R
Rob Lourens 已提交
467 468 469

	// Find excludes that are exactly the same in all folderQueries - e.g. from user settings, and that start with `**`.
	// To make the command shorter, don't resolve these against every folderQuery path - see #33189.
470 471
	const universalExcludes = findUniversalExcludes(config.folderQueries);
	const rgGlobs = foldersToRgExcludeGlobs(config.folderQueries, config.excludePattern, universalExcludes);
472 473
	rgGlobs.globArgs
		.forEach(rgGlob => args.push('-g', `!${rgGlob}`));
474 475 476 477
	if (universalExcludes) {
		universalExcludes
			.forEach(exclude => args.push('-g', `!${trimTrailingSlash(exclude)}`));
	}
478
	siblingClauses = rgGlobs.siblingClauses;
R
💄  
Rob Lourens 已提交
479 480 481 482 483

	if (config.maxFilesize) {
		args.push('--max-filesize', config.maxFilesize + '');
	}

R
Rob Lourens 已提交
484
	if (config.disregardIgnoreFiles) {
R
Rob Lourens 已提交
485 486 487 488 489 490 491
		// Don't use .gitignore or .ignore
		args.push('--no-ignore');
	}

	// Follow symlinks
	args.push('--follow');

492
	// Set default encoding if only one folder is opened
R
Rob Lourens 已提交
493
	if (config.folderQueries.length === 1 && config.folderQueries[0].fileEncoding && config.folderQueries[0].fileEncoding !== 'utf8') {
494 495
		args.push('--encoding', encoding.toCanonicalName(config.folderQueries[0].fileEncoding));
	}
496

497 498 499 500 501 502 503
	// Ripgrep handles -- as a -- arg separator. Only --.
	// - is ok, --- is ok, --some-flag is handled as query text. Need to special case.
	if (config.contentPattern.pattern === '--') {
		config.contentPattern.isRegExp = true;
		config.contentPattern.pattern = '\\-\\-';
	}

R
Rob Lourens 已提交
504
	let searchPatternAfterDoubleDashes: string;
505 506
	if (config.contentPattern.isWordMatch) {
		const regexp = strings.createRegExp(config.contentPattern.pattern, config.contentPattern.isRegExp, { wholeWord: config.contentPattern.isWordMatch });
507 508
		const regexpStr = regexp.source.replace(/\\\//g, '/'); // RegExp.source arbitrarily returns escaped slashes. Search and destroy.
		args.push('--regexp', regexpStr);
509
	} else if (config.contentPattern.isRegExp) {
R
💄  
Rob Lourens 已提交
510 511
		args.push('--regexp', config.contentPattern.pattern);
	} else {
512 513
		searchPatternAfterDoubleDashes = config.contentPattern.pattern;
		args.push('--fixed-strings');
R
💄  
Rob Lourens 已提交
514 515 516
	}

	// Folder to search
R
Rob Lourens 已提交
517 518 519 520 521 522 523
	args.push('--');

	if (searchPatternAfterDoubleDashes) {
		// Put the query after --, in case the query starts with a dash
		args.push(searchPatternAfterDoubleDashes);
	}

524
	args.push(...config.folderQueries.map(q => q.folder));
525 526
	args.push(...config.extraFiles);

527
	return { globArgs: args, siblingClauses };
R
💄  
Rob Lourens 已提交
528
}
529 530

function getSiblings(file: string): TPromise<string[]> {
531
	return new TPromise<string[]>((resolve, reject) => {
532 533 534 535 536 537 538 539 540
		extfs.readdir(path.dirname(file), (error: Error, files: string[]) => {
			if (error) {
				reject(error);
			}

			resolve(files);
		});
	});
}
541 542 543 544 545 546 547 548

function findUniversalExcludes(folderQueries: IFolderSearch[]): Set<string> {
	if (folderQueries.length < 2) {
		// Nothing to simplify
		return null;
	}

	const firstFolder = folderQueries[0];
549 550 551
	if (!firstFolder.excludePattern) {
		return null;
	}
552 553 554

	const universalExcludes = new Set<string>();
	Object.keys(firstFolder.excludePattern).forEach(key => {
555
		if (strings.startsWith(key, '**') && folderQueries.every(q => q.excludePattern && q.excludePattern[key] === true)) {
556 557 558 559 560 561
			universalExcludes.add(key);
		}
	});

	return universalExcludes;
}