Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge 01602257de Format workspace filesystem tests
Co-authored-by: Julius Marminge <[email protected]>
2026-06-18 16:11:32 +00:00
Cursor AgentandJulius Marminge cb1e1698f3 Refactor filesystem and VCS config Effect usage
Co-authored-by: Julius Marminge <[email protected]>
2026-06-18 16:10:22 +00:00
4 changed files with 229 additions and 84 deletions

No files matched your search

@@ -53,6 +53,48 @@ describe("VcsProjectConfig", () => {
);
});
it.layer(TestLayer)("ignores invalid project config files", (it) => {
it.effect("returns auto for malformed JSON", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const configDir = path.join(root, ".t3code");
yield* fileSystem.makeDirectory(configDir, { recursive: true });
yield* fileSystem.writeFileString(path.join(configDir, "vcs.json"), "{ not json");
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
}),
);
it.effect("returns auto for schema-invalid JSON", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-vcs-config-test-",
});
const configDir = path.join(root, ".t3code");
yield* fileSystem.makeDirectory(configDir, { recursive: true });
yield* fileSystem.writeFileString(
path.join(configDir, "vcs.json"),
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify({ vcs: { kind: "svn" } }),
);
const config = yield* VcsProjectConfig.VcsProjectConfig;
const kind = yield* config.resolveKind({ cwd: root });
assert.equal(kind, "auto");
}),
);
});
it.layer(TestLayer)("falls back to auto when no config exists", (it) => {
it.effect("returns auto", () =>
Effect.gen(function* () {
+8 -22
View File
@@ -2,6 +2,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
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 * as Schema from "effect/Schema";
@@ -15,16 +16,10 @@ const ProjectVcsConfig = Schema.Struct({
),
vcsKind: Schema.optional(VcsDriverKind),
});
const isProjectVcsConfig = Schema.is(ProjectVcsConfig);
interface ProjectVcsConfigFile {
readonly vcs?:
| {
readonly kind?: VcsDriverKindType | undefined;
}
| undefined;
readonly vcsKind?: VcsDriverKindType | undefined;
}
const decodeProjectVcsConfigJson = Schema.decodeUnknownOption(
Schema.fromJsonString(ProjectVcsConfig),
);
type ProjectVcsConfigFile = typeof ProjectVcsConfig.Type;
export interface VcsProjectConfigResolveInput {
readonly cwd: string;
@@ -45,15 +40,6 @@ function configuredKind(config: ProjectVcsConfigFile): VcsDriverKindType | "auto
return config.vcs?.kind ?? config.vcsKind ?? "auto";
}
function parseConfig(raw: string): ProjectVcsConfigFile | null {
try {
const parsed = JSON.parse(raw) as unknown;
return isProjectVcsConfig(parsed) ? parsed : null;
} catch {
return null;
}
}
export const make = Effect.fn("makeVcsProjectConfig")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -89,15 +75,15 @@ export const make = Effect.fn("makeVcsProjectConfig")(function* () {
return "auto" as const;
}
const parsed = parseConfig(raw);
if (parsed === null) {
const parsed = decodeProjectVcsConfigJson(raw);
if (Option.isNone(parsed)) {
yield* Effect.logWarning("invalid VCS project config", {
configPath,
});
return "auto" as const;
}
return configuredKind(parsed);
return configuredKind(parsed.value);
});
const resolveKind: VcsProjectConfigShape["resolveKind"] = Effect.fn(
@@ -1,5 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, it, describe } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -18,6 +18,8 @@ const ProjectLayer = WorkspaceFileSystemLive.pipe(
Layer.provide(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePathsLive))),
);
const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
const TestLayer = Layer.empty.pipe(
Layer.provideMerge(ProjectLayer),
Layer.provideMerge(WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePathsLive))),
@@ -52,6 +54,20 @@ const writeTextFile = Effect.fn("writeTextFile")(function* (
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
});
const writeBinaryFile = Effect.fn("writeBinaryFile")(function* (
cwd: string,
relativePath: string,
contents: Uint8Array,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const absolutePath = path.join(cwd, relativePath);
yield* fileSystem
.makeDirectory(path.dirname(absolutePath), { recursive: true })
.pipe(Effect.orDie);
yield* fileSystem.writeFile(absolutePath, contents).pipe(Effect.orDie);
});
it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (it) => {
describe("readFile", () => {
it.effect("reads UTF-8 files relative to the workspace root", () =>
@@ -65,7 +81,7 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
relativePath: "src/index.ts",
});
expect(result).toEqual({
assert.deepStrictEqual(result, {
relativePath: "src/index.ts",
contents: "export const answer = 42;\n",
byteLength: 26,
@@ -83,7 +99,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFile({ cwd, relativePath: "../escape.md" })
.pipe(Effect.flip);
expect(error.message).toContain(
assert.include(
error.message,
"Workspace file path must be relative to the project root: ../escape.md",
);
}),
@@ -106,7 +123,56 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFile({ cwd, relativePath: "linked-secret.txt" })
.pipe(Effect.flip);
expect(error.message).toContain("resolves outside the project root");
assert.include(error.message, "resolves outside the project root");
}),
);
it.effect("truncates files larger than the preview byte limit", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem;
const cwd = yield* makeTempDir;
const contents = `${"a".repeat(PROJECT_READ_FILE_MAX_BYTES)}tail`;
yield* writeTextFile(cwd, "large.txt", contents);
const result = yield* workspaceFileSystem.readFile({
cwd,
relativePath: "large.txt",
});
assert.equal(result.contents.length, PROJECT_READ_FILE_MAX_BYTES);
assert.equal(result.contents, "a".repeat(PROJECT_READ_FILE_MAX_BYTES));
assert.equal(result.byteLength, PROJECT_READ_FILE_MAX_BYTES + 4);
assert.isTrue(result.truncated);
}),
);
it.effect("rejects binary files", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem;
const cwd = yield* makeTempDir;
yield* writeBinaryFile(cwd, "binary.bin", new Uint8Array([65, 0, 66]));
const error = yield* workspaceFileSystem
.readFile({ cwd, relativePath: "binary.bin" })
.pipe(Effect.flip);
assert.include(error.message, "Binary files cannot be previewed as text.");
}),
);
it.effect("rejects directories", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const cwd = yield* makeTempDir;
yield* fileSystem.makeDirectory(path.join(cwd, "src"), { recursive: true });
const error = yield* workspaceFileSystem
.readFile({ cwd, relativePath: "src" })
.pipe(Effect.flip);
assert.include(error.message, "Workspace path is not a file.");
}),
);
});
@@ -127,8 +193,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
.readFileString(path.join(cwd, "plans/effect-rpc.md"))
.pipe(Effect.orDie);
expect(result).toEqual({ relativePath: "plans/effect-rpc.md" });
expect(saved).toBe("# Plan\n");
assert.deepStrictEqual(result, { relativePath: "plans/effect-rpc.md" });
assert.equal(saved, "# Plan\n");
}),
);
@@ -140,9 +206,7 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
yield* writeTextFile(cwd, "src/existing.ts", "export {};\n");
const beforeWrite = yield* workspaceEntries.list({ cwd });
expect(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md")).toBe(
false,
);
assert.isFalse(beforeWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md"));
yield* workspaceFileSystem.writeFile({
cwd,
@@ -151,10 +215,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
});
const afterWrite = yield* workspaceEntries.list({ cwd });
expect(afterWrite.entries).toEqual(
expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]),
);
expect(afterWrite.truncated).toBe(false);
assert.isTrue(afterWrite.entries.some((entry) => entry.path === "plans/effect-rpc.md"));
assert.isFalse(afterWrite.truncated);
}),
);
@@ -173,7 +235,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
})
.pipe(Effect.flip);
expect(error.message).toContain(
assert.include(
error.message,
"Workspace file path must be relative to the project root: ../escape.md",
);
@@ -181,7 +244,7 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
const escapedStat = yield* fileSystem
.stat(escapedPath)
.pipe(Effect.orElseSucceed(() => null));
expect(escapedStat).toBeNull();
assert.isNull(escapedStat);
}),
);
});
@@ -1,6 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
import fsPromises from "node:fs/promises";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -16,6 +13,25 @@ import { WorkspacePaths } from "../Services/WorkspacePaths.ts";
const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
function makeReadFileError(input: {
readonly cwd: string;
readonly relativePath: string;
readonly detail: string;
readonly cause?: unknown;
}) {
return new WorkspaceFileSystemError({
cwd: input.cwd,
relativePath: input.relativePath,
operation: "workspaceFileSystem.readFile",
detail: input.detail,
...(input.cause === undefined ? {} : { cause: input.cause }),
});
}
function causeMessage(cause: { readonly message: string }) {
return cause.message;
}
export const makeWorkspaceFileSystem = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -29,54 +45,92 @@ export const makeWorkspaceFileSystem = Effect.gen(function* () {
relativePath: input.relativePath,
});
const result = yield* Effect.tryPromise({
try: async () => {
const [realWorkspaceRoot, realTargetPath] = await Promise.all([
fsPromises.realpath(input.cwd),
fsPromises.realpath(target.absolutePath),
]);
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
relativeRealPath === ".." ||
path.isAbsolute(relativeRealPath)
) {
throw new Error("Workspace file path resolves outside the project root.");
}
const handle = await fsPromises.open(realTargetPath, "r");
try {
const stat = await handle.stat();
if (!stat.isFile()) {
throw new Error("Workspace path is not a file.");
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = await handle.read(buffer, 0, bytesToRead, 0);
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
throw new Error("Binary files cannot be previewed as text.");
}
const contents = new TextDecoder("utf-8").decode(fileBytes);
return {
relativePath: target.relativePath,
contents,
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
} finally {
await handle.close();
}
},
catch: (cause) =>
new WorkspaceFileSystemError({
const [realWorkspaceRoot, realTargetPath] = yield* Effect.all([
fileSystem.realPath(input.cwd),
fileSystem.realPath(target.absolutePath),
]).pipe(
Effect.mapError((cause) =>
makeReadFileError({
cwd: input.cwd,
relativePath: input.relativePath,
operation: "workspaceFileSystem.readFile",
detail: cause instanceof Error ? cause.message : String(cause),
detail: causeMessage(cause),
cause,
}),
});
),
);
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
relativeRealPath === ".." ||
path.isAbsolute(relativeRealPath)
) {
return yield* makeReadFileError({
cwd: input.cwd,
relativePath: input.relativePath,
detail: "Workspace file path resolves outside the project root.",
});
}
const result = yield* Effect.scoped(
Effect.gen(function* () {
const handle = yield* fileSystem.open(realTargetPath, { flag: "r" }).pipe(
Effect.mapError((cause) =>
makeReadFileError({
cwd: input.cwd,
relativePath: input.relativePath,
detail: causeMessage(cause),
cause,
}),
),
);
const stat = yield* handle.stat.pipe(
Effect.mapError((cause) =>
makeReadFileError({
cwd: input.cwd,
relativePath: input.relativePath,
detail: causeMessage(cause),
cause,
}),
),
);
if (stat.type !== "File") {
return yield* makeReadFileError({
cwd: input.cwd,
relativePath: input.relativePath,
detail: "Workspace path is not a file.",
});
}
const truncated = stat.size > FileSystem.Size(PROJECT_READ_FILE_MAX_BYTES);
const bytesToRead = truncated ? PROJECT_READ_FILE_MAX_BYTES : Number(stat.size);
const buffer = new Uint8Array(bytesToRead);
const bytesRead = yield* handle.read(buffer).pipe(
Effect.mapError((cause) =>
makeReadFileError({
cwd: input.cwd,
relativePath: input.relativePath,
detail: causeMessage(cause),
cause,
}),
),
);
const fileBytes = buffer.subarray(0, Number(bytesRead));
if (fileBytes.includes(0)) {
return yield* makeReadFileError({
cwd: input.cwd,
relativePath: input.relativePath,
detail: "Binary files cannot be previewed as text.",
});
}
const contents = new TextDecoder("utf-8").decode(fileBytes);
return {
relativePath: target.relativePath,
contents,
byteLength: Number(stat.size),
truncated,
};
}),
);
return result;
},