src/vs/workbench/services/search/common/fileSearchManager.ts
429 LOC · 385 covered · 44 uncovered · 85 ranges · 60 concepts · 17 introducers · 32 tests
File neighbourhood
The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.
Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file
In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.
Graph controls are ready.
Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.
/*---------------------------------------------------------------------------------------------
fileSearch.ts ×31
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from '../../../../base/common/path.js';
import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js';
import { toErrorMessage } from '../../../../base/common/errorMessage.js';
import * as strings from '../../../../base/common/strings.js';
import * as glob from '../../../../base/common/glob.js';
import * as resources from '../../../../base/common/resources.js';
import { StopWatch } from '../../../../base/common/stopwatch.js';
import { URI } from '../../../../base/common/uri.js';
import { IFileMatch, IFileSearchProviderStats, IFolderQuery, ISearchCompleteStats, IFileQuery, QueryGlobTester, resolvePatternsForProvider, hasSiblingFn, excludeToGlobPattern, DEFAULT_MAX_SEARCH_RESULTS } from './search.js';
import { FileSearchProviderFolderOptions, FileSearchProvider2, FileSearchProviderOptions } from './searchExtTypes.js';
import { OldFileSearchProviderConverter } from './searchExtConversionTypes.js';
import { FolderQuerySearchTree } from './folderQuerySearchTree.js';
interface IInternalFileMatch {
base: URI;
original?: URI;
relativePath?: string; // Not present for extraFiles or absolute path matches
basename: string;
size?: number;
}
interface IDirectoryEntry {
base: URI;
relativePath: string;
basename: string;
}
interface FolderQueryInfo {
queryTester: QueryGlobTester;
noSiblingsClauses: boolean;
folder: URI;
tree: IDirectoryTree;
}
interface IDirectoryTree {
rootEntries: IDirectoryEntry[];
pathToEntries: { [relativePath: string]: IDirectoryEntry[] };
}
class FileSearchEngine {
private filePattern?: string;
private includePattern?: glob.ParsedExpression;
private maxResults?: number;
private exists?: boolean;
private isLimitHit = false;
private resultCount = 0;
private isCanceled = false;
private activeCancellationTokens: Set<CancellationTokenSource>;
private globalExcludePattern?: glob.ParsedExpression;
constructor(private config: IFileQuery, private provider: FileSearchProvider2, private sessionLifecycle?: SessionLifecycle) {
const globOptions = config.ignoreGlobCase ? { ignoreCase: true } : undefined;
this.includePattern = config.includePattern && glob.parse(config.includePattern, globOptions);
this.maxResults = config.maxResults || undefined;
this.exists = config.exists;
this.activeCancellationTokens = new Set<CancellationTokenSource>();
this.globalExcludePattern = config.excludePattern && glob.parse(config.excludePattern, globOptions);
}
cancel(): void {
this.activeCancellationTokens.forEach(t => t.cancel());
this.activeCancellationTokens = new Set();
}
search(_onResult: (match: IInternalFileMatch) => void): Promise<IInternalSearchComplete> {
return new Promise((resolve, reject) => {
const onResult = (match: IInternalFileMatch) => {
_onResult(match);
};
// Support that the file pattern is a full path to a file that exists
if (this.isCanceled) {
return resolve({ limitHit: this.isLimitHit });
}
// For each extra file
if (this.config.extraFileResources) {
this.config.extraFileResources
.forEach(extraFile => {
const extraFileStr = extraFile.toString(); // ?
const basename = path.basename(extraFileStr);
if (this.globalExcludePattern && this.globalExcludePattern(extraFileStr, basename)) {
return; // excluded
}
// File: Check for match on file pattern and include pattern
this.matchFile(onResult, { base: extraFile, basename });
});
}
// For each root folder'
// NEW: can just call with an array of folder info
this.doSearch(folderQueries, onResult).then(stats => {
resolve({
limitHit: this.isLimitHit,
stats: stats || undefined // Only looking at single-folder workspace stats...
});
}, (err: Error) => {
reject(new Error(toErrorMessage(err)));
});
}
private async doSearch(fqs: IFolderQuery<URI>[], onResult: (match: IInternalFileMatch) => void): Promise<IFileSearchProviderStats | null> {
const folderOptions = fqs.map(fq => this.getSearchOptionsForFolder(fq));
const session = this.provider instanceof OldFileSearchProviderConverter ? this.sessionLifecycle?.tokenSource.token : this.sessionLifecycle?.obj;
const options: FileSearchProviderOptions = {
folderOptions,
maxResults: this.config.maxResults ?? DEFAULT_MAX_SEARCH_RESULTS,
session
};
const getFolderQueryInfo = (fq: IFolderQuery) => {
const noSiblingsClauses = !queryTester.hasSiblingExcludeClauses();
return { queryTester, noSiblingsClauses, folder: fq.folder, tree: this.initDirectoryTree() };
};
const folderMappings: FolderQuerySearchTree<FolderQueryInfo> = new FolderQuerySearchTree<FolderQueryInfo>(fqs, getFolderQueryInfo);
let providerSW: StopWatch;
try {
this.activeCancellationTokens.add(cancellation);
providerSW = StopWatch.create();
const results = await this.provider.provideFileSearchResults(
this.config.filePattern || '',
options,
cancellation.token);
const providerTime = providerSW.elapsed();
const postProcessSW = StopWatch.create();
if (this.isCanceled && !this.isLimitHit) {
}
if (results) {
results.forEach(result => {
const fqFolderInfo = folderMappings.findQueryFragmentAwareSubstr(result)!;
fileSearchManager.ts ×10
const relativePath = path.posix.relative(fqFolderInfo.folder.path, result.path);
if (fqFolderInfo.noSiblingsClauses) {
this.matchFile(onResult, { base: fqFolderInfo.folder, relativePath, basename });
return;
}
// TODO: Optimize siblings clauses with ripgrep here.
this.addDirectoryEntries(fqFolderInfo.tree, fqFolderInfo.folder, relativePath, onResult);
}
return null;
}
folderMappings.forEachFolderQueryInfo(e => {
return {
providerTime,
postProcessTime: postProcessSW.elapsed()
};
cancellation.dispose();
this.activeCancellationTokens.delete(cancellation);
}
}
private getSearchOptionsForFolder(fq: IFolderQuery<URI>): FileSearchProviderFolderOptions {
const includes = resolvePatternsForProvider(this.config.includePattern, fq.includePattern);
fileSearchManager.ts ×5
let excludePattern = fq.excludePattern?.map(e => ({
patterns: resolvePatternsForProvider(this.config.excludePattern, e.pattern)
if (!excludePattern?.length) {
folder: undefined,
patterns: resolvePatternsForProvider(this.config.excludePattern, undefined)
}];
}
return {
folder: fq.folder,
excludes,
includes,
useIgnoreFiles: {
local: !fq.disregardIgnoreFiles,
parent: !fq.disregardParentIgnoreFiles,
global: !fq.disregardGlobalIgnoreFiles
},
followSymlinks: !fq.ignoreSymlinks,
};
}
private initDirectoryTree(): IDirectoryTree {
rootEntries: [],
pathToEntries: Object.create(null)
};
tree.pathToEntries['.'] = tree.rootEntries;
return tree;
}
private addDirectoryEntries({ pathToEntries }: IDirectoryTree, base: URI, relativeFile: string, onResult: (result: IInternalFileMatch) => void) {
// Support relative paths to files from a root resource (ignores excludes)
fileSearchManager.ts ×9
if (this.filePattern && strings.equals(relativeFile, this.filePattern, this.config.ignoreGlobCase)) {
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) {
add(dirname);
}
base,
relativePath,
basename
});
}
add(relativeFile);
}
private matchDirectoryTree({ rootEntries, pathToEntries }: IDirectoryTree, queryTester: QueryGlobTester, onResult: (result: IInternalFileMatch) => void) {
const filePattern = this.filePattern;
const ignoreGlobCase = this.config.ignoreGlobCase;
function matchDirectory(entries: IDirectoryEntry[]) {
const hasSibling = hasSiblingFn(() => entries.map(entry => entry.basename));
for (let i = 0, n = entries.length; i < n; 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 they
// are searching for and we want to include the result in that case anyway
if (queryTester.matchesExcludesSync(relativePath, basename, !strings.equals(filePattern, basename, ignoreGlobCase) ? hasSibling : undefined)) {
}
const sub = pathToEntries[relativePath];
if (sub) {
if (strings.equals(relativePath, filePattern, ignoreGlobCase)) {
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);
}
private matchFile(onResult: (result: IInternalFileMatch) => void, candidate: IInternalFileMatch): void {
if (!this.includePattern || (candidate.relativePath && this.includePattern(candidate.relativePath, candidate.basename))) {
fileSearchManager.ts ×10
if (this.exists || (this.maxResults && this.resultCount >= this.maxResults)) {
this.cancel();
}
if (!this.isLimitHit) {
onResult(candidate);
}
}
}
interface IInternalSearchComplete {
limitHit: boolean;
stats?: IFileSearchProviderStats;
}
/**
* For backwards compatibility, store both a cancellation token and a session object. The session object is the new implementation, where
*/
class SessionLifecycle {
private _obj: object | undefined;
public readonly tokenSource: CancellationTokenSource;
constructor() {
this.tokenSource = new CancellationTokenSource();
}
public get obj() {
if (this._obj) {
return this._obj;
}
throw new Error('Session object has been dereferenced.');
}
cancel() {
this._obj = undefined; // dereference
}
export class FileSearchManager {
private static readonly BATCH_SIZE = 512;
private readonly sessions = new Map<string, SessionLifecycle>();
fileSearch(config: IFileQuery, provider: FileSearchProvider2, onBatch: (matches: IFileMatch[]) => void, token: CancellationToken): Promise<ISearchCompleteStats> {
const sessionTokenSource = this.getSessionTokenSource(config.cacheKey);
fileSearchManager.ts ×20
const engine = new FileSearchEngine(config, provider, sessionTokenSource);
let resultCount = 0;
const onInternalResult = (batch: IInternalFileMatch[]) => {
onBatch(batch.map(m => this.rawMatchToSearchItem(m)));
};
return this.doSearch(engine, FileSearchManager.BATCH_SIZE, onInternalResult, token).then(
result => {
return {
limitHit: result.limitHit,
stats: result.stats ? {
type: 'fileSearchProvider',
resultCount,
detailStats: result.stats
messages: []
};
});
}
clearCache(cacheKey: string): void {
this.sessions.get(cacheKey)?.cancel();
// with no reference to this, it will be removed from WeakMaps
this.sessions.delete(cacheKey);
}
private getSessionTokenSource(cacheKey: string | undefined): SessionLifecycle | undefined {
}
if (!this.sessions.has(cacheKey)) {
this.sessions.set(cacheKey, new SessionLifecycle());
}
return this.sessions.get(cacheKey);
private rawMatchToSearchItem(match: IInternalFileMatch): IFileMatch {
return {
resource: resources.joinPath(match.base, match.relativePath)
};
} else {
// extraFileResources
return {
resource: match.base
};
}
private doSearch(engine: FileSearchEngine, batchSize: number, onResultBatch: (matches: IInternalFileMatch[]) => void, token: CancellationToken): Promise<IInternalSearchComplete> {
const _onResult = (match: IInternalFileMatch) => {
batch.push(match);
if (batchSize > 0 && batch.length >= batchSize) {
onResultBatch(batch);
batch = [];
}
};
let batch: IInternalFileMatch[] = [];
return engine.search(_onResult).then(result => {
if (batch.length) {
}
listener.dispose();
return result;
}, error => {
if (batch.length) {
onResultBatch(batch);
}
listener.dispose();
return Promise.reject(error);
}