extHostSearch.ts 34.3 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;

R
Rob Lourens 已提交
382 383 384 385 386 387
		return new PPromise<{ isLimitHit: boolean }, IInternalFileMatch>((resolve, reject, onResult) => {
			// 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 });
				}
388

R
Rob Lourens 已提交
389 390 391 392 393 394 395
				// Report result from file pattern if matching
				if (exists) {
					this.resultCount++;
					onResult({
						relativePath: this.filePattern,
						basename: path.basename(this.filePattern),
						size
396
					});
397

R
Rob Lourens 已提交
398 399 400 401
					// 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 });
402 403
				}

R
Rob Lourens 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416
				// 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 });
						});
417 418
				}

R
Rob Lourens 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
				// 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));
				});
			});
		});
	}
434

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

R
Rob Lourens 已提交
443
			const onProviderResult = (result: URI) => {
444 445 446 447
				if (this.isCanceled) {
					return;
				}

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

R
Rob Lourens 已提交
452 453 454 455
				if (noSiblingsClauses) {
					if (relativePath === this.filePattern) {
						filePatternSeen = true;
					}
456

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

R
Rob Lourens 已提交
460 461 462 463 464 465 466 467 468 469 470 471
					// if (this.isLimitHit) {
					// 	killCmd();
					// 	break;
					// }

					return;
				}

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

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

R
Rob Lourens 已提交
485 486 487 488 489 490 491 492 493 494
					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) {
									this.resultCount++;
									onResult({
										base: folderStr,
										relativePath: this.filePattern,
										basename: path.basename(this.filePattern),
495 496
									});
								}
R
Rob Lourens 已提交
497 498 499
							});
						}
					}
500

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

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

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

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

537
	private addDirectoryEntries({ pathToEntries }: IDirectoryTree, base: string, relativeFile: string, onResult: (result: IInternalFileMatch) => void) {
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
		// 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);
	}

562
	private matchDirectoryTree({ rootEntries, pathToEntries }: IDirectoryTree, rootFolder: string, onResult: (result: IInternalFileMatch) => void) {
563 564 565 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
		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 已提交
616 617 618 619 620
	/**
	 * 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 }> {
621
		if (!this.filePattern || !path.isAbsolute(this.filePattern)) {
R
Rob Lourens 已提交
622
			return TPromise.wrap({ exists: false });
623 624
		}

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

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

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

656
	private matchFile(onResult: (result: IInternalFileMatch) => void, candidate: IInternalFileMatch): void {
657 658 659 660 661 662 663 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
		if (this.isFilePatternMatch(candidate.relativePath) && (!this.includePattern || this.includePattern(candidate.relativePath, candidate.basename))) {
			this.resultCount++;

			if (this.exists || (this.maxResults && this.resultCount > this.maxResults)) {
				this.isLimitHit = true;
			}

			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;

694 695
	private _hasSiblingClauses = false;

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
	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];
				}
716 717 718 719

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

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

726 727 728 729
	public hasSiblingClauses(): boolean {
		return this._hasSiblingClauses;
	}

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

762 763 764 765 766
interface ISearchComplete {
	limitHit: boolean;
	stats?: any;
}

R
Rob Lourens 已提交
767
class FileSearchManager {
768 769 770 771 772

	private static readonly BATCH_SIZE = 512;

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

773 774 775
	constructor(private _pfs: typeof pfs) {
	}

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

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

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

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

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

R
Rob Lourens 已提交
826
	private doSortedSearch(engine: FileSearchEngine, provider: vscode.SearchProvider, config: IRawSearchQuery): PPromise<[ISearchComplete, IInternalFileMatch[]]> {
827 828 829
		let searchPromise: PPromise<void, OneOrMore<IInternalFileMatch>>;
		let allResultsPromise = new PPromise<[ISearchComplete, IInternalFileMatch[]], OneOrMore<IInternalFileMatch>>((c, e, p) => {
			let results: IInternalFileMatch[] = [];
R
Rob Lourens 已提交
830
			searchPromise = this.doSearch(engine, provider, -1)
831 832 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
				.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>;
863
		return new PPromise<[ISearchComplete, IInternalFileMatch[]]>((c, e, p) => {
864 865 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
			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();
	}

893
	private trySortedSearchFromCache(config: IRawSearchQuery): TPromise<[ISearchComplete, IInternalFileMatch[]]> {
894 895 896 897 898 899 900 901 902
		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>;
903
			return new TPromise<[ISearchComplete, IInternalFileMatch[]]>((c, e) => {
904 905 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
				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;
	}

941
	private sortResults(config: IRawSearchQuery, results: IInternalFileMatch[], scorerCache: ScorerCache): TPromise<IInternalFileMatch[]> {
942 943 944 945 946
		// 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);
947
		const compare = (matchA: IInternalFileMatch, matchB: IInternalFileMatch) => compareItemsByScore(matchA, matchB, query, true, FileMatchItemAccessor, scorerCache);
948 949 950 951

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

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

962
	private getResultsFromCache(cache: Cache, searchValue: string): PPromise<[ISearchComplete, IInternalFileMatch[], CacheStats]> {
963 964 965 966 967 968
		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;
969
		let cached: PPromise<[ISearchComplete, IInternalFileMatch[]], OneOrMore<IInternalFileMatch>>;
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
		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;
		}

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

				// Pattern match on results
996
				let results: IInternalFileMatch[] = [];
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
				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 已提交
1020
	private doSearch(engine: FileSearchEngine, provider: vscode.SearchProvider, batchSize?: number): PPromise<ISearchComplete, OneOrMore<IInternalFileMatch>> {
1021 1022
		return new PPromise<ISearchComplete, OneOrMore<IInternalFileMatch>>((c, e, p) => {
			let batch: IInternalFileMatch[] = [];
R
Rob Lourens 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
			engine.search().then(() => {
				if (batch.length) {
					p(batch);
				}

				c({
					limitHit: false,
					stats: engine.getStats()
				});
			}, error => {
				if (batch.length) {
					p(batch);
				}

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

	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 {

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

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

1080
const FileMatchItemAccessor = new class implements IItemAccessor<IInternalFileMatch> {
1081

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

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

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

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