Open History to see the last commit
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: ProjectEntry[];
32 truncated: boolean;
33}
34
35const workspaceIndexCache = new Map<string, WorkspaceIndex>();
36const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
37
38function toPosixPath(input: string): string {
39 return input.split(path.sep).join("/");
40}
41
42function parentPathOf(input: string): string | undefined {
43 const separatorIndex = input.lastIndexOf("/");
44 if (separatorIndex === -1) {
45 return undefined;
46 }
47 return input.slice(0, separatorIndex);
48}
49
50function basenameOf(input: string): string {
51 const separatorIndex = input.lastIndexOf("/");
52 if (separatorIndex === -1) {
53 return input;
54 }
55 return input.slice(separatorIndex + 1);
56}
57
58function normalizeQuery(input: string): string {
59 return input
60 .trim()
61 .replace(/^[@./]+/, "")
62 .toLowerCase();
63}
64
65function scoreEntry(entry: ProjectEntry, query: string): number {
66 if (!query) {
67 return entry.kind === "directory" ? 0 : 1;
68 }
69
70 const normalizedPath = entry.path.toLowerCase();
71 const normalizedName = basenameOf(normalizedPath);
72
73 if (normalizedName === query) return 0;
74 if (normalizedPath === query) return 1;
75 if (normalizedName.startsWith(query)) return 2;
76 if (normalizedPath.startsWith(query)) return 3;
77 if (normalizedPath.includes(`/${query}`)) return 4;
78 return 5;
79}
80
81function isPathInIgnoredDirectory(relativePath: string): boolean {
82 const firstSegment = relativePath.split("/")[0];
83 if (!firstSegment) return false;
84 return IGNORED_DIRECTORY_NAMES.has(firstSegment);
85}
86
87function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
88 const parts = input.split("\0");
89 if (parts.length === 0) return [];
90
91 // If output was truncated, the final token can be partial.
92 if (truncated && parts[parts.length - 1]?.length) {
93 parts.pop();
94 }
95
96 return parts.filter((value) => value.length > 0);
97}
98
99function directoryAncestorsOf(relativePath: string): string[] {
100 const segments = relativePath.split("/").filter((segment) => segment.length > 0);
101 if (segments.length <= 1) return [];
102 const directories: string[] = [];
103 for (let index = 1; index < segments.length; index += 1) {
104 directories.push(segments.slice(0, index).join("/"));
105 }
106 return directories;
107}
108
109async function mapWithConcurrency<TInput, TOutput>(
110 items: readonly TInput[],
111 concurrency: number,
112 mapper: (item: TInput, index: number) => Promise<TOutput>,
113): Promise<TOutput[]> {
114 if (items.length === 0) {
115 return [];
116 }
117
118 const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length));
119 const results = Array.from({ length: items.length }) as TOutput[];
120 let nextIndex = 0;
121
122 const workers = Array.from({ length: boundedConcurrency }, async () => {
123 while (nextIndex < items.length) {
124 const currentIndex = nextIndex;
125 nextIndex += 1;
126 results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex);
127 }
128 });
129
130 await Promise.all(workers);
131 return results;
132}
133
134async function isInsideGitWorkTree(cwd: string): Promise<boolean> {
135 const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], {
136 cwd,
137 allowNonZeroExit: true,
138 timeoutMs: 5_000,
139 maxBufferBytes: 4_096,
140 }).catch(() => null);
141 return Boolean(
142 insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true",
143 );
144}
145
146async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise<string[]> {
147 if (relativePaths.length === 0) {
148 return relativePaths;
149 }
150
151 const ignoredPaths = new Set<string>();
152 let chunk: string[] = [];
153 let chunkBytes = 0;
154
155 const flushChunk = async (): Promise<boolean> => {
156 if (chunk.length === 0) {
157 return true;
158 }
159
160 const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], {
161 cwd,
162 allowNonZeroExit: true,
163 timeoutMs: 20_000,
164 maxBufferBytes: 16 * 1024 * 1024,
165 outputMode: "truncate",
166 stdin: `${chunk.join("\0")}\0`,
167 }).catch(() => null);
168 chunk = [];
169 chunkBytes = 0;
170
171 if (!checkIgnore) {
172 return false;
173 }
174
175 // git-check-ignore exits with 1 when no paths match.
176 if (checkIgnore.code !== 0 && checkIgnore.code !== 1) {
177 return false;
178 }
179
180 const matchedIgnoredPaths = splitNullSeparatedPaths(
181 checkIgnore.stdout,
182 Boolean(checkIgnore.stdoutTruncated),
183 );
184 for (const ignoredPath of matchedIgnoredPaths) {
185 ignoredPaths.add(ignoredPath);
186 }
187 return true;
188 };
189
190 for (const relativePath of relativePaths) {
191 const relativePathBytes = Buffer.byteLength(relativePath) + 1;
192 if (
193 chunk.length > 0 &&
194 chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES &&
195 !(await flushChunk())
196 ) {
197 return relativePaths;
198 }
199
200 chunk.push(relativePath);
201 chunkBytes += relativePathBytes;
202
203 if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) {
204 return relativePaths;
205 }
206 }
207
208 if (!(await flushChunk())) {
209 return relativePaths;
210 }
211
212 if (ignoredPaths.size === 0) {
213 return relativePaths;
214 }
215
216 return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
217}
218
219async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex | null> {
220 if (!(await isInsideGitWorkTree(cwd))) {
221 return null;
222 }
223
224 const listedFiles = await runProcess(
225 "git",
226 ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
227 {
228 cwd,
229 allowNonZeroExit: true,
230 timeoutMs: 20_000,
231 maxBufferBytes: 16 * 1024 * 1024,
232 outputMode: "truncate",
233 },
234 ).catch(() => null);
235 if (!listedFiles || listedFiles.code !== 0) {
236 return null;
237 }
238
239 const listedPaths = splitNullSeparatedPaths(
240 listedFiles.stdout,
241 Boolean(listedFiles.stdoutTruncated),
242 )
243 .map((entry) => toPosixPath(entry))
244 .filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
245 const filePaths = await filterGitIgnoredPaths(cwd, listedPaths);
246
247 const directorySet = new Set<string>();
248 for (const filePath of filePaths) {
249 for (const directoryPath of directoryAncestorsOf(filePath)) {
250 if (!isPathInIgnoredDirectory(directoryPath)) {
251 directorySet.add(directoryPath);
252 }
253 }
254 }
255
256 const directoryEntries: ProjectEntry[] = [...directorySet]
257 .toSorted((left, right) => left.localeCompare(right))
258 .map((directoryPath) => ({
259 path: directoryPath,
260 kind: "directory",
261 parentPath: parentPathOf(directoryPath),
262 }));
263 const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
264 .toSorted((left, right) => left.localeCompare(right))
265 .map((filePath) => ({
266 path: filePath,
267 kind: "file",
268 parentPath: parentPathOf(filePath),
269 }));
270
271 const entries = [...directoryEntries, ...fileEntries];
272 return {
273 scannedAt: Date.now(),
274 entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES),
275 truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES,
276 };
277}
278
279async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
280 const gitIndexed = await buildWorkspaceIndexFromGit(cwd);
281 if (gitIndexed) {
282 return gitIndexed;
283 }
284 const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
285
286 let pendingDirectories: string[] = [""];
287 const entries: ProjectEntry[] = [];
288 let truncated = false;
289
290 while (pendingDirectories.length > 0 && !truncated) {
291 const currentDirectories = pendingDirectories;
292 pendingDirectories = [];
293 const directoryEntries = await mapWithConcurrency(
294 currentDirectories,
295 WORKSPACE_SCAN_READDIR_CONCURRENCY,
296 async (relativeDir) => {
297 const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
298 try {
299 const dirents = await fs.readdir(absoluteDir, { withFileTypes: true });
300 return { relativeDir, dirents };
301 } catch (error) {
302 if (!relativeDir) {
303 throw new Error(
304 `Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`,
305 { cause: error },
306 );
307 }
308 return { relativeDir, dirents: null };
309 }
310 },
311 );
312
313 const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
314 const { relativeDir, dirents } = directoryEntry;
315 if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
316
317 dirents.sort((left, right) => left.name.localeCompare(right.name));
318 const candidates: Array<{ dirent: Dirent; relativePath: string }> = [];
319 for (const dirent of dirents) {
320 if (!dirent.name || dirent.name === "." || dirent.name === "..") {
321 continue;
322 }
323 if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
324 continue;
325 }
326 if (!dirent.isDirectory() && !dirent.isFile()) {
327 continue;
328 }
329
330 const relativePath = toPosixPath(
331 relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
332 );
333 if (isPathInIgnoredDirectory(relativePath)) {
334 continue;
335 }
336 candidates.push({ dirent, relativePath });
337 }
338 return candidates;
339 });
340
341 const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) =>
342 candidateEntries.map((entry) => entry.relativePath),
343 );
344 const allowedPathSet = shouldFilterWithGitIgnore
345 ? new Set(await filterGitIgnoredPaths(cwd, candidatePaths))
346 : null;
347
348 for (const candidateEntries of candidateEntriesByDirectory) {
349 for (const candidate of candidateEntries) {
350 if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) {
351 continue;
352 }
353
354 const entry: ProjectEntry = {
355 path: candidate.relativePath,
356 kind: candidate.dirent.isDirectory() ? "directory" : "file",
357 parentPath: parentPathOf(candidate.relativePath),
358 };
359 entries.push(entry);
360
361 if (candidate.dirent.isDirectory()) {
362 pendingDirectories.push(candidate.relativePath);
363 }
364
365 if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) {
366 truncated = true;
367 break;
368 }
369 }
370
371 if (truncated) {
372 break;
373 }
374 }
375 }
376
377 return {
378 scannedAt: Date.now(),
379 entries,
380 truncated,
381 };
382}
383
384async function getWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
385 const cached = workspaceIndexCache.get(cwd);
386 if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) {
387 return cached;
388 }
389
390 const inFlight = inFlightWorkspaceIndexBuilds.get(cwd);
391 if (inFlight) {
392 return inFlight;
393 }
394
395 const nextPromise = buildWorkspaceIndex(cwd)
396 .then((next) => {
397 workspaceIndexCache.set(cwd, next);
398 while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) {
399 const oldestKey = workspaceIndexCache.keys().next().value;
400 if (!oldestKey) break;
401 workspaceIndexCache.delete(oldestKey);
402 }
403 return next;
404 })
405 .finally(() => {
406 inFlightWorkspaceIndexBuilds.delete(cwd);
407 });
408 inFlightWorkspaceIndexBuilds.set(cwd, nextPromise);
409 return nextPromise;
410}
411
412export async function searchWorkspaceEntries(
413 input: ProjectSearchEntriesInput,
414): Promise<ProjectSearchEntriesResult> {
415 const index = await getWorkspaceIndex(input.cwd);
416 const normalizedQuery = normalizeQuery(input.query);
417 const candidates = normalizedQuery
418 ? index.entries.filter((entry) => entry.path.toLowerCase().includes(normalizedQuery))
419 : index.entries;
420
421 const ranked = candidates.toSorted((left, right) => {
422 const scoreDelta = scoreEntry(left, normalizedQuery) - scoreEntry(right, normalizedQuery);
423 if (scoreDelta !== 0) return scoreDelta;
424 return left.path.localeCompare(right.path);
425 });
426
427 return {
428 entries: ranked.slice(0, input.limit),
429 truncated: index.truncated || ranked.length > input.limit,
430 };
431}