Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions packages/core/src/utils/filesearch/fileSearch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,47 @@ describe('FileSearch', () => {
);
});

it('should prioritize filenames closer to the end of the path and shorter paths', async () => {
tmpDir = await createTmpDir({
src: {
'hooks.ts': '',
hooks: {
'index.ts': '',
},
utils: {
'hooks.tsx': '',
},
'hooks-dev': {
'test.ts': '',
},
},
});

const fileSearch = FileSearchFactory.create({
projectRoot: tmpDir,
fileDiscoveryService: new FileDiscoveryService(tmpDir, {
respectGitIgnore: false,
respectGeminiIgnore: false,
}),
ignoreDirs: [],
cache: false,
cacheTtl: 0,
enableRecursiveFileSearch: true,
enableFuzzySearch: true,
});

await fileSearch.initialize();
const results = await fileSearch.search('hooks');

// The order should prioritize matches closer to the end and shorter strings.
// FZF matches right-to-left.
// src/hooks/ -> length 10, maxPos 8, dist 2
// src/hooks.ts -> length 12, maxPos 8, dist 4
// src/hooks/index.ts -> length 18, maxPos 8, dist 10
expect(results[0]).toBe('src/hooks/');
expect(results[1]).toBe('src/hooks.ts');
});

it('should return empty array when no matches are found', async () => {
tmpDir = await createTmpDir({
src: ['file1.js'],
Expand Down
16 changes: 16 additions & 0 deletions packages/core/src/utils/filesearch/fileSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ import { AsyncFzf, type FzfResultItem } from 'fzf';
import { unescapePath } from '../paths.js';
import type { FileDiscoveryService } from '../../services/fileDiscoveryService.js';

const byLengthAsc = (a: FzfResultItem<string>, b: FzfResultItem<string>) =>
a.item.length - b.item.length;

const byMatchPosFromEnd = (
a: FzfResultItem<string>,
b: FzfResultItem<string>,
) => {
const maxPosA = Math.max(-1, ...a.positions);
const maxPosB = Math.max(-1, ...b.positions);
const distA = a.item.length - maxPosA;
const distB = b.item.length - maxPosB;
return distA - distB;
};

export interface FileSearchOptions {
projectRoot: string;
ignoreDirs: string[];
Expand Down Expand Up @@ -192,6 +206,8 @@ class RecursiveFileSearch implements FileSearch {
// files, because the v2 algorithm is just too slow in those cases.
this.fzf = new AsyncFzf(this.allFiles, {
fuzzy: this.allFiles.length > 20000 ? 'v1' : 'v2',
forward: false,
tiebreakers: [byMatchPosFromEnd, byLengthAsc],
});
}
}
Expand Down
Loading