ripgrepTextSearch.ts 9.7 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 13 14 15 16 17 18
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 已提交
19
export class RipgrepEngine implements ISearchEngine<ISerializedFileMatch> {
R
Rob Lourens 已提交
20 21
	private isDone = false;
	private rgProc: cp.ChildProcess;
R
💄  
Rob Lourens 已提交
22
	private postProcessExclusions: glob.SiblingClause[];
R
Rob Lourens 已提交
23

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

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

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

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

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

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

54
		this.ripgrepParser = new RipgrepParser(this.config.maxResults, rootFolder);
R
💄  
Rob Lourens 已提交
55 56 57 58 59 60 61 62
		this.ripgrepParser.on('result', onResult);
		this.ripgrepParser.on('hitLimit', () => {
			this.cancel();
			done(null, {
				limitHit: true,
				stats: null
			});
		});
R
Rob Lourens 已提交
63 64

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

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

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

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

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;

102
	constructor(private maxResults: number, private rootFolder: string) {
R
💄  
Rob Lourens 已提交
103 104
		super();
	}
R
Rob Lourens 已提交
105

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

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

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

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

R
💄  
Rob Lourens 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
			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();
				}

140
				this.fileMatch = new FileMatch(path.join(this.rootFolder, r[1]));
R
💄  
Rob Lourens 已提交
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 178 179
			} 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++;

180 181 182 183 184 185 186 187
				// 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 已提交
188
			} else {
R
💄  
Rob Lourens 已提交
189 190
				i++;
				textRealIdx++;
R
Rob Lourens 已提交
191 192 193
			}
		}

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

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

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

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 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
}

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

297
function getRgArgs(config: IRawSearch): { args: string[], siblingClauses: glob.SiblingClause[] } {
298
	const args = ['--heading', '--line-number', '--color', 'ansi', '--colors', 'path:none', '--colors', 'line:none', '--colors', 'match:fg:red', '--colors', 'match:style:nobold'];
R
💄  
Rob Lourens 已提交
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
	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);
		}
	}

334 335 336 337 338
	if (!config.useIgnoreFiles) {
		// Don't use .gitignore or .ignore
		args.push('--no-ignore');
	}

R
💄  
Rob Lourens 已提交
339
	// Folder to search
340
	args.push('--', './');
R
💄  
Rob Lourens 已提交
341 342 343

	return { args, siblingClauses };
}