searchWorker.ts 9.6 KB
Newer Older
R
roblou 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import * as fs from 'fs';
9 10
import gracefulFs = require('graceful-fs');
gracefulFs.gracefulify(fs);
R
roblou 已提交
11

R
roblou 已提交
12
import { onUnexpectedError } from 'vs/base/common/errors';
R
roblou 已提交
13
import * as strings from 'vs/base/common/strings';
14
import { TPromise } from 'vs/base/common/winjs.base';
R
roblou 已提交
15 16
import { ISerializedFileMatch } from '../search';
import * as baseMime from 'vs/base/common/mime';
17
import { ILineMatch } from 'vs/platform/search/common/search';
R
roblou 已提交
18 19 20
import { UTF16le, UTF16be, UTF8, UTF8_with_bom, encodingExists, decode } from 'vs/base/node/encoding';
import { detectMimeAndEncodingFromBuffer } from 'vs/base/node/mime';

21
import { ISearchWorker, ISearchWorkerConfig, ISearchWorkerSearchArgs, ISearchWorkerSearchResult } from './searchWorkerIpc';
R
roblou 已提交
22

R
roblou 已提交
23 24 25 26 27
interface ReadLinesOptions {
	bufferLength: number;
	encoding: string;
}

28 29
// Global isCanceled flag for the process. It's only set once and this avoids awkwardness in passing it around.
let isCanceled = false;
R
roblou 已提交
30

R
roblou 已提交
31 32 33 34 35 36 37 38
const MAX_FILE_ERRORS = 5; // Don't report more than this number of errors, 1 per file, to avoid flooding the log when there's a general issue
let numErrorsLogged = 0;
function onError(error: any): void {
	if (numErrorsLogged++ < MAX_FILE_ERRORS) {
		onUnexpectedError(error);
	}
}

39 40
export class SearchWorker implements ISearchWorker {
	private contentPattern: RegExp;
R
roblou 已提交
41
	private nextSearch = TPromise.wrap(null);
42 43
	private config: ISearchWorkerConfig;
	private fileEncoding: string;
R
roblou 已提交
44

R
roblou 已提交
45 46
	initialize(config: ISearchWorkerConfig): TPromise<void> {
		this.contentPattern = strings.createRegExp(config.pattern.pattern, config.pattern.isRegExp, { matchCase: config.pattern.isCaseSensitive, wholeWord: config.pattern.isWordMatch, multiline: false, global: true });
R
roblou 已提交
47
		this.config = config;
48
		this.fileEncoding = encodingExists(config.fileEncoding) ? config.fileEncoding : UTF8;
R
roblou 已提交
49 50 51 52
		return TPromise.wrap<void>(undefined);
	}

	cancel(): TPromise<void> {
53
		isCanceled = true;
R
roblou 已提交
54
		return TPromise.wrap<void>(null);
R
roblou 已提交
55 56
	}

57 58
	search(args: ISearchWorkerSearchArgs): TPromise<ISearchWorkerSearchResult> {
		// Queue this search to run after the current one
59
		return this.nextSearch = this.nextSearch
R
roblou 已提交
60
			.then(() => searchBatch(args.absolutePaths, this.contentPattern, this.fileEncoding, args.maxResults));
61 62
	}
}
R
roblou 已提交
63

64
/**
R
roblou 已提交
65
 * Searches some number of the given paths concurrently, and starts searches in other paths when those complete.
66
 */
R
roblou 已提交
67
function searchBatch(absolutePaths: string[], contentPattern: RegExp, fileEncoding: string, maxResults?: number): TPromise<ISearchWorkerSearchResult> {
68 69 70 71
	if (isCanceled) {
		return TPromise.wrap(null);
	}

R
roblou 已提交
72 73 74
	return new TPromise(batchDone => {
		const result: ISearchWorkerSearchResult = {
			matches: [],
R
roblou 已提交
75
			numMatches: 0,
R
roblou 已提交
76 77 78
			limitReached: false
		};

R
roblou 已提交
79
		// Search in the given path, and when it's finished, search in the next path in absolutePaths
R
roblou 已提交
80
		const startSearchInFile = (absolutePath: string): TPromise<void> => {
R
roblou 已提交
81
			return searchInFile(absolutePath, contentPattern, fileEncoding, maxResults && (maxResults - result.numMatches)).then(fileResult => {
82
				// Finish early if search is canceled
R
roblou 已提交
83 84 85 86
				if (isCanceled) {
					return;
				}

R
roblou 已提交
87 88 89 90
				if (fileResult) {
					result.numMatches += fileResult.numMatches;
					result.matches.push(fileResult.match.serialize());
					if (fileResult.limitReached) {
R
roblou 已提交
91
						// If the limit was reached, terminate early with the results so far and cancel in-progress searches.
R
roblou 已提交
92 93
						isCanceled = true;
						result.limitReached = true;
94
						return batchDone(result);
R
roblou 已提交
95
					}
96
				}
R
roblou 已提交
97
			}, onError);
R
roblou 已提交
98
		};
R
roblou 已提交
99

100
		TPromise.join(absolutePaths.map(startSearchInFile)).then(() => {
R
roblou 已提交
101 102
			batchDone(result);
		});
R
roblou 已提交
103
	});
104
}
R
roblou 已提交
105

106 107
interface IFileSearchResult {
	match: FileMatch;
R
roblou 已提交
108
	numMatches: number;
109 110
	limitReached?: boolean;
}
R
roblou 已提交
111

R
roblou 已提交
112
function searchInFile(absolutePath: string, contentPattern: RegExp, fileEncoding: string, maxResults?: number): TPromise<IFileSearchResult> {
113 114
	let fileMatch: FileMatch = null;
	let limitReached = false;
R
roblou 已提交
115
	let numMatches = 0;
116 117 118 119 120 121

	const perLineCallback = (line: string, lineNumber: number) => {
		let lineMatch: LineMatch = null;
		let match = contentPattern.exec(line);

		// Record all matches into file result
R
roblou 已提交
122
		while (match !== null && match[0].length > 0 && !isCanceled && !limitReached) {
123 124 125
			if (fileMatch === null) {
				fileMatch = new FileMatch(absolutePath);
			}
R
roblou 已提交
126

127 128 129 130
			if (lineMatch === null) {
				lineMatch = new LineMatch(line, lineNumber);
				fileMatch.addMatch(lineMatch);
			}
R
roblou 已提交
131

132
			lineMatch.addMatch(match.index, match[0].length);
R
roblou 已提交
133

R
roblou 已提交
134 135
			numMatches++;
			if (maxResults && numMatches >= maxResults) {
136
				limitReached = true;
R
roblou 已提交
137 138
			}

139 140 141 142 143
			match = contentPattern.exec(line);
		}
	};

	// Read lines buffered to support large files
144
	return readlinesAsync(absolutePath, perLineCallback, { bufferLength: 8096, encoding: fileEncoding }).then(
R
roblou 已提交
145
		() => fileMatch ? { match: fileMatch, limitReached, numMatches } : null);
146
}
R
roblou 已提交
147

148 149
function readlinesAsync(filename: string, perLineCallback: (line: string, lineNumber: number) => void, options: ReadLinesOptions): TPromise<void> {
	return new TPromise<void>((resolve, reject) => {
R
roblou 已提交
150 151
		fs.open(filename, 'r', null, (error: Error, fd: number) => {
			if (error) {
152
				return reject(error);
R
roblou 已提交
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
			}

			let buffer = new Buffer(options.bufferLength);
			let pos: number;
			let i: number;
			let line = '';
			let lineNumber = 0;
			let lastBufferHadTraillingCR = false;

			const decodeBuffer = (buffer: NodeBuffer, start, end): string => {
				if (options.encoding === UTF8 || options.encoding === UTF8_with_bom) {
					return buffer.toString(undefined, start, end); // much faster to use built in toString() when encoding is default
				}

				return decode(buffer.slice(start, end), options.encoding);
			};

			const lineFinished = (offset: number): void => {
				line += decodeBuffer(buffer, pos, i + offset);
				perLineCallback(line, lineNumber);
				line = '';
				lineNumber++;
				pos = i + offset;
			};

			const readFile = (isFirstRead: boolean, clb: (error: Error) => void): void => {
179
				if (isCanceled) {
R
roblou 已提交
180 181 182 183
					return clb(null); // return early if canceled or limit reached
				}

				fs.read(fd, buffer, 0, buffer.length, null, (error: Error, bytesRead: number, buffer: NodeBuffer) => {
184
					if (error || bytesRead === 0 || isCanceled) {
R
roblou 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 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
						return clb(error); // return early if canceled or limit reached or no more bytes to read
					}

					pos = 0;
					i = 0;

					// Detect encoding and mime when this is the beginning of the file
					if (isFirstRead) {
						let mimeAndEncoding = detectMimeAndEncodingFromBuffer(buffer, bytesRead);
						if (mimeAndEncoding.mimes[mimeAndEncoding.mimes.length - 1] !== baseMime.MIME_TEXT) {
							return clb(null); // skip files that seem binary
						}

						// Check for BOM offset
						switch (mimeAndEncoding.encoding) {
							case UTF8:
								pos = i = 3;
								options.encoding = UTF8;
								break;
							case UTF16be:
								pos = i = 2;
								options.encoding = UTF16be;
								break;
							case UTF16le:
								pos = i = 2;
								options.encoding = UTF16le;
								break;
						}
					}

					if (lastBufferHadTraillingCR) {
						if (buffer[i] === 0x0a) { // LF (Line Feed)
							lineFinished(1);
							i++;
						} else {
							lineFinished(0);
						}

						lastBufferHadTraillingCR = false;
					}

					for (; i < bytesRead; ++i) {
						if (buffer[i] === 0x0a) { // LF (Line Feed)
							lineFinished(1);
						} else if (buffer[i] === 0x0d) { // CR (Carriage Return)
							if (i + 1 === bytesRead) {
								lastBufferHadTraillingCR = true;
							} else if (buffer[i + 1] === 0x0a) { // LF (Line Feed)
								lineFinished(2);
								i++;
							} else {
								lineFinished(1);
							}
						}
					}

					line += decodeBuffer(buffer, pos, bytesRead);

243
					readFile(/*isFirstRead=*/false, clb); // Continue reading
R
roblou 已提交
244
				});
R
roblou 已提交
245
			};
R
roblou 已提交
246

247
			readFile(/*isFirstRead=*/true, (error: Error) => {
R
roblou 已提交
248
				if (error) {
249
					return reject(error);
R
roblou 已提交
250 251 252 253 254 255 256
				}

				if (line.length) {
					perLineCallback(line, lineNumber); // handle last line
				}

				fs.close(fd, (error: Error) => {
257 258 259 260 261
					if (error) {
						reject(error);
					} else {
						resolve(null);
					}
R
roblou 已提交
262 263 264
				});
			});
		});
265
	});
R
roblou 已提交
266 267 268
}

export class FileMatch implements ISerializedFileMatch {
R
roblou 已提交
269 270
	path: string;
	lineMatches: LineMatch[];
R
roblou 已提交
271 272 273 274 275 276

	constructor(path: string) {
		this.path = path;
		this.lineMatches = [];
	}

R
roblou 已提交
277
	addMatch(lineMatch: LineMatch): void {
R
roblou 已提交
278 279 280
		this.lineMatches.push(lineMatch);
	}

R
roblou 已提交
281
	isEmpty(): boolean {
R
roblou 已提交
282 283 284
		return this.lineMatches.length === 0;
	}

R
roblou 已提交
285
	serialize(): ISerializedFileMatch {
R
roblou 已提交
286
		let lineMatches: ILineMatch[] = [];
287
		let numMatches = 0;
R
roblou 已提交
288 289

		for (let i = 0; i < this.lineMatches.length; i++) {
290
			numMatches += this.lineMatches[i].offsetAndLengths.length;
R
roblou 已提交
291 292 293 294 295
			lineMatches.push(this.lineMatches[i].serialize());
		}

		return {
			path: this.path,
296 297
			lineMatches,
			numMatches
R
roblou 已提交
298 299 300 301 302
		};
	}
}

export class LineMatch implements ILineMatch {
R
roblou 已提交
303 304 305
	preview: string;
	lineNumber: number;
	offsetAndLengths: number[][];
R
roblou 已提交
306 307 308 309 310 311 312

	constructor(preview: string, lineNumber: number) {
		this.preview = preview.replace(/(\r|\n)*$/, '');
		this.lineNumber = lineNumber;
		this.offsetAndLengths = [];
	}

R
roblou 已提交
313
	getText(): string {
R
roblou 已提交
314 315 316
		return this.preview;
	}

R
roblou 已提交
317
	getLineNumber(): number {
R
roblou 已提交
318 319 320
		return this.lineNumber;
	}

R
roblou 已提交
321
	addMatch(offset: number, length: number): void {
R
roblou 已提交
322 323 324
		this.offsetAndLengths.push([offset, length]);
	}

R
roblou 已提交
325
	serialize(): ILineMatch {
R
roblou 已提交
326 327 328 329 330 331 332 333 334
		let result = {
			preview: this.preview,
			lineNumber: this.lineNumber,
			offsetAndLengths: this.offsetAndLengths
		};

		return result;
	}
}