Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

workspaceEntries.ts

565 lines15.5 KB

1import fs from "node:fs/promises";
2import type { Dirent } from "node:fs";
3import path from "node:path";
4import { runProcess } from "./processRunner";
5​
6import {
7 ProjectEntry,
8 ProjectSearchEntriesInput,
9 ProjectSearchEntriesResult,
10} from "@t3tools/contracts";
11​
12const WORKSPACE_CACHE_TTL_MS = 15_000;
13const WORKSPACE_CACHE_MAX_KEYS = 4;
14const WORKSPACE_INDEX_MAX_ENTRIES = 25_000;
15const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32;
16const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
17const IGNORED_DIRECTORY_NAMES = new Set([
18 ".git",
19 ".convex",
20 "node_modules",
21 ".next",
22 ".turbo",
23 "dist",
24 "build",
25 "out",
26 ".cache",
27]);
28​
29interface WorkspaceIndex {
30 scannedAt: number;
31 entries: SearchableWorkspaceEntry[];
32 truncated: boolean;
34​
35interface SearchableWorkspaceEntry extends ProjectEntry {
36 normalizedPath: string;
37 normalizedName: string;
39​
40interface RankedWorkspaceEntry {
41 entry: SearchableWorkspaceEntry;
42 score: number;
44​
45const workspaceIndexCache = new Map<string, WorkspaceIndex>();
46const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
47​
48function toPosixPath(input: string): string {
49 return input.split(path.sep).join("/");
51​
52function parentPathOf(input: string): string | undefined {
53 const separatorIndex = input.lastIndexOf("/");
54 if (separatorIndex === -1) {
55 return undefined;
56 }
57 return input.slice(0, separatorIndex);
59​
60function basenameOf(input: string): string {
61 const separatorIndex = input.lastIndexOf("/");
62 if (separatorIndex === -1) {
63 return input;
64 }
65 return input.slice(separatorIndex + 1);
67​
68function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry {
69 const normalizedPath = entry.path.toLowerCase();
70 return {
71 ...entry,
72 normalizedPath,
73 normalizedName: basenameOf(normalizedPath),
74 };
76​
77function normalizeQuery(input: string): string {
78 return input
79 .trim()
80 .replace(/^[@./]+/, "")
81 .toLowerCase();
83​
84function scoreSubsequenceMatch(value: string, query: string): number | null {
85 if (!query) return 0;
86​
87 let queryIndex = 0;
88 let firstMatchIndex = -1;
89 let previousMatchIndex = -1;
90 let gapPenalty = 0;
91​
92 for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
93 if (value[valueIndex] !== query[queryIndex]) {
94 continue;
95 }
96​
97 if (firstMatchIndex === -1) {
98 firstMatchIndex = valueIndex;
99 }
100 if (previousMatchIndex !== -1) {
101 gapPenalty += valueIndex - previousMatchIndex - 1;
102 }
103​
104 previousMatchIndex = valueIndex;
105 queryIndex += 1;
106 if (queryIndex === query.length) {
107 const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
108 const lengthPenalty = Math.min(64, value.length - query.length);
109 return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;
110 }
111 }
112​
113 return null;
115​
116function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null {
117 if (!query) {
118 return entry.kind === "directory" ? 0 : 1;
119 }
120​
121 const { normalizedPath, normalizedName } = entry;
122​
123 if (normalizedName === query) return 0;
124 if (normalizedPath === query) return 1;
125 if (normalizedName.startsWith(query)) return 2;
126 if (normalizedPath.startsWith(query)) return 3;
127 if (normalizedPath.includes(`/${query}`)) return 4;
128 if (normalizedName.includes(query)) return 5;
129 if (normalizedPath.includes(query)) return 6;
130​
131 const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query);
132 if (nameFuzzyScore !== null) {
133 return 100 + nameFuzzyScore;
134 }
135​
136 const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query);
137 if (pathFuzzyScore !== null) {
138 return 200 + pathFuzzyScore;
139 }
140​
141 return null;
143​
144function compareRankedWorkspaceEntries(
145 left: RankedWorkspaceEntry,
146 right: RankedWorkspaceEntry,
147): number {
148 const scoreDelta = left.score - right.score;
149 if (scoreDelta !== 0) return scoreDelta;
150 return left.entry.path.localeCompare(right.entry.path);
152​
153function findInsertionIndex(
154 rankedEntries: RankedWorkspaceEntry[],
155 candidate: RankedWorkspaceEntry,
156): number {
157 let low = 0;
158 let high = rankedEntries.length;
159​
160 while (low < high) {
161 const middle = low + Math.floor((high - low) / 2);
162 const current = rankedEntries[middle];
163 if (!current) {
164 break;
165 }
166​
167 if (compareRankedWorkspaceEntries(candidate, current) < 0) {
168 high = middle;
169 } else {
170 low = middle + 1;
171 }
172 }
173​
174 return low;
176​
177function insertRankedEntry(
178 rankedEntries: RankedWorkspaceEntry[],
179 candidate: RankedWorkspaceEntry,
180 limit: number,
181): void {
182 if (limit <= 0) {
183 return;
184 }
185​
186 const insertionIndex = findInsertionIndex(rankedEntries, candidate);
187 if (rankedEntries.length < limit) {
188 rankedEntries.splice(insertionIndex, 0, candidate);
189 return;
190 }
191​
192 if (insertionIndex >= limit) {
193 return;
194 }
195​
196 rankedEntries.splice(insertionIndex, 0, candidate);
197 rankedEntries.pop();
199​
200function isPathInIgnoredDirectory(relativePath: string): boolean {
201 const firstSegment = relativePath.split("/")[0];
202 if (!firstSegment) return false;
203 return IGNORED_DIRECTORY_NAMES.has(firstSegment);
205​
206function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
207 const parts = input.split("\0");
208 if (parts.length === 0) return [];
209​
210 // If output was truncated, the final token can be partial.
211 if (truncated && parts[parts.length - 1]?.length) {
212 parts.pop();
213 }
214​
215 return parts.filter((value) => value.length > 0);
217​
218function directoryAncestorsOf(relativePath: string): string[] {
219 const segments = relativePath.split("/").filter((segment) => segment.length > 0);
220 if (segments.length <= 1) return [];
221 const directories: string[] = [];
222 for (let index = 1; index < segments.length; index += 1) {
223 directories.push(segments.slice(0, index).join("/"));
224 }
225 return directories;
227​
228async function mapWithConcurrency<TInput, TOutput>(
229 items: readonly TInput[],
230 concurrency: number,
231 mapper: (item: TInput, index: number) => Promise<TOutput>,
232): Promise<TOutput[]> {
233 if (items.length === 0) {
234 return [];
235 }
236​
237 const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length));
238 const results = Array.from({ length: items.length }) as TOutput[];
239 let nextIndex = 0;
240​
241 const workers = Array.from({ length: boundedConcurrency }, async () => {
242 while (nextIndex < items.length) {
243 const currentIndex = nextIndex;
244 nextIndex += 1;
245 results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex);
246 }
247 });
248​
249 await Promise.all(workers);
250 return results;
252​
253async function isInsideGitWorkTree(cwd: string): Promise<boolean> {
254 const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
255 cwd,
256 allowNonZeroExit: true,
257 timeoutMs: 5_000,
258 maxBufferBytes: 4_096,
259 }).catch(() => null);
260 return Boolean(
261 insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true",
262 );
264​
265async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise<string[]> {
266 if (relativePaths.length === 0) {
267 return relativePaths;
268 }
269​
270 const ignoredPaths = new Set<string>();
271 let chunk: string[] = [];
272 let chunkBytes = 0;
273​
274 const flushChunk = async (): Promise<boolean> => {
275 if (chunk.length === 0) {
276 return true;
277 }
278​
279 const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
280 cwd,
281 allowNonZeroExit: true,
282 timeoutMs: 20_000,
283 maxBufferBytes: 16 * 1024 * 1024,
284 outputMode: "truncate",
285 stdin: `${chunk.join("\0")}\0`,
286 }).catch(() => null);
287 chunk = [];
288 chunkBytes = 0;
289​
290 if (!checkIgnore) {
291 return false;
292 }
293​
294 // git-check-ignore exits with 1 when no paths match.
295 if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
296 return false;
297 }
298​
299 const matchedIgnoredPaths = splitNullSeparatedPaths(
300 checkIgnore.stdout,
301 Boolean(checkIgnore.stdoutTruncated),
302 );
303 for (const ignoredPath of matchedIgnoredPaths) {
304 ignoredPaths.add(ignoredPath);
305 }
306 return true;
307 };
308​
309 for (const relativePath of relativePaths) {
310 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
311 if (
312 chunk.length > 0 &&
313 chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES &&
314 !(await flushChunk())
315 ) {
316 return relativePaths;
317 }
318​
319 chunk.push(relativePath);
320 chunkBytes += relativePathBytes;
321​
322 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) {
323 return relativePaths;
324 }
325 }
326​
327 if (!(await flushChunk())) {
328 return relativePaths;
329 }
330​
331 if (ignoredPaths.size === 0) {
332 return relativePaths;
333 }
334​
335 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
337​
338async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
339 if (!(await isInsideGitWorkTree(cwd))) {
340 return null;
341 }
342​
343 const listedFiles = await runProcess(
344 "git",
345 ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
346 {
347 cwd,
348 allowNonZeroExit: true,
349 timeoutMs: 20_000,
350 maxBufferBytes: 16 * 1024 * 1024,
351 outputMode: "truncate",
352 },
353 ).catch(() => null);
354 if (!listedFiles || listedFiles.code !== 0) {
355 return null;
356 }
357​
358 const listedPaths = splitNullSeparatedPaths(
359 listedFiles.stdout,
360 Boolean(listedFiles.stdoutTruncated),
361 )
362 .map((entry) => toPosixPath(entry))
363 .filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
364 const filePaths = await filterGitIgnoredPaths(cwd, listedPaths);
365​
366 const directorySet = new Set<string>();
367 for (const filePath of filePaths) {
368 for (const directoryPath of directoryAncestorsOf(filePath)) {
369 if (!isPathInIgnoredDirectory(directoryPath)) {
370 directorySet.add(directoryPath);
371 }
372 }
373 }
374​
375 const directoryEntries = [...directorySet]
376 .toSorted((left, right) => left.localeCompare(right))
377 .map(
378 (directoryPath): ProjectEntry => ({
379 path: directoryPath,
380 kind: "directory",
381 parentPath: parentPathOf(directoryPath),
382 }),
383 )
384 .map(toSearchableWorkspaceEntry);
385 const fileEntries = [...new Set(filePaths)]
386 .toSorted((left, right) => left.localeCompare(right))
387 .map(
388 (filePath): ProjectEntry => ({
389 path: filePath,
390 kind: "file",
391 parentPath: parentPathOf(filePath),
392 }),
393 )
394 .map(toSearchableWorkspaceEntry);
395​
396 const entries = [...directoryEntries, ...fileEntries];
397 return {
398 scannedAt: Date.now(),
399 entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
400 truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
401 };
403​
404async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
405 const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
406 if (gitIndexed) {
407 return gitIndexed;
408 }
409 const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
410​
411 let pendingDirectories: string[] = [""];
412 const entries: SearchableWorkspaceEntry[] = [];
413 let truncated = false;
414​
415 while (pendingDirectories.length > 0 && !truncated) {
416 const currentDirectories = pendingDirectories;
417 pendingDirectories = [];
418 const directoryEntries = await mapWithConcurrency(
419 currentDirectories,
420 WORKSPACE_SCAN_READDIR_CONCURRENCY,
421 async (relativeDir) => {
422 const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
423 try {
424 const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
425 return { relativeDir, dirents };
426 } catch (error) {
427 if (!relativeDir) {
428 throw new Error(
429 `Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
430 { cause: error },
431 );
432 }
433 return { relativeDir, dirents: null };
434 }
435 },
436 );
437​
438 const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
439 const { relativeDir, dirents } = directoryEntry;
440 if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
441​
442 dirents.sort((left, right) => left.name.localeCompare(right.name));
443 const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
444 for (const dirent of dirents) {
445 if (!dirent.name || dirent.name === "." || dirent.name === "..") {
446 continue;
447 }
448 if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
449 continue;
450 }
451 if (!dirent.isDirectory() && !dirent.isFile()) {
452 continue;
453 }
454​
455 const relativePath = toPosixPath(
456 relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
457 );
458 if (isPathInIgnoredDirectory(relativePath)) {
459 continue;
460 }
461 candidates.push({ dirent, relativePath });
462 }
463 return candidates;
464 });
465​
466 const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
467 candidateEntries.map((entry) => entry.relativePath),
468 );
469 const allowedPathSet = shouldFilterWithGitIgnore
470 ? new Set(await filterGitIgnoredPaths(cwd, candidatePaths))
471 : null;
472​
473 for (const candidateEntries of candidateEntriesByDirectory) {
474 for (const candidate of candidateEntries) {
475 if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
476 continue;
477 }
478​
479 const entry = toSearchableWorkspaceEntry({
480 path: candidate.relativePath,
481 kind: candidate.dirent.isDirectory() ? "directory" : "file",
482 parentPath: parentPathOf(candidate.relativePath),
483 });
484 entries.push(entry);
485​
486 if (candidate.dirent.isDirectory()) {
487 pendingDirectories.push(candidate.relativePath);
488 }
489​
490 if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
491 truncated = true;
492 break;
493 }
494 }
495​
496 if (truncated) {
497 break;
498 }
499 }
500 }
501​
502 return {
503 scannedAt: Date.now(),
504 entries,
505 truncated,
506 };
508​
509async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
510 const cached = workspaceIndexCache.get(cwd);
511 if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
512 return cached;
513 }
514​
515 const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
516 if (inFlight) {
517 return inFlight;
518 }
519​
520 const nextPromise = buildWorkspaceIndex(cwd)
521 .then((next) => {
522 workspaceIndexCache.set(cwd, next);
523 while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
524 const oldestKey = workspaceIndexCache.keys().next().value;
525 if (!oldestKey) break;
526 workspaceIndexCache.delete(oldestKey);
527 }
528 return next;
529 })
530 .finally(() => {
531 inFlightWorkspaceIndexBuilds.delete(cwd);
532 });
533 inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);
534 return nextPromise;
536​
537export function clearWorkspaceIndexCache(cwd: string): void {
538 workspaceIndexCache.delete(cwd);
539 inFlightWorkspaceIndexBuilds.delete(cwd);
541​
542export async function searchWorkspaceEntries(
543 input: ProjectSearchEntriesInput,
544): Promise<ProjectSearchEntriesResult> {
545 const index = await getWorkspaceIndex(input.cwd);
546 const normalizedQuery = normalizeQuery(input.query);
547 const limit = Math.max(0, Math.floor(input.limit));
548 const rankedEntries: RankedWorkspaceEntry[] = [];
549 let matchedEntryCount = 0;
550​
551 for (const entry of index.entries) {
552 const score = scoreEntry(entry, normalizedQuery);
553 if (score === null) {
554 continue;
555 }
556​
557 matchedEntryCount += 1;
558 insertRankedEntry(rankedEntries, { entry, score }, limit);
559 }
560​
561 return {
562 entries: rankedEntries.map((candidate) => candidate.entry),
563 truncated: index.truncated || matchedEntryCount > limit,
564 };