ripgrepTextSearch.ts 10.8 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';
R
💄  
Rob Lourens 已提交
9

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

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

import { ISerializedFileMatch, ISerializedSearchComplete, IRawSearch, ISearchEngine } from './search';

R
Rob Lourens 已提交
22
export class RipgrepEngine implements ISearchEngine<ISerializedFileMatch> {
R
Rob Lourens 已提交
23 24
	private isDone = false;
	private rgProc: cp.ChildProcess;
25
	private postProcessExclusions: glob.ParsedExpression;
R
Rob Lourens 已提交
26

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

R
Rob Lourens 已提交
29
	constructor(private config: IRawSearch) {
R
Rob Lourens 已提交
30 31 32 33
	}

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

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

R
Rob Lourens 已提交
50
	private searchFolder(rootFolder: string, onResult: (match: ISerializedFileMatch) => void, onProgress: (progress: IProgress) => void, done: (error: Error, complete: ISerializedSearchComplete) => void): void {
51
		const rgArgs = getRgArgs(this.config);
52 53 54
		if (rgArgs.siblingClauses) {
			this.postProcessExclusions = glob.parseToAsync(rgArgs.siblingClauses, { trimForExclusions: true });
		}
R
💄  
Rob Lourens 已提交
55

R
Rob Lourens 已提交
56
		// console.log(`rg ${rgArgs.args.join(' ')}, cwd: ${rootFolder}`);
R
💄  
Rob Lourens 已提交
57 58
		this.rgProc = cp.spawn(rgPath, rgArgs.args, { cwd: rootFolder });

59
		this.ripgrepParser = new RipgrepParser(this.config.maxResults, rootFolder);
60 61 62 63 64 65 66 67 68 69 70 71
		this.ripgrepParser.on('result', (match: ISerializedFileMatch) => {
			if (this.postProcessExclusions) {
				const relativePath = path.relative(rootFolder, match.path);
				(<TPromise<string>>this.postProcessExclusions(relativePath, undefined, () => getSiblings(match.path))).then(globMatch => {
					if (!globMatch) {
						onResult(match);
					}
				});
			} else {
				onResult(match);
			}
		});
R
💄  
Rob Lourens 已提交
72 73 74 75 76 77 78
		this.ripgrepParser.on('hitLimit', () => {
			this.cancel();
			done(null, {
				limitHit: true,
				stats: null
			});
		});
R
Rob Lourens 已提交
79 80

		this.rgProc.stdout.on('data', data => {
R
💄  
Rob Lourens 已提交
81
			this.ripgrepParser.handleData(data);
R
Rob Lourens 已提交
82 83 84
		});

		this.rgProc.stderr.on('data', data => {
R
💄  
Rob Lourens 已提交
85
			// TODO@rob remove console.logs
R
Rob Lourens 已提交
86
			console.log('stderr:');
R
Rob Lourens 已提交
87 88 89 90 91
			console.log(data.toString());
		});

		this.rgProc.on('close', code => {
			this.rgProc = null;
R
💄  
Rob Lourens 已提交
92
			// console.log(`closed with ${code}`);
R
Rob Lourens 已提交
93 94 95 96 97 98 99 100 101 102

			if (!this.isDone) {
				this.isDone = true;
				done(null, {
					limitHit: false,
					stats: null
				});
			}
		});
	}
R
💄  
Rob Lourens 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
}

export class RipgrepParser extends EventEmitter {
	private static RESULT_REGEX = /^\u001b\[m(\d+)\u001b\[m:(.*)$/;
	private static FILE_REGEX = /^\u001b\[m(.+)\u001b\[m$/;

	private static MATCH_START_MARKER = '\u001b[m\u001b[31m';
	private static MATCH_END_MARKER = '\u001b[m';

	private fileMatch: FileMatch;
	private remainder: string;
	private isDone: boolean;

	private numResults = 0;

118
	constructor(private maxResults: number, private rootFolder: string) {
R
💄  
Rob Lourens 已提交
119 120
		super();
	}
R
Rob Lourens 已提交
121

R
💄  
Rob Lourens 已提交
122 123 124
	public cancel(): void {
		this.isDone = true;
	}
R
Rob Lourens 已提交
125

R
💄  
Rob Lourens 已提交
126 127 128 129 130
	public handleData(data: string | Buffer): void {
		// If the previous data chunk didn't end in a newline, append it to this chunk
		const dataStr = this.remainder ?
			this.remainder + data.toString() :
			data.toString();
R
Rob Lourens 已提交
131

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

R
💄  
Rob Lourens 已提交
135 136 137 138
		for (let l = 0; l < dataLines.length; l++) {
			const outputLine = dataLines[l].trim();
			if (this.isDone) {
				break;
R
Rob Lourens 已提交
139 140
			}

R
💄  
Rob Lourens 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
			let r: RegExpMatchArray;
			if (!outputLine) {
				if (this.fileMatch) {
					this.onResult();
				}
			} else if (r = outputLine.match(RipgrepParser.RESULT_REGEX)) {
				// Line is a result - add to collected results for the current file path
				this.handleMatchLine(outputLine, parseInt(r[1]) - 1, r[2]);
			} 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) {
					// TODO@Rob Check fileMatch against other exclude globs
					this.onResult();
				}

156
				this.fileMatch = new FileMatch(path.join(this.rootFolder, r[1]));
R
💄  
Rob Lourens 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
			} else {
				// Line is malformed
			}
		}
	}

	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;
173
		let hitLimit = false;
R
💄  
Rob Lourens 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

		const realTextParts: string[] = [];

		// todo@Rob Consider just rewriting with a regex. I think perf will be fine.
		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);
190 191 192 193
				if (!hitLimit) {
					lineMatch.addMatch(matchTextStartRealIdx, textRealIdx - matchTextStartRealIdx);
				}

R
💄  
Rob Lourens 已提交
194 195 196 197 198 199
				matchTextStartPos = -1;
				matchTextStartRealIdx = -1;
				i += RipgrepParser.MATCH_END_MARKER.length;
				lastMatchEndPos = i;
				this.numResults++;

200 201
				// Check hit maxResults limit
				if (this.numResults >= this.maxResults) {
202 203
					// Finish the line, then report the result below
					hitLimit = true;
204
				}
R
Rob Lourens 已提交
205
			} else {
R
💄  
Rob Lourens 已提交
206 207
				i++;
				textRealIdx++;
R
Rob Lourens 已提交
208 209 210
			}
		}

R
💄  
Rob Lourens 已提交
211 212 213
		const chunk = text.slice(lastMatchEndPos);
		realTextParts.push(chunk);

214
		// Replace preview with version without color codes
R
💄  
Rob Lourens 已提交
215 216
		const preview = realTextParts.join('');
		lineMatch.preview = preview;
217 218 219 220 221 222

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

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

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 已提交
297 298
}

299
function globExprsToRgGlobs(patterns: glob.IExpression): { globArgs: string[], siblingClauses: glob.IExpression } {
R
💄  
Rob Lourens 已提交
300
	const globArgs: string[] = [];
301
	let siblingClauses: glob.IExpression = null;
R
💄  
Rob Lourens 已提交
302 303 304 305 306 307 308 309 310 311 312
	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) {
313 314 315 316 317
				if (!siblingClauses) {
					siblingClauses = {};
				}

				siblingClauses[key] = value;
R
💄  
Rob Lourens 已提交
318 319 320 321 322 323
			}
		});

	return { globArgs, siblingClauses };
}

324
function getRgArgs(config: IRawSearch): { args: string[], siblingClauses: glob.IExpression } {
325
	const args = ['--heading', '--line-number', '--color', 'ansi', '--colors', 'path:none', '--colors', 'line:none', '--colors', 'match:fg:red', '--colors', 'match:style:nobold'];
R
💄  
Rob Lourens 已提交
326 327 328 329 330 331 332 333 334
	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);
		});
	}

335
	let siblingClauses: glob.IExpression;
R
💄  
Rob Lourens 已提交
336 337 338 339 340 341 342 343 344 345 346
	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 已提交
347 348 349 350 351 352 353 354
	if (!config.useIgnoreFiles) {
		// Don't use .gitignore or .ignore
		args.push('--no-ignore');
	}

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

355 356 357 358 359
	// Set default encoding
	if (config.fileEncoding) {
		args.push('--encoding', encoding.toCanonicalName(config.fileEncoding));
	}

R
💄  
Rob Lourens 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
	if (config.contentPattern.isRegExp) {
		if (config.contentPattern.isWordMatch) {
			args.push('--word-regexp');
		}

		args.push('--regexp', config.contentPattern.pattern);
	} else {
		if (config.contentPattern.isWordMatch) {
			args.push('--word-regexp', '--regexp', strings.escapeRegExpCharacters(config.contentPattern.pattern));
		} else {
			args.push('--fixed-strings', config.contentPattern.pattern);
		}
	}

	// Folder to search
375
	args.push('--', './');
R
💄  
Rob Lourens 已提交
376 377 378

	return { args, siblingClauses };
}
379 380 381 382 383 384 385 386 387 388 389 390

function getSiblings(file: string): TPromise<string[]> {
	return new TPromise((resolve, reject) => {
		extfs.readdir(path.dirname(file), (error: Error, files: string[]) => {
			if (error) {
				reject(error);
			}

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