ripgrepTextSearch.ts 15.0 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 postProcessExclusions: glob.ParsedExpression;
R
Rob Lourens 已提交
30

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

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

R
Rob Lourens 已提交
35
	constructor(private config: IRawSearch) {
R
Rob Lourens 已提交
36 37 38 39
	}

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

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

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

59
		const cwd = platform.isWindows ? 'c:/' : '/';
60
		process.nextTick(() => {
61
			const escapedArgs = rgArgs.globArgs
62 63 64
				.map(arg => arg.match(/^-/) ? arg : `'${arg}'`)
				.join(' ');

65
			// Allow caller to register progress callback
66
			const rgCmd = `rg ${escapedArgs}\n - cwd: ${cwd}\n`;
67
			onMessage({ message: rgCmd });
68 69 70
			if (rgArgs.siblingClauses) {
				onMessage({ message: ` - Sibling clauses: ${JSON.stringify(rgArgs.siblingClauses)}\n` });
			}
71
		});
72
		this.rgProc = cp.spawn(rgPath, rgArgs.globArgs, { cwd });
R
💄  
Rob Lourens 已提交
73

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

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

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

101 102 103 104
		let gotData = false;
		this.rgProc.stdout.once('data', () => gotData = true);

		let stderr = '';
R
Rob Lourens 已提交
105
		this.rgProc.stderr.on('data', data => {
106 107 108
			const message = data.toString();
			onMessage({ message });
			stderr += message;
R
Rob Lourens 已提交
109 110 111
		});

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

135 136 137 138 139 140
	/**
	 * 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 {
141 142
		const firstLine = msg.split('\n')[0];

143 144 145 146 147 148 149 150 151
		if (strings.startsWith(firstLine, 'Error parsing regex')) {
			return firstLine;
		}

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

		return undefined;
152
	}
R
💄  
Rob Lourens 已提交
153 154 155
}

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

R
Rob Lourens 已提交
159 160
	public static MATCH_START_MARKER = '\u001b[m\u001b[31m';
	public static MATCH_END_MARKER = '\u001b[m';
R
💄  
Rob Lourens 已提交
161 162 163 164

	private fileMatch: FileMatch;
	private remainder: string;
	private isDone: boolean;
165
	private stringDecoder: NodeStringDecoder;
R
💄  
Rob Lourens 已提交
166 167 168

	private numResults = 0;

169
	constructor(private maxResults: number, private rootFolder: string) {
R
💄  
Rob Lourens 已提交
170
		super();
171
		this.stringDecoder = new StringDecoder();
R
💄  
Rob Lourens 已提交
172
	}
R
Rob Lourens 已提交
173

R
💄  
Rob Lourens 已提交
174 175 176
	public cancel(): void {
		this.isDone = true;
	}
R
Rob Lourens 已提交
177

R
Rob Lourens 已提交
178
	public flush(): void {
179 180
		this.handleDecodedData(this.stringDecoder.end());

R
Rob Lourens 已提交
181 182 183 184 185
		if (this.fileMatch) {
			this.onResult();
		}
	}

186 187 188 189 190 191
	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 已提交
192
		// If the previous data chunk didn't end in a newline, prepend it to this chunk
R
💄  
Rob Lourens 已提交
193
		const dataStr = this.remainder ?
194 195
			this.remainder + decodedData :
			decodedData;
R
Rob Lourens 已提交
196

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

R
💄  
Rob Lourens 已提交
200 201 202 203
		for (let l = 0; l < dataLines.length; l++) {
			const outputLine = dataLines[l].trim();
			if (this.isDone) {
				break;
R
Rob Lourens 已提交
204 205
			}

R
💄  
Rob Lourens 已提交
206
			let r: RegExpMatchArray;
R
Rob Lourens 已提交
207
			if (r = outputLine.match(RipgrepParser.RESULT_REGEX)) {
R
Rob Lourens 已提交
208 209 210 211 212 213 214 215 216
				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 已提交
217
				// Line is a result - add to collected results for the current file path
R
Rob Lourens 已提交
218
				this.handleMatchLine(outputLine, lineNum, matchText);
R
💄  
Rob Lourens 已提交
219 220 221 222 223 224
			} 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 已提交
225
				this.fileMatch = new FileMatch(path.isAbsolute(r[1]) ? r[1] : path.join(this.rootFolder, r[1]));
R
💄  
Rob Lourens 已提交
226
			} else {
R
Rob Lourens 已提交
227
				// Line is empty (or malformed)
R
💄  
Rob Lourens 已提交
228 229 230 231 232 233 234 235 236 237 238 239 240 241
			}
		}
	}

	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;
242
		let hitLimit = false;
R
💄  
Rob Lourens 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257

		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);
258 259 260 261
				if (!hitLimit) {
					lineMatch.addMatch(matchTextStartRealIdx, textRealIdx - matchTextStartRealIdx);
				}

R
💄  
Rob Lourens 已提交
262 263 264 265 266 267
				matchTextStartPos = -1;
				matchTextStartRealIdx = -1;
				i += RipgrepParser.MATCH_END_MARKER.length;
				lastMatchEndPos = i;
				this.numResults++;

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

R
💄  
Rob Lourens 已提交
279 280 281
		const chunk = text.slice(lastMatchEndPos);
		realTextParts.push(chunk);

282
		// Replace preview with version without color codes
R
💄  
Rob Lourens 已提交
283 284
		const preview = realTextParts.join('');
		lineMatch.preview = preview;
285 286 287 288 289 290

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

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

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 已提交
365 366
}

R
Rob Lourens 已提交
367 368
interface IRgGlobResult {
	globArgs: string[];
369
	siblingClauses: glob.IExpression;
R
Rob Lourens 已提交
370 371
}

372
function foldersToRgExcludeGlobs(folderQueries: IFolderSearch[], globalExclude: glob.IExpression): IRgGlobResult {
R
Rob Lourens 已提交
373
	const globArgs: string[] = [];
374
	let siblingClauses: glob.IExpression = {};
R
Rob Lourens 已提交
375
	folderQueries.forEach(folderQuery => {
376 377
		const totalExcludePattern = objects.assign({}, globalExclude || {}, folderQuery.excludePattern || {});
		const result = globExprsToRgGlobs(totalExcludePattern, folderQuery.folder);
R
Rob Lourens 已提交
378
		globArgs.push(...result.globArgs);
379 380 381
		if (result.siblingClauses) {
			siblingClauses = objects.assign(siblingClauses, result.siblingClauses);
		}
R
Rob Lourens 已提交
382 383 384 385 386
	});

	return { globArgs, siblingClauses };
}

387 388 389 390 391 392 393 394 395 396 397
function foldersToIncludeGlobs(folderQueries: IFolderSearch[], globalInclude: glob.IExpression): string[] {
	const globArgs = [];
	folderQueries.forEach(folderQuery => {
		const totalIncludePattern = objects.assign({}, globalInclude || {}, folderQuery.includePattern || {});
		const result = globExprsToRgGlobs(totalIncludePattern, folderQuery.folder);
		globArgs.push(...result.globArgs);
	});

	return globArgs;
}

R
Rob Lourens 已提交
398
function globExprsToRgGlobs(patterns: glob.IExpression, folder: string): IRgGlobResult {
R
💄  
Rob Lourens 已提交
399
	const globArgs: string[] = [];
400
	let siblingClauses: glob.IExpression = null;
R
💄  
Rob Lourens 已提交
401 402 403
	Object.keys(patterns)
		.forEach(key => {
			const value = patterns[key];
404
			key = getAbsoluteGlob(folder, key);
R
Rob Lourens 已提交
405

R
💄  
Rob Lourens 已提交
406
			if (typeof value === 'boolean' && value) {
407
				globArgs.push(fixDriveC(key));
R
💄  
Rob Lourens 已提交
408
			} else if (value && value.when) {
409 410 411 412 413
				if (!siblingClauses) {
					siblingClauses = {};
				}

				siblingClauses[key] = value;
R
💄  
Rob Lourens 已提交
414 415 416 417 418 419
			}
		});

	return { globArgs, siblingClauses };
}

420 421
/**
 * Resolves a glob like "node_modules/**" in "/foo/bar" to "/foo/bar/node_modules/**".
R
Rob Lourens 已提交
422 423 424
 * Special cases C:/foo paths to write the glob like /foo instead - see https://github.com/BurntSushi/ripgrep/issues/530.
 *
 * Exported for testing
425
 */
R
Rob Lourens 已提交
426
export function getAbsoluteGlob(folder: string, key: string): string {
R
Rob Lourens 已提交
427
	let absolute = paths.isAbsolute(key) ?
428 429
		key :
		path.join(folder, key);
R
Rob Lourens 已提交
430 431 432 433 434

	absolute = strings.rtrim(absolute, '\\');
	absolute = strings.rtrim(absolute, '/');

	return absolute;
435
}
436

437 438
export function fixDriveC(path: string): string {
	const root = paths.getRoot(path);
439
	return root.toLowerCase() === 'c:/' ?
440 441
		path.replace(/^c:[/\\]/i, '/') :
		path;
442 443
}

R
Rob Lourens 已提交
444
function getRgArgs(config: IRawSearch): IRgGlobResult {
R
Rob Lourens 已提交
445
	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 已提交
446 447
	args.push(config.contentPattern.isCaseSensitive ? '--case-sensitive' : '--ignore-case');

448
	// includePattern can't have siblingClauses
449 450 451 452 453 454 455 456 457
	foldersToIncludeGlobs(config.folderQueries, config.includePattern).forEach(globArg => {
		args.push('-g', globArg);
	});

	let siblingClauses: glob.IExpression;
	const rgGlobs = foldersToRgExcludeGlobs(config.folderQueries, config.excludePattern);
	rgGlobs.globArgs
		.forEach(rgGlob => args.push('-g', `!${rgGlob}`));
	siblingClauses = rgGlobs.siblingClauses;
R
💄  
Rob Lourens 已提交
458 459 460 461 462

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

R
Rob Lourens 已提交
463
	if (config.disregardIgnoreFiles) {
R
Rob Lourens 已提交
464 465 466 467 468 469 470
		// Don't use .gitignore or .ignore
		args.push('--no-ignore');
	}

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

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

476 477 478 479 480 481 482
	// 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 已提交
483
	let searchPatternAfterDoubleDashes: string;
484 485
	if (config.contentPattern.isWordMatch) {
		const regexp = strings.createRegExp(config.contentPattern.pattern, config.contentPattern.isRegExp, { wholeWord: config.contentPattern.isWordMatch });
486 487
		const regexpStr = regexp.source.replace(/\\\//g, '/'); // RegExp.source arbitrarily returns escaped slashes. Search and destroy.
		args.push('--regexp', regexpStr);
488
	} else if (config.contentPattern.isRegExp) {
R
💄  
Rob Lourens 已提交
489 490
		args.push('--regexp', config.contentPattern.pattern);
	} else {
491 492
		searchPatternAfterDoubleDashes = config.contentPattern.pattern;
		args.push('--fixed-strings');
R
💄  
Rob Lourens 已提交
493 494 495
	}

	// Folder to search
R
Rob Lourens 已提交
496 497 498 499 500 501 502
	args.push('--');

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

503
	args.push(...config.folderQueries.map(q => q.folder));
504 505
	args.push(...config.extraFiles);

506
	return { globArgs: args, siblingClauses };
R
💄  
Rob Lourens 已提交
507
}
508 509

function getSiblings(file: string): TPromise<string[]> {
510
	return new TPromise<string[]>((resolve, reject) => {
511 512 513 514 515 516 517 518 519
		extfs.readdir(path.dirname(file), (error: Error, files: string[]) => {
			if (error) {
				reject(error);
			}

			resolve(files);
		});
	});
}