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