extHostSearch.ts 34.4 KB
Newer Older
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 * as pfs from 'vs/base/node/pfs';
8 9
import * as path from 'path';
import * as arrays from 'vs/base/common/arrays';
10
import { asWinJsPromise } from 'vs/base/common/async';
11 12 13 14 15 16 17
import { toErrorMessage } from 'vs/base/common/errorMessage';
import * as glob from 'vs/base/common/glob';
import { isEqualOrParent } from 'vs/base/common/paths';
import * as strings from 'vs/base/common/strings';
import URI, { UriComponents } from 'vs/base/common/uri';
import { PPromise, TPromise } from 'vs/base/common/winjs.base';
import { IItemAccessor, ScorerCache, compareItemsByScore, prepareQuery } from 'vs/base/parts/quickopen/common/quickOpenScorer';
18
import { ICachedSearchStats, IFileMatch, IFolderQuery, IPatternInfo, IRawSearchQuery, ISearchQuery } from 'vs/platform/search/common/search';
19 20
import * as vscode from 'vscode';
import { ExtHostSearchShape, IMainContext, MainContext, MainThreadSearchShape } from './extHost.protocol';
R
Rob Lourens 已提交
21
import { CancellationTokenSource } from 'vs/base/common/cancellation';
22

23 24
type OneOrMore<T> = T | T[];

A
Alex Dima 已提交
25 26 27 28
export interface ISchemeTransformer {
	transformOutgoing(scheme: string): string;
}

29 30 31 32 33 34
export class ExtHostSearch implements ExtHostSearchShape {

	private readonly _proxy: MainThreadSearchShape;
	private readonly _searchProvider = new Map<number, vscode.SearchProvider>();
	private _handlePool: number = 0;

35
	private _fileSearchManager: FileSearchManager;
36

37
	constructor(mainContext: IMainContext, private _schemeTransformer: ISchemeTransformer, private _pfs = pfs) {
38
		this._proxy = mainContext.getProxy(MainContext.MainThreadSearch);
39
		this._fileSearchManager = new FileSearchManager(this._pfs);
40 41
	}

A
Alex Dima 已提交
42 43 44 45 46 47 48
	private _transformScheme(scheme: string): string {
		if (this._schemeTransformer) {
			return this._schemeTransformer.transformOutgoing(scheme);
		}
		return scheme;
	}

49 50 51
	registerSearchProvider(scheme: string, provider: vscode.SearchProvider) {
		const handle = this._handlePool++;
		this._searchProvider.set(handle, provider);
A
Alex Dima 已提交
52
		this._proxy.$registerSearchProvider(handle, this._transformScheme(scheme));
53 54 55 56 57 58 59 60
		return {
			dispose: () => {
				this._searchProvider.delete(handle);
				this._proxy.$unregisterProvider(handle);
			}
		};
	}

61 62 63 64 65 66 67
	$provideFileSearchResults(handle: number, session: number, rawQuery: IRawSearchQuery): TPromise<void> {
		const provider = this._searchProvider.get(handle);
		if (!provider.provideFileSearchResults) {
			return TPromise.as(undefined);
		}

		const query = reviveQuery(rawQuery);
R
Rob Lourens 已提交
68
		return this._fileSearchManager.fileSearch(query, provider).then(
69 70 71 72 73
			() => { }, // still need to return limitHit
			null,
			progress => {
				if (Array.isArray(progress)) {
					progress.forEach(p => {
74
						this._proxy.$handleFindMatch(handle, session, p.resource);
75 76
					});
				} else {
77
					this._proxy.$handleFindMatch(handle, session, progress.resource);
78
				}
79
			});
80 81
	}

82 83 84 85 86 87 88 89 90 91 92
	$provideTextSearchResults(handle: number, session: number, pattern: IPatternInfo, query: IRawSearchQuery): TPromise<void> {
		return TPromise.join(
			query.folderQueries.map(fq => this.provideTextSearchResultsForFolder(handle, session, pattern, query, fq))
		).then(
			() => { },
			(err: Error[]) => {
				return TPromise.wrapError(err[0]);
			});
	}

	private provideTextSearchResultsForFolder(handle: number, session: number, pattern: IPatternInfo, query: IRawSearchQuery, folderQuery: IFolderQuery<UriComponents>): TPromise<void> {
93 94 95 96
		const provider = this._searchProvider.get(handle);
		if (!provider.provideTextSearchResults) {
			return TPromise.as(undefined);
		}
97

98 99
		const includes = resolvePatternsForProvider(query.includePattern, folderQuery.includePattern);
		const excludes = resolvePatternsForProvider(query.excludePattern, folderQuery.excludePattern);
100 101 102 103 104

		const searchOptions: vscode.TextSearchOptions = {
			folder: URI.from(folderQuery.folder),
			excludes,
			includes,
R
Rob Lourens 已提交
105 106
			useIgnoreFiles: !query.disregardIgnoreFiles,
			followSymlinks: !query.ignoreSymlinks,
107 108 109 110
			encoding: query.fileEncoding
		};

		const collector = new TextSearchResultsCollector(handle, session, this._proxy);
111 112
		const progress = {
			report: (data: vscode.TextSearchResult) => {
113
				collector.add(data);
114 115
			}
		};
116 117 118 119 120
		return asWinJsPromise(token => provider.provideTextSearchResults(pattern, searchOptions, progress, token))
			.then(() => collector.flush());
	}
}

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
/**
 * TODO@roblou
 * Discards sibling clauses (for now) and 'false' patterns
 */
function resolvePatternsForProvider(globalPattern: glob.IExpression, folderPattern: glob.IExpression): string[] {
	const merged = {
		...(globalPattern || {}),
		...(folderPattern || {})
	};

	return Object.keys(merged)
		.filter(key => {
			const value = merged[key];
			return typeof value === 'boolean' && value;
		});
}

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
function reviveQuery(rawQuery: IRawSearchQuery): ISearchQuery {
	return {
		...rawQuery,
		...{
			folderQueries: rawQuery.folderQueries && rawQuery.folderQueries.map(reviveFolderQuery),
			extraFileResources: rawQuery.extraFileResources && rawQuery.extraFileResources.map(components => URI.revive(components))
		}
	};
}

function reviveFolderQuery(rawFolderQuery: IFolderQuery<UriComponents>): IFolderQuery<URI> {
	return {
		...rawFolderQuery,
		folder: URI.revive(rawFolderQuery.folder)
	};
}

155
class TextSearchResultsCollector {
156
	private _batchedCollector: BatchedCollector<IFileMatch>;
157 158 159 160

	private _currentFileMatch: IFileMatch;

	constructor(private _handle: number, private _session: number, private _proxy: MainThreadSearchShape) {
161
		this._batchedCollector = new BatchedCollector<IFileMatch>(512, items => this.sendItems(items));
162 163 164
	}

	add(data: vscode.TextSearchResult): void {
165
		// Collects TextSearchResults into IInternalFileMatches and collates using BatchedCollector.
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
		// This is efficient for ripgrep which sends results back one file at a time. It wouldn't be efficient for other search
		// providers that send results in random order. We could do this step afterwards instead.
		if (this._currentFileMatch && this._currentFileMatch.resource.toString() !== data.uri.toString()) {
			this.pushToCollector();
			this._currentFileMatch = null;
		}

		if (!this._currentFileMatch) {
			this._currentFileMatch = {
				resource: data.uri,
				lineMatches: []
			};
		}

		// TODO@roblou - line text is sent for every match
R
Rob Lourens 已提交
181
		const matchRange = data.preview.match;
182 183
		this._currentFileMatch.lineMatches.push({
			lineNumber: data.range.start.line,
R
Rob Lourens 已提交
184 185
			preview: data.preview.text,
			offsetAndLengths: [[matchRange.start.character, matchRange.end.character - matchRange.start.character]]
186 187 188 189
		});
	}

	private pushToCollector(): void {
190 191 192
		const size = this._currentFileMatch ?
			this._currentFileMatch.lineMatches.reduce((acc, match) => acc + match.offsetAndLengths.length, 0) :
			0;
193 194 195 196 197 198 199 200
		this._batchedCollector.addItem(this._currentFileMatch, size);
	}

	flush(): void {
		this.pushToCollector();
		this._batchedCollector.flush();
	}

201
	private sendItems(items: IFileMatch | IFileMatch[]): void {
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 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
		items = Array.isArray(items) ? items : [items];
		this._proxy.$handleFindMatch(this._handle, this._session, items);
	}
}

/**
 * Collects items that have a size - before the cumulative size of collected items reaches START_BATCH_AFTER_COUNT, the callback is called for every
 * set of items collected.
 * But after that point, the callback is called with batches of maxBatchSize.
 * If the batch isn't filled within some time, the callback is also called.
 */
class BatchedCollector<T> {
	private static readonly TIMEOUT = 4000;

	// After START_BATCH_AFTER_COUNT items have been collected, stop flushing on timeout
	private static readonly START_BATCH_AFTER_COUNT = 50;

	private totalNumberCompleted = 0;
	private batch: T[] = [];
	private batchSize = 0;
	private timeoutHandle: number;

	constructor(private maxBatchSize: number, private cb: (items: T | T[]) => void) {
	}

	addItem(item: T, size: number): void {
		if (!item) {
			return;
		}

		if (this.maxBatchSize > 0) {
			this.addItemToBatch(item, size);
		} else {
			this.cb(item);
		}
	}

	addItems(items: T[], size: number): void {
		if (!items) {
			return;
		}

		if (this.maxBatchSize > 0) {
			this.addItemsToBatch(items, size);
		} else {
			this.cb(items);
		}
	}

	private addItemToBatch(item: T, size: number): void {
		this.batch.push(item);
		this.batchSize += size;
		this.onUpdate();
	}

	private addItemsToBatch(item: T[], size: number): void {
		this.batch = this.batch.concat(item);
		this.batchSize += size;
		this.onUpdate();
	}

	private onUpdate(): void {
		if (this.totalNumberCompleted < BatchedCollector.START_BATCH_AFTER_COUNT) {
			// Flush because we aren't batching yet
			this.flush();
		} else if (this.batchSize >= this.maxBatchSize) {
			// Flush because the batch is full
			this.flush();
		} else if (!this.timeoutHandle) {
			// No timeout running, start a timeout to flush
			this.timeoutHandle = setTimeout(() => {
				this.flush();
			}, BatchedCollector.TIMEOUT);
		}
	}

	flush(): void {
		if (this.batchSize) {
			this.totalNumberCompleted += this.batchSize;
			this.cb(this.batch);
			this.batch = [];
			this.batchSize = 0;

			if (this.timeoutHandle) {
				clearTimeout(this.timeoutHandle);
				this.timeoutHandle = 0;
			}
		}
290 291
	}
}
292 293 294 295 296 297 298 299 300 301 302 303

interface IDirectoryEntry {
	base: string;
	relativePath: string;
	basename: string;
}

interface IDirectoryTree {
	rootEntries: IDirectoryEntry[];
	pathToEntries: { [relativePath: string]: IDirectoryEntry[] };
}

304 305 306 307 308 309 310
interface IInternalFileMatch {
	base?: string;
	relativePath: string; // Not necessarily relative... extraFiles put an absolute path here. Rename.
	basename: string;
	size?: number;
}

R
Rob Lourens 已提交
311
class FileSearchEngine {
312 313 314 315 316 317 318 319 320 321
	private filePattern: string;
	private normalizedFilePatternLowercase: string;
	private includePattern: glob.ParsedExpression;
	private maxResults: number;
	private exists: boolean;
	// private maxFilesize: number;
	private isLimitHit: boolean;
	private resultCount: number;
	private isCanceled: boolean;

322 323
	private activeCancellationTokens: Set<CancellationTokenSource>;

324 325 326 327 328 329
	// private filesWalked: number;
	// private directoriesWalked: number;

	private folderExcludePatterns: Map<string, AbsoluteAndRelativeParsedExpression>;
	private globalExcludePattern: glob.ParsedExpression;

330
	constructor(private config: ISearchQuery, private provider: vscode.SearchProvider, private _pfs: typeof pfs) {
331 332 333 334 335 336 337
		this.filePattern = config.filePattern;
		this.includePattern = config.includePattern && glob.parse(config.includePattern);
		this.maxResults = config.maxResults || null;
		this.exists = config.exists;
		// this.maxFilesize = config.maxFileSize || null;
		this.resultCount = 0;
		this.isLimitHit = false;
338
		this.activeCancellationTokens = new Set<CancellationTokenSource>();
339 340 341 342 343 344 345 346 347 348 349 350 351

		// this.filesWalked = 0;
		// this.directoriesWalked = 0;

		if (this.filePattern) {
			this.normalizedFilePatternLowercase = strings.stripWildcards(this.filePattern).toLowerCase();
		}

		this.globalExcludePattern = config.excludePattern && glob.parse(config.excludePattern);
		this.folderExcludePatterns = new Map<string, AbsoluteAndRelativeParsedExpression>();

		config.folderQueries.forEach(folderQuery => {
			const folderExcludeExpression: glob.IExpression = {
352 353
				...(this.config.excludePattern || {}),
				...(folderQuery.excludePattern || {})
354 355 356
			};

			// Add excludes for other root folders
357
			const folderString = URI.from(folderQuery.folder).fsPath;
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
			config.folderQueries
				.map(rootFolderQuery => rootFolderQuery.folder)
				.filter(rootFolder => rootFolder !== folderQuery.folder)
				.forEach(otherRootFolder => {
					// Exclude nested root folders
					const otherString = URI.from(otherRootFolder).toString();
					if (isEqualOrParent(otherString, folderString)) {
						folderExcludeExpression[path.relative(folderString, otherString)] = true;
					}
				});

			this.folderExcludePatterns.set(folderString, new AbsoluteAndRelativeParsedExpression(folderExcludeExpression, folderString));
		});
	}

	public cancel(): void {
		this.isCanceled = true;
375 376
		this.activeCancellationTokens.forEach(t => t.cancel());
		this.activeCancellationTokens = new Set();
377 378
	}

R
Rob Lourens 已提交
379
	public search(): PPromise<{ isLimitHit: boolean }, IInternalFileMatch> {
380 381
		const folderQueries = this.config.folderQueries;

382 383 384 385 386 387
		return new PPromise<{ isLimitHit: boolean }, IInternalFileMatch>((resolve, reject, _onResult) => {
			const onResult = (match: IInternalFileMatch) => {
				this.resultCount++;
				_onResult(match);
			};

R
Rob Lourens 已提交
388 389 390 391 392
			// Support that the file pattern is a full path to a file that exists
			this.checkFilePatternAbsoluteMatch().then(({ exists, size }) => {
				if (this.isCanceled) {
					return resolve({ isLimitHit: this.isLimitHit });
				}
393

R
Rob Lourens 已提交
394 395 396 397 398 399
				// Report result from file pattern if matching
				if (exists) {
					onResult({
						relativePath: this.filePattern,
						basename: path.basename(this.filePattern),
						size
400
					});
401

R
Rob Lourens 已提交
402 403 404 405
					// Optimization: a match on an absolute path is a good result and we do not
					// continue walking the entire root paths array for other matches because
					// it is very unlikely that another file would match on the full absolute path
					return resolve({ isLimitHit: this.isLimitHit });
406 407
				}

R
Rob Lourens 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420
				// For each extra file
				if (this.config.extraFileResources) {
					this.config.extraFileResources
						.map(uri => uri.toString())
						.forEach(extraFilePath => {
							const basename = path.basename(extraFilePath);
							if (this.globalExcludePattern && this.globalExcludePattern(extraFilePath, basename)) {
								return; // excluded
							}

							// File: Check for match on file pattern and include pattern
							this.matchFile(onResult, { relativePath: extraFilePath /* no workspace relative path */, basename });
						});
421 422
				}

R
Rob Lourens 已提交
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
				// For each root folder
				PPromise.join(folderQueries.map(fq => {
					return this.searchInFolder(fq).then(null, null, onResult);
				})).then(() => {
					resolve({ isLimitHit: false });
				}, (errs: Error[]) => {
					const errMsg = errs
						.map(err => toErrorMessage(err))
						.filter(msg => !!msg)[0];

					reject(new Error(errMsg));
				});
			});
		});
	}
438

R
Rob Lourens 已提交
439 440 441 442
	private searchInFolder(fq: IFolderQuery<URI>): PPromise<void, IInternalFileMatch> {
		let cancellation = new CancellationTokenSource();
		return new PPromise((resolve, reject, onResult) => {
			const options = this.getSearchOptionsForFolder(fq);
443
			const folderStr = fq.folder.fsPath;
R
Rob Lourens 已提交
444 445
			let filePatternSeen = false;
			const tree = this.initDirectoryTree();
446

R
Rob Lourens 已提交
447
			const onProviderResult = (result: URI) => {
448 449 450 451
				if (this.isCanceled) {
					return;
				}

R
Rob Lourens 已提交
452 453
				// TODO@roblou - What if it is not relative to the folder query.
				// This is slow...
454
				const relativePath = path.relative(folderStr, result.fsPath);
455

R
Rob Lourens 已提交
456 457 458 459
				if (noSiblingsClauses) {
					if (relativePath === this.filePattern) {
						filePatternSeen = true;
					}
460

R
Rob Lourens 已提交
461 462
					const basename = path.basename(relativePath);
					this.matchFile(onResult, { base: folderStr, relativePath, basename });
463

R
Rob Lourens 已提交
464 465 466 467 468 469 470 471 472 473 474 475
					// if (this.isLimitHit) {
					// 	killCmd();
					// 	break;
					// }

					return;
				}

				// TODO: Optimize siblings clauses with ripgrep here.
				this.addDirectoryEntries(tree, folderStr, relativePath, onResult);
			};

476 477
			const allFolderExcludes = this.folderExcludePatterns.get(fq.folder.fsPath);
			const noSiblingsClauses = !allFolderExcludes || !allFolderExcludes.hasSiblingClauses();
478 479 480 481 482
			new TPromise(resolve => process.nextTick(resolve))
				.then(() => {
					this.activeCancellationTokens.add(cancellation);
					return this.provider.provideFileSearchResults(options, { report: onProviderResult }, cancellation.token);
				})
R
Rob Lourens 已提交
483
				.then(() => {
484 485 486 487 488
					this.activeCancellationTokens.delete(cancellation);
					if (this.isCanceled) {
						return null;
					}

R
Rob Lourens 已提交
489 490 491 492 493 494 495 496 497
					if (noSiblingsClauses && this.isLimitHit) {
						if (!filePatternSeen) {
							// If the limit was hit, check whether filePattern is an exact relative match because it must be included
							return this.checkFilePatternRelativeMatch(folderStr).then(({ exists, size }) => {
								if (exists) {
									onResult({
										base: folderStr,
										relativePath: this.filePattern,
										basename: path.basename(this.filePattern),
498 499
									});
								}
R
Rob Lourens 已提交
500 501 502
							});
						}
					}
503

R
Rob Lourens 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516
					this.matchDirectoryTree(tree, folderStr, onResult);
					return null;
				}).then(
					() => {
						cancellation.dispose();
						resolve(undefined);
					},
					err => {
						cancellation.dispose();
						reject(err);
					});
		});
	}
517

R
Rob Lourens 已提交
518
	private getSearchOptionsForFolder(fq: IFolderQuery<URI>): vscode.FileSearchOptions {
519 520
		const includes = resolvePatternsForProvider(this.config.includePattern, fq.includePattern);
		const excludes = resolvePatternsForProvider(this.config.excludePattern, fq.excludePattern);
521

R
Rob Lourens 已提交
522 523 524 525 526 527 528
		return {
			folder: fq.folder,
			excludes,
			includes,
			useIgnoreFiles: !this.config.disregardIgnoreFiles,
			followSymlinks: !this.config.ignoreSymlinks
		};
529 530 531 532 533 534 535 536 537 538 539
	}

	private initDirectoryTree(): IDirectoryTree {
		const tree: IDirectoryTree = {
			rootEntries: [],
			pathToEntries: Object.create(null)
		};
		tree.pathToEntries['.'] = tree.rootEntries;
		return tree;
	}

540
	private addDirectoryEntries({ pathToEntries }: IDirectoryTree, base: string, relativeFile: string, onResult: (result: IInternalFileMatch) => void) {
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
		// Support relative paths to files from a root resource (ignores excludes)
		if (relativeFile === this.filePattern) {
			const basename = path.basename(this.filePattern);
			this.matchFile(onResult, { base: base, relativePath: this.filePattern, basename });
		}

		function add(relativePath: string) {
			const basename = path.basename(relativePath);
			const dirname = path.dirname(relativePath);
			let entries = pathToEntries[dirname];
			if (!entries) {
				entries = pathToEntries[dirname] = [];
				add(dirname);
			}
			entries.push({
				base,
				relativePath,
				basename
			});
		}

		add(relativeFile);
	}

565
	private matchDirectoryTree({ rootEntries, pathToEntries }: IDirectoryTree, rootFolder: string, onResult: (result: IInternalFileMatch) => void) {
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
		const self = this;
		const excludePattern = this.folderExcludePatterns.get(rootFolder);
		const filePattern = this.filePattern;
		function matchDirectory(entries: IDirectoryEntry[]) {
			// self.directoriesWalked++;
			for (let i = 0, n = entries.length; i < n; i++) {
				const entry = entries[i];
				const { relativePath, basename } = entry;

				// Check exclude pattern
				// If the user searches for the exact file name, we adjust the glob matching
				// to ignore filtering by siblings because the user seems to know what she
				// is searching for and we want to include the result in that case anyway
				if (excludePattern.test(relativePath, basename, () => filePattern !== basename ? entries.map(entry => entry.basename) : [])) {
					continue;
				}

				const sub = pathToEntries[relativePath];
				if (sub) {
					matchDirectory(sub);
				} else {
					// self.filesWalked++;
					if (relativePath === filePattern) {
						continue; // ignore file if its path matches with the file pattern because that is already matched above
					}

					self.matchFile(onResult, entry);
				}

				if (self.isLimitHit) {
					break;
				}
			}
		}
		matchDirectory(rootEntries);
	}

	public getStats(): any {
		return null;
		// return {
		// 	fromCache: false,
		// 	traversal: Traversal[this.traversal],
		// 	errors: this.errors,
		// 	fileWalkStartTime: this.fileWalkStartTime,
		// 	fileWalkResultTime: Date.now(),
		// 	directoriesWalked: this.directoriesWalked,
		// 	filesWalked: this.filesWalked,
		// 	resultCount: this.resultCount,
		// 	cmdForkResultTime: this.cmdForkResultTime,
		// 	cmdResultCount: this.cmdResultCount
		// };
	}

R
Rob Lourens 已提交
619 620 621 622 623
	/**
	 * Return whether the file pattern is an absolute path to a file that exists.
	 * TODO@roblou should use FS provider?
	 */
	private checkFilePatternAbsoluteMatch(): TPromise<{ exists: boolean, size?: number }> {
624
		if (!this.filePattern || !path.isAbsolute(this.filePattern)) {
R
Rob Lourens 已提交
625
			return TPromise.wrap({ exists: false });
626 627
		}

628
		return this._pfs.stat(this.filePattern)
R
Rob Lourens 已提交
629 630 631 632 633 634 635 636 637 638
			.then(stat => {
				return {
					exists: !stat.isDirectory(),
					size: stat.size
				};
			}, err => {
				return {
					exists: false
				};
			});
639 640
	}

R
Rob Lourens 已提交
641
	private checkFilePatternRelativeMatch(basePath: string): TPromise<{ exists: boolean, size?: number }> {
642
		if (!this.filePattern || path.isAbsolute(this.filePattern)) {
R
Rob Lourens 已提交
643
			return TPromise.wrap({ exists: false });
644 645 646
		}

		const absolutePath = path.join(basePath, this.filePattern);
647
		return this._pfs.stat(absolutePath).then(stat => {
R
Rob Lourens 已提交
648 649 650 651 652 653 654 655
			return {
				exists: !stat.isDirectory(),
				size: stat.size
			};
		}, err => {
			return {
				exists: false
			};
656 657 658
		});
	}

659
	private matchFile(onResult: (result: IInternalFileMatch) => void, candidate: IInternalFileMatch): void {
660
		if (this.isFilePatternMatch(candidate.relativePath) && (!this.includePattern || this.includePattern(candidate.relativePath, candidate.basename))) {
661
			if (this.exists || (this.maxResults && this.resultCount >= this.maxResults)) {
662
				this.isLimitHit = true;
663
				this.cancel();
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
			}

			if (!this.isLimitHit) {
				onResult(candidate);
			}
		}
	}

	private isFilePatternMatch(path: string): boolean {
		// Check for search pattern
		if (this.filePattern) {
			if (this.filePattern === '*') {
				return true; // support the all-matching wildcard
			}

			return strings.fuzzyContains(path, this.normalizedFilePatternLowercase);
		}

		// No patterns means we match all
		return true;
	}
}

/**
 * This class exists to provide one interface on top of two ParsedExpressions, one for absolute expressions and one for relative expressions.
 * The absolute and relative expressions don't "have" to be kept separate, but this keeps us from having to path.join every single
 * file searched, it's only used for a text search with a searchPath
 */
class AbsoluteAndRelativeParsedExpression {
	private absoluteParsedExpr: glob.ParsedExpression;
	private relativeParsedExpr: glob.ParsedExpression;

696 697
	private _hasSiblingClauses = false;

698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
	constructor(public expression: glob.IExpression, private root: string) {
		this.init(expression);
	}

	/**
	 * Split the IExpression into its absolute and relative components, and glob.parse them separately.
	 */
	private init(expr: glob.IExpression): void {
		let absoluteGlobExpr: glob.IExpression;
		let relativeGlobExpr: glob.IExpression;
		Object.keys(expr)
			.filter(key => expr[key])
			.forEach(key => {
				if (path.isAbsolute(key)) {
					absoluteGlobExpr = absoluteGlobExpr || glob.getEmptyExpression();
					absoluteGlobExpr[key] = expr[key];
				} else {
					relativeGlobExpr = relativeGlobExpr || glob.getEmptyExpression();
					relativeGlobExpr[key] = expr[key];
				}
718 719 720 721

				if (typeof expr[key] !== 'boolean') {
					this._hasSiblingClauses = true;
				}
722 723 724 725 726 727
			});

		this.absoluteParsedExpr = absoluteGlobExpr && glob.parse(absoluteGlobExpr, { trimForExclusions: true });
		this.relativeParsedExpr = relativeGlobExpr && glob.parse(relativeGlobExpr, { trimForExclusions: true });
	}

728 729 730 731
	public hasSiblingClauses(): boolean {
		return this._hasSiblingClauses;
	}

732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
	public test(_path: string, basename?: string, siblingsFn?: () => string[] | TPromise<string[]>): string | TPromise<string> {
		return (this.relativeParsedExpr && this.relativeParsedExpr(_path, basename, siblingsFn)) ||
			(this.absoluteParsedExpr && this.absoluteParsedExpr(path.join(this.root, _path), basename, siblingsFn));
	}

	public getBasenameTerms(): string[] {
		const basenameTerms = [];
		if (this.absoluteParsedExpr) {
			basenameTerms.push(...glob.getBasenameTerms(this.absoluteParsedExpr));
		}

		if (this.relativeParsedExpr) {
			basenameTerms.push(...glob.getBasenameTerms(this.relativeParsedExpr));
		}

		return basenameTerms;
	}

	public getPathTerms(): string[] {
		const pathTerms = [];
		if (this.absoluteParsedExpr) {
			pathTerms.push(...glob.getPathTerms(this.absoluteParsedExpr));
		}

		if (this.relativeParsedExpr) {
			pathTerms.push(...glob.getPathTerms(this.relativeParsedExpr));
		}

		return pathTerms;
	}
}

764 765 766 767 768
interface ISearchComplete {
	limitHit: boolean;
	stats?: any;
}

R
Rob Lourens 已提交
769
class FileSearchManager {
770 771 772 773 774

	private static readonly BATCH_SIZE = 512;

	private caches: { [cacheKey: string]: Cache; } = Object.create(null);

775 776 777
	constructor(private _pfs: typeof pfs) {
	}

778
	public fileSearch(config: ISearchQuery, provider: vscode.SearchProvider): PPromise<ISearchComplete, OneOrMore<IFileMatch>> {
779 780 781
		if (config.sortByScore) {
			let sortedSearch = this.trySortedSearchFromCache(config);
			if (!sortedSearch) {
R
Rob Lourens 已提交
782
				const engineConfig = config.maxResults ?
783 784 785 786 787 788
					{
						...config,
						...{ maxResults: null }
					} :
					config;

789
				const engine = new FileSearchEngine(engineConfig, provider, this._pfs);
R
Rob Lourens 已提交
790
				sortedSearch = this.doSortedSearch(engine, provider, config);
791 792
			}

793
			return new PPromise<ISearchComplete, OneOrMore<IFileMatch>>((c, e, p) => {
794 795 796
				process.nextTick(() => { // allow caller to register progress callback first
					sortedSearch.then(([result, rawMatches]) => {
						const serializedMatches = rawMatches.map(rawMatch => this.rawMatchToSearchItem(rawMatch));
R
Rob Lourens 已提交
797
						this.sendProgress(serializedMatches, p, FileSearchManager.BATCH_SIZE);
798 799 800 801 802 803 804 805
						c(result);
					}, e, p);
				});
			}, () => {
				sortedSearch.cancel();
			});
		}

806 807
		let searchPromise: PPromise<void, OneOrMore<IInternalFileMatch>>;
		return new PPromise<ISearchComplete, OneOrMore<IFileMatch>>((c, e, p) => {
808
			const engine = new FileSearchEngine(config, provider, this._pfs);
R
Rob Lourens 已提交
809
			searchPromise = this.doSearch(engine, provider, FileSearchManager.BATCH_SIZE)
810 811 812
				.then(c, e, progress => {
					if (Array.isArray(progress)) {
						p(progress.map(m => this.rawMatchToSearchItem(m)));
813 814
					} else if ((<IInternalFileMatch>progress).relativePath) {
						p(this.rawMatchToSearchItem(<IInternalFileMatch>progress));
815 816 817 818 819 820 821
					}
				});
		}, () => {
			searchPromise.cancel();
		});
	}

822
	private rawMatchToSearchItem(match: IInternalFileMatch): IFileMatch {
R
Rob Lourens 已提交
823
		return {
824
			resource: URI.file(match.base ? path.join(match.base, match.relativePath) : match.relativePath)
R
Rob Lourens 已提交
825
		};
826 827
	}

R
Rob Lourens 已提交
828
	private doSortedSearch(engine: FileSearchEngine, provider: vscode.SearchProvider, config: IRawSearchQuery): PPromise<[ISearchComplete, IInternalFileMatch[]]> {
829 830 831
		let searchPromise: PPromise<void, OneOrMore<IInternalFileMatch>>;
		let allResultsPromise = new PPromise<[ISearchComplete, IInternalFileMatch[]], OneOrMore<IInternalFileMatch>>((c, e, p) => {
			let results: IInternalFileMatch[] = [];
R
Rob Lourens 已提交
832
			searchPromise = this.doSearch(engine, provider, -1)
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
				.then(result => {
					c([result, results]);
					// TODO@roblou telemetry
					// if (this.telemetryPipe) {
					// 	// __GDPR__TODO__ classify event
					// 	this.telemetryPipe({
					// 		eventName: 'fileSearch',
					// 		data: result.stats
					// 	});
					// }
				}, e, progress => {
					if (Array.isArray(progress)) {
						results = progress;
					} else {
						p(progress);
					}
				});
		}, () => {
			searchPromise.cancel();
		});

		let cache: Cache;
		if (config.cacheKey) {
			cache = this.getOrCreateCache(config.cacheKey);
			cache.resultsToSearchCache[config.filePattern] = allResultsPromise;
			allResultsPromise.then(null, err => {
				delete cache.resultsToSearchCache[config.filePattern];
			});
			allResultsPromise = this.preventCancellation(allResultsPromise);
		}

		let chained: TPromise<void>;
865
		return new PPromise<[ISearchComplete, IInternalFileMatch[]]>((c, e, p) => {
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
			chained = allResultsPromise.then(([result, results]) => {
				const scorerCache: ScorerCache = cache ? cache.scorerCache : Object.create(null);
				const unsortedResultTime = Date.now();
				return this.sortResults(config, results, scorerCache)
					.then(sortedResults => {
						const sortedResultTime = Date.now();

						c([{
							stats: {
								...result.stats,
								...{ unsortedResultTime, sortedResultTime }
							},
							limitHit: result.limitHit || typeof config.maxResults === 'number' && results.length > config.maxResults
						}, sortedResults]);
					});
			}, e, p);
		}, () => {
			chained.cancel();
		});
	}

	private getOrCreateCache(cacheKey: string): Cache {
		const existing = this.caches[cacheKey];
		if (existing) {
			return existing;
		}
		return this.caches[cacheKey] = new Cache();
	}

895
	private trySortedSearchFromCache(config: IRawSearchQuery): TPromise<[ISearchComplete, IInternalFileMatch[]]> {
896 897 898 899 900 901 902 903 904
		const cache = config.cacheKey && this.caches[config.cacheKey];
		if (!cache) {
			return undefined;
		}

		const cacheLookupStartTime = Date.now();
		const cached = this.getResultsFromCache(cache, config.filePattern);
		if (cached) {
			let chained: TPromise<void>;
905
			return new TPromise<[ISearchComplete, IInternalFileMatch[]]>((c, e) => {
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
				chained = cached.then(([result, results, cacheStats]) => {
					const cacheLookupResultTime = Date.now();
					return this.sortResults(config, results, cache.scorerCache)
						.then(sortedResults => {
							const sortedResultTime = Date.now();

							const stats: ICachedSearchStats = {
								fromCache: true,
								cacheLookupStartTime: cacheLookupStartTime,
								cacheFilterStartTime: cacheStats.cacheFilterStartTime,
								cacheLookupResultTime: cacheLookupResultTime,
								cacheEntryCount: cacheStats.cacheFilterResultCount,
								resultCount: results.length
							};
							if (config.sortByScore) {
								stats.unsortedResultTime = cacheLookupResultTime;
								stats.sortedResultTime = sortedResultTime;
							}
							if (!cacheStats.cacheWasResolved) {
								stats.joined = result.stats;
							}
							c([
								{
									limitHit: result.limitHit || typeof config.maxResults === 'number' && results.length > config.maxResults,
									stats: stats
								},
								sortedResults
							]);
						});
				}, e);
			}, () => {
				chained.cancel();
			});
		}
		return undefined;
	}

943
	private sortResults(config: IRawSearchQuery, results: IInternalFileMatch[], scorerCache: ScorerCache): TPromise<IInternalFileMatch[]> {
944 945 946 947 948
		// we use the same compare function that is used later when showing the results using fuzzy scoring
		// this is very important because we are also limiting the number of results by config.maxResults
		// and as such we want the top items to be included in this result set if the number of items
		// exceeds config.maxResults.
		const query = prepareQuery(config.filePattern);
949
		const compare = (matchA: IInternalFileMatch, matchB: IInternalFileMatch) => compareItemsByScore(matchA, matchB, query, true, FileMatchItemAccessor, scorerCache);
950 951 952 953

		return arrays.topAsync(results, compare, config.maxResults, 10000);
	}

954
	private sendProgress(results: IFileMatch[], progressCb: (batch: IFileMatch[]) => void, batchSize: number) {
955 956 957 958 959 960 961 962 963
		if (batchSize && batchSize > 0) {
			for (let i = 0; i < results.length; i += batchSize) {
				progressCb(results.slice(i, i + batchSize));
			}
		} else {
			progressCb(results);
		}
	}

964
	private getResultsFromCache(cache: Cache, searchValue: string): PPromise<[ISearchComplete, IInternalFileMatch[], CacheStats]> {
965 966 967 968 969 970
		if (path.isAbsolute(searchValue)) {
			return null; // bypass cache if user looks up an absolute path where matching goes directly on disk
		}

		// Find cache entries by prefix of search value
		const hasPathSep = searchValue.indexOf(path.sep) >= 0;
971
		let cached: PPromise<[ISearchComplete, IInternalFileMatch[]], OneOrMore<IInternalFileMatch>>;
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
		let wasResolved: boolean;
		for (let previousSearch in cache.resultsToSearchCache) {

			// If we narrow down, we might be able to reuse the cached results
			if (strings.startsWith(searchValue, previousSearch)) {
				if (hasPathSep && previousSearch.indexOf(path.sep) < 0) {
					continue; // since a path character widens the search for potential more matches, require it in previous search too
				}

				const c = cache.resultsToSearchCache[previousSearch];
				c.then(() => { wasResolved = false; });
				wasResolved = true;
				cached = this.preventCancellation(c);
				break;
			}
		}

		if (!cached) {
			return null;
		}

993
		return new PPromise<[ISearchComplete, IInternalFileMatch[], CacheStats]>((c, e, p) => {
994 995 996 997
			cached.then(([complete, cachedEntries]) => {
				const cacheFilterStartTime = Date.now();

				// Pattern match on results
998
				let results: IInternalFileMatch[] = [];
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
				const normalizedSearchValueLowercase = strings.stripWildcards(searchValue).toLowerCase();
				for (let i = 0; i < cachedEntries.length; i++) {
					let entry = cachedEntries[i];

					// Check if this entry is a match for the search value
					if (!strings.fuzzyContains(entry.relativePath, normalizedSearchValueLowercase)) {
						continue;
					}

					results.push(entry);
				}

				c([complete, results, {
					cacheWasResolved: wasResolved,
					cacheFilterStartTime: cacheFilterStartTime,
					cacheFilterResultCount: cachedEntries.length
				}]);
			}, e, p);
		}, () => {
			cached.cancel();
		});
	}

R
Rob Lourens 已提交
1022
	private doSearch(engine: FileSearchEngine, provider: vscode.SearchProvider, batchSize?: number): PPromise<ISearchComplete, OneOrMore<IInternalFileMatch>> {
1023 1024
		return new PPromise<ISearchComplete, OneOrMore<IInternalFileMatch>>((c, e, p) => {
			let batch: IInternalFileMatch[] = [];
1025
			engine.search().then(result => {
R
Rob Lourens 已提交
1026 1027 1028 1029 1030
				if (batch.length) {
					p(batch);
				}

				c({
1031 1032
					limitHit: result.isLimitHit,
					stats: engine.getStats() // TODO@roblou
R
Rob Lourens 已提交
1033 1034 1035 1036 1037 1038 1039 1040
				});
			}, error => {
				if (batch.length) {
					p(batch);
				}

				e(error);
			}, match => {
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
				if (match) {
					if (batchSize) {
						batch.push(match);
						if (batchSize > 0 && batch.length >= batchSize) {
							p(batch);
							batch = [];
						}
					} else {
						p(match);
					}
				}
R
Rob Lourens 已提交
1052
			});
1053
		}, () => {
R
Rob Lourens 已提交
1054
			engine.cancel();
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
		});
	}

	public clearCache(cacheKey: string): TPromise<void> {
		delete this.caches[cacheKey];
		return TPromise.as(undefined);
	}

	private preventCancellation<C, P>(promise: PPromise<C, P>): PPromise<C, P> {
		return new PPromise<C, P>((c, e, p) => {
			// Allow for piled up cancellations to come through first.
			process.nextTick(() => {
				promise.then(c, e, p);
			});
		}, () => {
			// Do not propagate.
		});
	}
}

class Cache {

1077
	public resultsToSearchCache: { [searchValue: string]: PPromise<[ISearchComplete, IInternalFileMatch[]], OneOrMore<IInternalFileMatch>>; } = Object.create(null);
1078 1079 1080 1081

	public scorerCache: ScorerCache = Object.create(null);
}

1082
const FileMatchItemAccessor = new class implements IItemAccessor<IInternalFileMatch> {
1083

1084
	public getItemLabel(match: IInternalFileMatch): string {
1085 1086 1087
		return match.basename; // e.g. myFile.txt
	}

1088
	public getItemDescription(match: IInternalFileMatch): string {
1089 1090 1091
		return match.relativePath.substr(0, match.relativePath.length - match.basename.length - 1); // e.g. some/path/to/file
	}

1092
	public getItemPath(match: IInternalFileMatch): string {
1093 1094 1095 1096 1097 1098 1099 1100
		return match.relativePath; // e.g. some/path/to/file/myFile.txt
	}
};

interface CacheStats {
	cacheWasResolved: boolean;
	cacheFilterStartTime: number;
	cacheFilterResultCount: number;
1101
}