Use Effect FileSystem for workspace entries

Co-authored-by: Julius Marminge <[email protected]>
This commit is contained in:
Cursor AgentandJulius Marminge committed 2026-05-24 16:09:10 +00:00
1 parent 4f0f24f055
commit 63a9c85c26
2 files changed
+174 -108

No files matched your search

@@ -1,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import fsPromises from "node:fs/promises";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, afterEach, describe, expect, vi } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
@@ -16,18 +16,51 @@ import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts";
import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts";
import { WorkspacePathsLive } from "./WorkspacePaths.ts";
const TestLayer = Layer.empty.pipe(
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer))),
Layer.provide(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-workspace-entries-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
const makeTestLayer = (workspaceEntriesLayer = WorkspaceEntriesLive) =>
Layer.empty.pipe(
Layer.provideMerge(workspaceEntriesLayer.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(VcsProcess.layer),
Layer.provideMerge(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcess.layer))),
Layer.provide(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3-workspace-entries-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
const TestLayer = makeTestLayer();
const WorkspaceEntriesWithFileSystem = (
makeFileSystem: (fileSystem: FileSystem.FileSystem) => FileSystem.FileSystem,
) =>
WorkspaceEntriesLive.pipe(
Layer.provide(
Layer.effect(FileSystem.FileSystem, Effect.map(FileSystem.FileSystem, makeFileSystem)).pipe(
Layer.provide(NodeServices.layer),
),
),
);
const instrumentWorkspaceReadDirectory = (
onReadDirectory: (
path: string,
run: () => Effect.Effect<Array<string>, PlatformError.PlatformError>,
) => Effect.Effect<Array<string>, PlatformError.PlatformError>,
) =>
WorkspaceEntriesWithFileSystem((fileSystem) => ({
...fileSystem,
readDirectory: (inputPath, options) =>
onReadDirectory(inputPath, () => fileSystem.readDirectory(inputPath, options)),
}));
const TestLayerWithReadDirectory = (
onReadDirectory: (
path: string,
run: () => Effect.Effect<Array<string>, PlatformError.PlatformError>,
) => Effect.Effect<Array<string>, PlatformError.PlatformError>,
) => makeTestLayer(instrumentWorkspaceReadDirectory(onReadDirectory));
const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) {
const fileSystem = yield* FileSystem.FileSystem;
@@ -80,10 +113,6 @@ const appendSeparator = (input: string) =>
: `${input}${process.platform === "win32" ? "\\" : "/"}`;
it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
afterEach(() => {
vi.restoreAllMocks();
});
describe("search", () => {
it.effect("returns files and directories relative to cwd", () =>
Effect.gen(function* () {
@@ -227,20 +256,16 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
yield* writeTextFile(cwd, "src/components/Composer.tsx");
let rootReadCount = 0;
let releaseRootRead: (() => void) | undefined;
const rootReadGate = new Promise<void>((resolve) => {
releaseRootRead = resolve;
});
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
...args: Parameters<typeof fsPromises.readdir>
) => {
if (args[0] === cwd) {
rootReadCount += 1;
await rootReadGate;
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir);
const rootReadGate = yield* Deferred.make<void>();
const instrumentedLayer = TestLayerWithReadDirectory((inputPath, run) =>
inputPath === cwd
? Effect.gen(function* () {
rootReadCount += 1;
yield* Deferred.await(rootReadGate);
return yield* run();
})
: run(),
);
const searches = yield* Effect.all(
[
@@ -249,17 +274,17 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
searchWorkspaceEntries({ cwd, query: "src", limit: 100 }),
],
{ concurrency: "unbounded" },
).pipe(Effect.forkScoped);
).pipe(Effect.provide(instrumentedLayer), Effect.forkScoped);
for (let attempt = 0; attempt < 50; attempt += 1) {
if (rootReadCount > 0) {
break;
}
yield* Effect.yieldNow;
}
releaseRootRead?.();
yield* Deferred.succeed(rootReadGate, undefined);
yield* Fiber.join(searches);
expect(rootReadCount).toBe(1);
assert.equal(rootReadCount, 1);
}),
);
@@ -274,29 +299,26 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
let activeReads = 0;
let peakReads = 0;
let releaseReads: (() => void) | undefined;
const readsGate = new Promise<void>((resolve) => {
releaseReads = resolve;
});
const originalReaddir = fsPromises.readdir.bind(fsPromises);
vi.spyOn(fsPromises, "readdir").mockImplementation((async (
...args: Parameters<typeof fsPromises.readdir>
) => {
const target = args[0];
if (typeof target === "string" && target.startsWith(cwd)) {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
await readsGate;
try {
return await originalReaddir(...args);
} finally {
activeReads -= 1;
}
}
return originalReaddir(...args);
}) as typeof fsPromises.readdir);
const readsGate = yield* Deferred.make<void>();
const instrumentedLayer = TestLayerWithReadDirectory((inputPath, run) =>
inputPath !== cwd && inputPath.startsWith(cwd)
? Effect.gen(function* () {
activeReads += 1;
peakReads = Math.max(peakReads, activeReads);
yield* Deferred.await(readsGate);
return yield* run().pipe(
Effect.ensuring(
Effect.sync(() => {
activeReads -= 1;
}),
),
);
})
: run(),
);
const search = yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 }).pipe(
Effect.provide(instrumentedLayer),
Effect.forkScoped,
);
for (let attempt = 0; attempt < 50; attempt += 1) {
@@ -305,10 +327,10 @@ it.layer(TestLayer)("WorkspaceEntriesLive", (it) => {
}
yield* Effect.yieldNow;
}
releaseReads?.();
yield* Deferred.succeed(readsGate, undefined);
yield* Fiber.join(search);
expect(peakReads).toBeLessThanOrEqual(32);
assert.isAtMost(peakReads, 32);
}),
);
});
@@ -1,14 +1,14 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as OS from "node:os";
import fsPromises from "node:fs/promises";
import type { Dirent } from "node:fs";
import * as Cache from "effect/Cache";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { type FilesystemBrowseInput, type ProjectEntry } from "@t3tools/contracts";
@@ -56,6 +56,11 @@ interface SearchableWorkspaceEntry extends ProjectEntry {
normalizedName: string;
}
interface DirectoryEntry {
readonly name: string;
readonly kind: ProjectEntry["kind"];
}
type RankedWorkspaceEntry = RankedSearchResult<SearchableWorkspaceEntry>;
function toPosixPath(input: string): string {
@@ -180,6 +185,7 @@ const resolveBrowseTarget = (
});
export const makeWorkspaceEntries = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const vcsRegistry = yield* VcsDriverRegistry;
const workspacePaths = yield* WorkspacePaths;
@@ -269,30 +275,64 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
},
);
const readDirectoryEntry = Effect.fn("WorkspaceEntries.readDirectoryEntry")(function* (
absoluteDir: string,
name: string,
): Effect.fn.Return<Option.Option<DirectoryEntry>, never> {
const absolutePath = path.join(absoluteDir, name);
const linkTarget = yield* fileSystem.readLink(absolutePath).pipe(Effect.option);
if (Option.isSome(linkTarget)) {
return Option.none();
}
return yield* fileSystem.stat(absolutePath).pipe(
Effect.map((info) =>
info.type === "Directory"
? Option.some({ name, kind: "directory" as const })
: info.type === "File"
? Option.some({ name, kind: "file" as const })
: Option.none<DirectoryEntry>(),
),
Effect.catch(() => Effect.succeed(Option.none<DirectoryEntry>())),
);
});
const readDirectoryEntries = Effect.fn("WorkspaceEntries.readDirectoryEntries")(function* (
cwd: string,
relativeDir: string,
): Effect.fn.Return<
{ readonly relativeDir: string; readonly dirents: Dirent[] | null },
{
readonly relativeDir: string;
readonly entries: Option.Option<ReadonlyArray<DirectoryEntry>>;
},
WorkspaceEntriesError
> {
return yield* Effect.tryPromise({
try: async () => {
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
const dirents = await fsPromises.readdir(absoluteDir, { withFileTypes: true });
return { relativeDir, dirents };
},
catch: (cause) =>
new WorkspaceEntriesError({
cwd,
operation: "workspaceEntries.readDirectoryEntries",
detail: cause instanceof Error ? cause.message : String(cause),
cause,
}),
}).pipe(
const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd;
return yield* fileSystem.readDirectory(absoluteDir).pipe(
Effect.flatMap((names) =>
Effect.forEach(
names.toSorted((left, right) => left.localeCompare(right)),
(name) => readDirectoryEntry(absoluteDir, name),
{ concurrency: "unbounded" },
),
),
Effect.map((entries) => ({
relativeDir,
entries: Option.some(entries.filter(Option.isSome).map((entry) => entry.value)),
})),
Effect.mapError(
(cause) =>
new WorkspaceEntriesError({
cwd,
operation: "workspaceEntries.readDirectoryEntries",
detail: cause.message,
cause,
}),
),
Effect.catchIf(
() => relativeDir.length > 0,
() => Effect.succeed({ relativeDir, dirents: null }),
() =>
Effect.succeed({ relativeDir, entries: Option.none<ReadonlyArray<DirectoryEntry>>() }),
),
);
});
@@ -317,29 +357,26 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
);
const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => {
const { relativeDir, dirents } = directoryEntry;
if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>;
const { relativeDir, entries } = directoryEntry;
if (Option.isNone(entries))
return [] as Array<{ entry: DirectoryEntry; 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 === "..") {
const candidates: Array<{ entry: DirectoryEntry; relativePath: string }> = [];
for (const entry of entries.value) {
if (!entry.name || entry.name === "." || entry.name === "..") {
continue;
}
if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) {
continue;
}
if (!dirent.isDirectory() && !dirent.isFile()) {
if (entry.kind === "directory" && IGNORED_DIRECTORY_NAMES.has(entry.name)) {
continue;
}
const relativePath = toPosixPath(
relativeDir ? path.join(relativeDir, dirent.name) : dirent.name,
relativeDir ? path.join(relativeDir, entry.name) : entry.name,
);
if (isPathInIgnoredDirectory(relativePath)) {
continue;
}
candidates.push({ dirent, relativePath });
candidates.push({ entry, relativePath });
}
return candidates;
});
@@ -359,12 +396,12 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const entry = toSearchableWorkspaceEntry({
path: candidate.relativePath,
kind: candidate.dirent.isDirectory() ? "directory" : "file",
kind: candidate.entry.kind,
parentPath: parentPathOf(candidate.relativePath),
});
entries.push(entry);
if (candidate.dirent.isDirectory()) {
if (candidate.entry.kind === "directory") {
pendingDirectories.push(candidate.relativePath);
}
@@ -442,33 +479,40 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
const parentPath = endsWithSeparator ? resolvedInputPath : path.dirname(resolvedInputPath);
const prefix = endsWithSeparator ? "" : path.basename(resolvedInputPath);
const dirents = yield* Effect.tryPromise({
try: () => fsPromises.readdir(parentPath, { withFileTypes: true }),
catch: (cause) =>
new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.browse.readDirectory",
detail: `Unable to browse '${parentPath}': ${cause instanceof Error ? cause.message : String(cause)}`,
cause,
const entries = yield* fileSystem.readDirectory(parentPath).pipe(
Effect.flatMap((names) =>
Effect.forEach(names, (name) => readDirectoryEntry(parentPath, name), {
concurrency: "unbounded",
}),
});
),
Effect.map((entries) => entries.filter(Option.isSome).map((entry) => entry.value)),
Effect.mapError(
(cause) =>
new WorkspaceEntriesBrowseError({
cwd: input.cwd,
partialPath: input.partialPath,
operation: "workspaceEntries.browse.readDirectory",
detail: `Unable to browse '${parentPath}': ${cause.message}`,
cause,
}),
),
);
const showHidden = endsWithSeparator || prefix.startsWith(".");
const lowerPrefix = prefix.toLowerCase();
return {
parentPath,
entries: dirents
entries: entries
.filter(
(dirent) =>
dirent.isDirectory() &&
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !dirent.name.startsWith(".")),
(entry) =>
entry.kind === "directory" &&
entry.name.toLowerCase().startsWith(lowerPrefix) &&
(showHidden || !entry.name.startsWith(".")),
)
.map((dirent) => ({
name: dirent.name,
fullPath: path.join(parentPath, dirent.name),
.map((entry) => ({
name: entry.name,
fullPath: path.join(parentPath, entry.name),
}))
.toSorted((left, right) => left.name.localeCompare(right.name)),
};