ripgrepTextSearch.ts 9.5 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 8
import { EventEmitter } from 'events';

R
Rob Lourens 已提交
9 10 11 12 13 14 15 16 17
import * as cp from 'child_process';
import { rgPath } from 'vscode-ripgrep';

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';

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

R
Rob Lourens 已提交
18
export class RipgrepEngine implements ISearchEngine<ISerializedFileMatch> {
R
Rob Lourens 已提交
19 20
	private isDone = false;
	private rgProc: cp.ChildProcess;
R
💄  
Rob Lourens 已提交
21
	private postProcessExclusions: glob.SiblingClause[];
R
Rob Lourens 已提交
22

R
💄  
Rob Lourens 已提交
23
	private ripgrepParser: RipgrepParser;
R
Rob Lourens 已提交
24

R
Rob Lourens 已提交
25
	constructor(private config: IRawSearch) {
R
Rob Lourens 已提交
26 27 28 29
	}

	cancel(): void {
		this.isDone = true;
R
💄  
Rob Lourens 已提交
30
		this.ripgrepParser.cancel();
R
Rob Lourens 已提交
31 32 33
		this.rgProc.kill();
	}

R
Rob Lourens 已提交
34
	search(onResult: (match: ISerializedFileMatch) => void, onProgress: (progress: IProgress) => void, done: (error: Error, complete: ISerializedSearchComplete) => void): void {
R
Rob Lourens 已提交
35
		if (this.config.rootFolders.length) {
R
Rob Lourens 已提交
36
			this.searchFolder(this.config.rootFolders[0], onResult, onProgress, done);
R
💄  
Rob Lourens 已提交
37 38 39 40 41
		} else {
			done(null, {
				limitHit: false,
				stats: null
			});
R
Rob Lourens 已提交
42 43 44
		}
	}

R
Rob Lourens 已提交
45
	private searchFolder(rootFolder: string, onResult: (match: ISerializedFileMatch) => void, onProgress: (progress: IProgress) => void, done: (error: Error, complete: ISerializedSearchComplete) => void): void {
R
💄  
Rob Lourens 已提交
46 47 48
		const rgArgs = getRgArgs(this.config, rootFolder);
		this.postProcessExclusions = rgArgs.siblingClauses;

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

		this.ripgrepParser = new RipgrepParser(this.config.maxResults);
		this.ripgrepParser.on('result', onResult);
		this.ripgrepParser.on('hitLimit', () => {
			this.cancel();
			done(null, {
				limitHit: true,
				stats: null
			});
		});
R
Rob Lourens 已提交
61 62

		this.rgProc.stdout.on('data', data => {
R
💄  
Rob Lourens 已提交
63
			this.ripgrepParser.handleData(data);
R
Rob Lourens 已提交
64 65 66
		});

		this.rgProc.stderr.on('data', data => {
R
💄  
Rob Lourens 已提交
67
			// TODO@rob remove console.logs
R
Rob Lourens 已提交
68
			console.log('stderr:');
R
Rob Lourens 已提交
69 70 71 72 73
			console.log(data.toString());
		});

		this.rgProc.on('close', code => {
			this.rgProc = null;
R
💄  
Rob Lourens 已提交
74
			// console.log(`closed with ${code}`);
R
Rob Lourens 已提交
75 76 77 78 79 80 81 82 83 84

			if (!this.isDone) {
				this.isDone = true;
				done(null, {
					limitHit: false,
					stats: null
				});
			}
		});
	}
R
💄  
Rob Lourens 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
}

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;

	constructor(private maxResults: number) {
		super();
	}
R
Rob Lourens 已提交
103

R
💄  
Rob Lourens 已提交
104 105 106
	public cancel(): void {
		this.isDone = true;
	}
R
Rob Lourens 已提交
107

R
💄  
Rob Lourens 已提交
108 109 110 111 112
	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 已提交
113

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

R
💄  
Rob Lourens 已提交
117 118 119 120
		for (let l = 0; l < dataLines.length; l++) {
			const outputLine = dataLines[l].trim();
			if (this.isDone) {
				break;
R
Rob Lourens 已提交
121 122
			}

R
💄  
Rob Lourens 已提交
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
			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();
				}

				this.fileMatch = new FileMatch(r[1]);
			} 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;

		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);
				lineMatch.addMatch(matchTextStartRealIdx, textRealIdx - matchTextStartRealIdx);
				matchTextStartPos = -1;
				matchTextStartRealIdx = -1;
				i += RipgrepParser.MATCH_END_MARKER.length;
				lastMatchEndPos = i;
				this.numResults++;

178 179 180 181 182 183 184 185
				// Check hit maxResults limit
				if (this.numResults >= this.maxResults) {
					// Replace preview with what we have so far, TODO@Rob
					lineMatch.preview = realTextParts.join('');
					this.cancel();
					this.onResult();
					this.emit('hitLimit');
				}
R
Rob Lourens 已提交
186
			} else {
R
💄  
Rob Lourens 已提交
187 188
				i++;
				textRealIdx++;
R
Rob Lourens 已提交
189 190 191
			}
		}

R
💄  
Rob Lourens 已提交
192 193 194
		const chunk = text.slice(lastMatchEndPos);
		realTextParts.push(chunk);

195
		// Replace preview with version without color codes
R
💄  
Rob Lourens 已提交
196 197 198
		const preview = realTextParts.join('');
		lineMatch.preview = preview;
	}
R
Rob Lourens 已提交
199

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

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

function globExprsToRgGlobs(patterns: glob.IExpression): { globArgs: string[], siblingClauses: glob.SiblingClause[] } {
	const globArgs: string[] = [];
	const siblingClauses: glob.SiblingClause[] = [];
	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) {
				siblingClauses.push(value);
			}
		});

	return { globArgs, siblingClauses };
}

function getRgArgs(config: IRawSearch, rootFolder: string): { args: string[], siblingClauses: glob.SiblingClause[] } {
	// -uu == Skip gitignore files, and hidden files/folders
	const args = ['--heading', '-uu', '--line-number', '--color', 'ansi', '--colors', 'path:none', '--colors', 'line:none', '--colors', 'match:fg:red', '--colors', 'match:style:nobold'];
	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);
		});
	}

	let siblingClauses: glob.SiblingClause[] = [];
	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 + '');
	}

	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
	args.push('--', rootFolder);

	return { args, siblingClauses };
}