ripgrepTextSearch.ts 14.2 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';

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

21
import { ISerializedFileMatch, ISerializedSearchComplete, IRawSearch } from './search';
R
Rob Lourens 已提交
22

23
export class RipgrepEngine {
R
Rob Lourens 已提交
24 25
	private isDone = false;
	private rgProc: cp.ChildProcess;
26
	private postProcessExclusions: glob.ParsedExpression;
R
Rob Lourens 已提交
27

R
💄  
Rob Lourens 已提交
28
	private ripgrepParser: RipgrepParser;
R
Rob Lourens 已提交
29

30
	private resultsHandledP: TPromise<any> = TPromise.wrap(null);
31

R
Rob Lourens 已提交
32
	constructor(private config: IRawSearch) {
R
Rob Lourens 已提交
33 34 35 36
	}

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

41
	// TODO@Rob - make promise-based once the old search is gone, and I don't need them to have matching interfaces anymore
42
	search(onResult: (match: ISerializedFileMatch) => void, onMessage: (message: ISearchLog) => void, done: (error: Error, complete: ISerializedSearchComplete) => void): void {
R
Rob Lourens 已提交
43
		if (this.config.rootFolders.length) {
44
			this.searchFolder(this.config.rootFolders[0], onResult, onMessage, done);
R
💄  
Rob Lourens 已提交
45 46 47 48 49
		} else {
			done(null, {
				limitHit: false,
				stats: null
			});
R
Rob Lourens 已提交
50 51 52
		}
	}

53
	private searchFolder(rootFolder: string, onResult: (match: ISerializedFileMatch) => void, onMessage: (message: ISearchLog) => void, done: (error: Error, complete: ISerializedSearchComplete) => void): void {
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
		process.nextTick(() => {
60 61 62 63
			const escapedArgs = rgArgs.args
				.map(arg => arg.match(/^-/) ? arg : `'${arg}'`)
				.join(' ');

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

73
		this.ripgrepParser = new RipgrepParser(this.config.maxResults, rootFolder);
74 75 76
		this.ripgrepParser.on('result', (match: ISerializedFileMatch) => {
			if (this.postProcessExclusions) {
				const relativePath = path.relative(rootFolder, match.path);
77
				const handleResultP = (<TPromise<string>>this.postProcessExclusions(relativePath, 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 143 144 145 146 147 148 149 150 151 152 153 154 155
		const firstLine = msg.split('\n')[0];
		if (firstLine.match(/^No files were searched, which means ripgrep/)) {
			// Not really a useful message to show in the UI
			return undefined;
		}

		// The error "No such file or directory" is returned for broken symlinks and also for bad search paths.
		// Only show it if it's from a search path.
		const reg = /^(\.\/.*): No such file or directory \(os error 2\)/;
		const noSuchFileMatch = firstLine.match(reg);
		if (noSuchFileMatch) {
			const errorPath = noSuchFileMatch[1];
			return this.config.searchPaths && this.config.searchPaths.indexOf(errorPath) >= 0 ? firstLine : undefined;
		}

156 157 158 159 160 161 162 163 164
		if (strings.startsWith(firstLine, 'Error parsing regex')) {
			return firstLine;
		}

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

		return undefined;
165
	}
R
💄  
Rob Lourens 已提交
166 167 168
}

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

R
Rob Lourens 已提交
172 173
	public static MATCH_START_MARKER = '\u001b[m\u001b[31m';
	public static MATCH_END_MARKER = '\u001b[m';
R
💄  
Rob Lourens 已提交
174 175 176 177

	private fileMatch: FileMatch;
	private remainder: string;
	private isDone: boolean;
178
	private stringDecoder: NodeStringDecoder;
R
💄  
Rob Lourens 已提交
179 180 181

	private numResults = 0;

182
	constructor(private maxResults: number, private rootFolder: string) {
R
💄  
Rob Lourens 已提交
183
		super();
184
		this.stringDecoder = new StringDecoder();
R
💄  
Rob Lourens 已提交
185
	}
R
Rob Lourens 已提交
186

R
💄  
Rob Lourens 已提交
187 188 189
	public cancel(): void {
		this.isDone = true;
	}
R
Rob Lourens 已提交
190

R
Rob Lourens 已提交
191
	public flush(): void {
192 193
		this.handleDecodedData(this.stringDecoder.end());

R
Rob Lourens 已提交
194 195 196 197 198
		if (this.fileMatch) {
			this.onResult();
		}
	}

199 200 201 202 203 204
	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 已提交
205
		// If the previous data chunk didn't end in a newline, prepend it to this chunk
R
💄  
Rob Lourens 已提交
206
		const dataStr = this.remainder ?
207 208
			this.remainder + decodedData :
			decodedData;
R
Rob Lourens 已提交
209

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

R
💄  
Rob Lourens 已提交
213 214 215 216
		for (let l = 0; l < dataLines.length; l++) {
			const outputLine = dataLines[l].trim();
			if (this.isDone) {
				break;
R
Rob Lourens 已提交
217 218
			}

R
💄  
Rob Lourens 已提交
219
			let r: RegExpMatchArray;
R
Rob Lourens 已提交
220
			if (r = outputLine.match(RipgrepParser.RESULT_REGEX)) {
R
Rob Lourens 已提交
221 222 223 224 225 226 227 228 229
				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 已提交
230
				// Line is a result - add to collected results for the current file path
R
Rob Lourens 已提交
231
				this.handleMatchLine(outputLine, lineNum, matchText);
R
💄  
Rob Lourens 已提交
232 233 234 235 236 237
			} 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();
				}

238
				this.fileMatch = new FileMatch(path.resolve(this.rootFolder, r[1]));
R
💄  
Rob Lourens 已提交
239
			} else {
R
Rob Lourens 已提交
240
				// Line is empty (or malformed)
R
💄  
Rob Lourens 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254
			}
		}
	}

	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;
255
		let hitLimit = false;
R
💄  
Rob Lourens 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

		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);
271 272 273 274
				if (!hitLimit) {
					lineMatch.addMatch(matchTextStartRealIdx, textRealIdx - matchTextStartRealIdx);
				}

R
💄  
Rob Lourens 已提交
275 276 277 278 279 280
				matchTextStartPos = -1;
				matchTextStartRealIdx = -1;
				i += RipgrepParser.MATCH_END_MARKER.length;
				lastMatchEndPos = i;
				this.numResults++;

281 282
				// Check hit maxResults limit
				if (this.numResults >= this.maxResults) {
283 284
					// Finish the line, then report the result below
					hitLimit = true;
285
				}
R
Rob Lourens 已提交
286
			} else {
R
💄  
Rob Lourens 已提交
287 288
				i++;
				textRealIdx++;
R
Rob Lourens 已提交
289 290 291
			}
		}

R
💄  
Rob Lourens 已提交
292 293 294
		const chunk = text.slice(lastMatchEndPos);
		realTextParts.push(chunk);

295
		// Replace preview with version without color codes
R
💄  
Rob Lourens 已提交
296 297
		const preview = realTextParts.join('');
		lineMatch.preview = preview;
298 299 300 301 302 303

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

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

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 已提交
378 379
}

380
function globExprsToRgGlobs(patterns: glob.IExpression): { globArgs: string[], siblingClauses: glob.IExpression } {
R
💄  
Rob Lourens 已提交
381
	const globArgs: string[] = [];
382
	let siblingClauses: glob.IExpression = null;
R
💄  
Rob Lourens 已提交
383 384 385 386 387 388 389 390 391 392 393
	Object.keys(patterns)
		.forEach(key => {
			const value = patterns[key];
			if (typeof value === 'boolean' && value) {
				// globs added to ripgrep don't match from the root by default, so add a /
				if (key.charAt(0) !== '*') {
					key = '/' + key;
				}

				globArgs.push(key);
			} else if (value && value.when) {
394 395 396 397 398
				if (!siblingClauses) {
					siblingClauses = {};
				}

				siblingClauses[key] = value;
R
💄  
Rob Lourens 已提交
399 400 401 402 403 404
			}
		});

	return { globArgs, siblingClauses };
}

405
function getRgArgs(config: IRawSearch): { args: string[], siblingClauses: glob.IExpression } {
R
Rob Lourens 已提交
406
	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 已提交
407 408 409 410 411 412 413 414 415
	args.push(config.contentPattern.isCaseSensitive ? '--case-sensitive' : '--ignore-case');

	if (config.includePattern) {
		// I don't think includePattern can have siblingClauses
		globExprsToRgGlobs(config.includePattern).globArgs.forEach(globArg => {
			args.push('-g', globArg);
		});
	}

416
	let siblingClauses: glob.IExpression;
R
💄  
Rob Lourens 已提交
417 418 419 420 421 422 423 424 425 426 427
	if (config.excludePattern) {
		const rgGlobs = globExprsToRgGlobs(config.excludePattern);
		rgGlobs.globArgs
			.forEach(rgGlob => args.push('-g', `!${rgGlob}`));
		siblingClauses = rgGlobs.siblingClauses;
	}

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

R
Rob Lourens 已提交
428
	if (config.disregardIgnoreFiles) {
R
Rob Lourens 已提交
429 430 431 432 433 434 435
		// Don't use .gitignore or .ignore
		args.push('--no-ignore');
	}

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

436
	// Set default encoding
R
Rob Lourens 已提交
437
	if (config.fileEncoding && config.fileEncoding !== 'utf8') {
438 439 440
		args.push('--encoding', encoding.toCanonicalName(config.fileEncoding));
	}

441 442 443 444 445 446 447
	// 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 已提交
448
	let searchPatternAfterDoubleDashes: string;
449 450
	if (config.contentPattern.isWordMatch) {
		const regexp = strings.createRegExp(config.contentPattern.pattern, config.contentPattern.isRegExp, { wholeWord: config.contentPattern.isWordMatch });
451 452
		const regexpStr = regexp.source.replace(/\\\//g, '/'); // RegExp.source arbitrarily returns escaped slashes. Search and destroy.
		args.push('--regexp', regexpStr);
453
	} else if (config.contentPattern.isRegExp) {
R
💄  
Rob Lourens 已提交
454 455
		args.push('--regexp', config.contentPattern.pattern);
	} else {
456 457
		searchPatternAfterDoubleDashes = config.contentPattern.pattern;
		args.push('--fixed-strings');
R
💄  
Rob Lourens 已提交
458 459 460
	}

	// Folder to search
R
Rob Lourens 已提交
461 462 463 464 465 466 467
	args.push('--');

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

468 469 470 471 472
	if (config.searchPaths && config.searchPaths.length) {
		args.push(...config.searchPaths);
	} else {
		args.push('./');
	}
R
💄  
Rob Lourens 已提交
473

474 475
	args.push(...config.extraFiles);

R
💄  
Rob Lourens 已提交
476 477
	return { args, siblingClauses };
}
478 479

function getSiblings(file: string): TPromise<string[]> {
480
	return new TPromise<string[]>((resolve, reject) => {
481 482 483 484 485 486 487 488 489
		extfs.readdir(path.dirname(file), (error: Error, files: string[]) => {
			if (error) {
				reject(error);
			}

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