Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions packages/cli/src/backend/filesystem/documents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,26 @@ export function stringifyYaml(value: unknown): string {

export function stringifyToml(value: Record<string, unknown>): string {
const text = Bun.TOML.stringify(value);
if (text === undefined) throw new WayfulError({ message: "cannot serialize TOML metadata." });
if (text === undefined)
throw new WayfulError({
message: "cannot serialize TOML metadata; the record has a value TOML cannot represent.",
});
return text.endsWith("\n") ? text : `${text}\n`;
}

export function parseYaml(text: string, where: string): unknown {
try {
return Bun.YAML.parse(text);
} catch {
throw new WayfulError({ message: `malformed YAML in ${where}.` });
throw new WayfulError({ message: `malformed YAML in ${where}; fix the file and retry.` });
}
}

export function parseToml(text: string, where: string): unknown {
try {
return Bun.TOML.parse(text);
} catch {
throw new WayfulError({ message: `malformed TOML in ${where}.` });
throw new WayfulError({ message: `malformed TOML in ${where}; fix the file and retry.` });
}
}

Expand All @@ -36,12 +39,19 @@ export function parseFrontmatter(
where: string,
): { data: Record<string, unknown>; body: string } {
if (!text.startsWith("---\n"))
throw new WayfulError({ message: `malformed frontmatter in ${where}.` });
throw new WayfulError({
message: `malformed frontmatter in ${where}; fix the file and retry.`,
});
const end = text.indexOf("\n---", 4);
if (end < 0) throw new WayfulError({ message: `malformed frontmatter in ${where}.` });
if (end < 0)
throw new WayfulError({
message: `malformed frontmatter in ${where}; fix the file and retry.`,
});
const data = parseYaml(text.slice(4, end), where);
if (!data || typeof data !== "object" || Array.isArray(data))
throw new WayfulError({ message: `malformed frontmatter in ${where}.` });
throw new WayfulError({
message: `malformed frontmatter in ${where}; fix the file and retry.`,
});
return { data: data as Record<string, unknown>, body: text.slice(end + 4).replace(/^\n/, "") };
}

Expand All @@ -64,7 +74,9 @@ export function writeAtomic(
): Effect.Effect<void, WayfulError> {
return Effect.gen(function* () {
const tmp = `${path}.tmp-${process.pid}-${yield* Clock.currentTimeMillis}-${(yield* Random.next).toString(36).slice(2)}`;
const onError = new WayfulError({ message: `cannot write ${path}.` });
const onError = new WayfulError({
message: `cannot write '${path}'; check that its directory exists and is writable.`,
});
yield* fs.writeFileString(tmp, text).pipe(Effect.mapError(() => onError));
yield* fs.rename(tmp, path).pipe(Effect.mapError(() => onError));
});
Expand Down
11 changes: 8 additions & 3 deletions packages/cli/src/backend/filesystem/layer/ops/goal.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Effect, FileSystem, Path } from "effect";

import { WayfulError } from "@domain/errors";
import type { GoalRecord, NewGoalRecord } from "@domain/model";
import type { MapHandle } from "@backend/MapStore";
import { decodeGoal } from "@backend/filesystem/decode";
Expand All @@ -13,7 +12,13 @@ import {
writeAtomic,
} from "@backend/filesystem/documents";
import { goalFile, goalsDir, mapDir } from "@backend/filesystem/paths";
import { accessError, collect, fail, goalToDocument } from "@backend/filesystem/layer/records";
import {
accessError,
collect,
fail,
goalToDocument,
readDirError,
} from "@backend/filesystem/layer/records";

export function makeGoalOps(fs: FileSystem.FileSystem, path: Path.Path) {
return {
Expand All @@ -22,7 +27,7 @@ export function makeGoalOps(fs: FileSystem.FileSystem, path: Path.Path) {
const dir = goalsDir(path, mapDir(path, map.project.root, map.name));
const files = yield* fs
.readDirectory(dir)
.pipe(Effect.mapError(() => new WayfulError({ message: "cannot read goals." })));
.pipe(Effect.mapError(() => readDirError(dir, "goals")));
const filenames = files.filter((file) => file.endsWith(".md")).toSorted();
const result = yield* collect(
filenames,
Expand Down
8 changes: 5 additions & 3 deletions packages/cli/src/backend/filesystem/layer/ops/map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
writeAtomic,
} from "@backend/filesystem/documents";
import { goalFile, goalsDir, mapDir, mapFile, mapsDir, stepsDir } from "@backend/filesystem/paths";
import { accessError, collect, fail } from "@backend/filesystem/layer/records";
import { accessError, collect, fail, readDirError } from "@backend/filesystem/layer/records";

export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) {
const openMapHandle = (
Expand Down Expand Up @@ -79,7 +79,7 @@ export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) {
if (!exists) return { records: [], errors: [] };
const entries = yield* fs
.readDirectory(dir)
.pipe(Effect.mapError(() => new WayfulError({ message: "cannot read project maps." })));
.pipe(Effect.mapError(() => readDirError(dir, "project maps")));
const names: string[] = [];
for (const name of entries.toSorted()) {
const stat = yield* fs
Expand Down Expand Up @@ -126,7 +126,9 @@ export function makeMapOps(fs: FileSystem.FileSystem, path: Path.Path) {
const dir = mapDir(path, project.root, name);
const exists = yield* fs.exists(dir).pipe(Effect.mapError(accessError));
if (exists) return yield* fail(`map '${name}' already exists.`);
const onCreateError = new WayfulError({ message: `cannot create map '${name}'.` });
const onCreateError = new WayfulError({
message: `cannot create map '${name}' under '${dir}'; check that the directory is writable.`,
});
yield* fs
.makeDirectory(stepsDir(path, dir), { recursive: true })
.pipe(Effect.mapError(() => onCreateError));
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/src/backend/filesystem/layer/ops/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ export function makeProjectOps(fs: FileSystem.FileSystem, path: Path.Path) {
const wayfulDir = path.join(root, ".wayful");
const exists = yield* fs.exists(wayfulDir).pipe(Effect.mapError(accessError));
if (exists) return yield* fail("Wayful state already exists; refusing to overwrite it.");
const onCreateError = new WayfulError({ message: `cannot create ${root}.` });
const onCreateError = new WayfulError({
message: `cannot create '${root}'; check that the parent directory exists and is writable.`,
});
yield* fs
.makeDirectory(typesDir(path, root), { recursive: true })
.pipe(Effect.mapError(() => onCreateError));
Expand Down
12 changes: 9 additions & 3 deletions packages/cli/src/backend/filesystem/layer/ops/step.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,13 @@ import {
writeAtomic,
} from "@backend/filesystem/documents";
import { mapDir, mapFile, stepFile, stepsDir } from "@backend/filesystem/paths";
import { accessError, collect, fail, stepToDocument } from "@backend/filesystem/layer/records";
import {
accessError,
collect,
fail,
readDirError,
stepToDocument,
} from "@backend/filesystem/layer/records";

export function makeStepOps(fs: FileSystem.FileSystem, path: Path.Path) {
// Guards each map's `step_id_counter` read-modify-write so that two
Expand All @@ -37,7 +43,7 @@ export function makeStepOps(fs: FileSystem.FileSystem, path: Path.Path) {
const raw = (yield* liftSync(() => parseToml(text, file))) as Record<string, unknown>;
const counter = raw.step_id_counter;
if (!Number.isInteger(counter) || (counter as number) < 1)
return yield* fail("malformed map metadata.");
return yield* fail(`map metadata in ${file} is missing a positive step_id_counter.`);
yield* writeAtomic(
fs,
file,
Expand All @@ -52,7 +58,7 @@ export function makeStepOps(fs: FileSystem.FileSystem, path: Path.Path) {
const dir = stepsDir(path, mapDir(path, map.project.root, map.name));
const files = yield* fs
.readDirectory(dir)
.pipe(Effect.mapError(() => new WayfulError({ message: "cannot read steps." })));
.pipe(Effect.mapError(() => readDirError(dir, "steps")));
const filenames = files.filter((file) => file.endsWith(".md")).toSorted();
const result = yield* collect(
filenames,
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/backend/filesystem/layer/ops/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { ProjectHandle } from "@backend/ProjectStore";
import { decodeType } from "@backend/filesystem/decode";
import { liftSync, parseFrontmatter, readTextFile } from "@backend/filesystem/documents";
import { typeFile, typesDir } from "@backend/filesystem/paths";
import { accessError, collect, fail } from "@backend/filesystem/layer/records";
import { accessError, collect, fail, readDirError } from "@backend/filesystem/layer/records";

export function makeTypeOps(fs: FileSystem.FileSystem, path: Path.Path) {
const readType = (
Expand All @@ -30,7 +30,7 @@ export function makeTypeOps(fs: FileSystem.FileSystem, path: Path.Path) {
const dir = typesDir(path, project.root);
const files = yield* fs
.readDirectory(dir)
.pipe(Effect.mapError(() => new WayfulError({ message: "cannot read project types." })));
.pipe(Effect.mapError(() => readDirError(dir, "project types")));
const names = files
.filter((file) => file.endsWith(".md"))
.map((file) => file.slice(0, -3))
Expand Down
12 changes: 11 additions & 1 deletion packages/cli/src/backend/filesystem/layer/records.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,17 @@ import {
// `yield* fail(...)` rather than call a throwing helper directly.
export const fail = (message: string) => Effect.fail(new WayfulError({ message }));

export const accessError = () => new WayfulError({ message: "cannot access filesystem." });
export const accessError = () =>
new WayfulError({
message:
"cannot access a project file; check that the project exists and you have permission to read it.",
});

/** The named error a collection read produces when its directory cannot be listed. */
export const readDirError = (dir: string, what: string) =>
new WayfulError({
message: `cannot read ${what} from '${dir}'; check that it exists and you have permission to read it.`,
});

/**
* Runs `decode` for each item in `items`, collecting successes and turning
Expand Down
75 changes: 75 additions & 0 deletions packages/cli/src/backend/github/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
createIssue,
ensureLabel,
ensureLabels,
getIssue,
listBlockedBy,
listIssues,
removeBlockedBy,
Expand Down Expand Up @@ -85,6 +86,80 @@ describe("verifyAccess", () => {
});
});

describe("github failures name the problem and the remedy", () => {
async function failure(status: number, message: string) {
const layer = stubGithubHttp(() => jsonResponse(status, { message }));
return Effect.runPromise(
listIssues(repo, secretToken, { labels: ["wayful:map"] }).pipe(
Effect.flip,
Effect.provide(layer),
),
);
}

test("an invalid credential says so and how to supply a working one", async () => {
const error = await failure(401, "Bad credentials");
expect(error.message).toContain("acme/widgets");
expect(error.message).toContain("invalid or expired");
expect(error.message).toMatch(/gh auth login|GH_TOKEN/);
});

test("a credential that cannot reach the repo says so without suggesting a new sign-in", async () => {
const error = await failure(403, "Resource not accessible by integration");
expect(error.message).toContain("cannot access acme/widgets");
expect(error.message).not.toContain("gh auth login");
expect(error.message).not.toMatch(/sign in/i);
});

test("a missing repository names it and says it is not found or not visible", async () => {
const error = await failure(404, "Not Found");
expect(error.message).toContain("acme/widgets");
expect(error.message).toMatch(/not exist|not be visible/);
});

test("an unexpected status keeps GitHub's own explanation", async () => {
const error = await failure(422, "Validation Failed");
expect(error.message).toContain("422");
expect(error.message).toContain("Validation Failed");
});

test("a missing resource names the resource and its repository", async () => {
const layer = stubGithubHttp(() => jsonResponse(404, { message: "Not Found" }));
const error = await Effect.runPromise(
getIssue(repo, secretToken, 7).pipe(Effect.flip, Effect.provide(layer)),
);
expect(error.message).toContain("issue #7");
expect(error.message).toContain("acme/widgets");
});
});

describe("verifyAccess failures", () => {
async function failure(status: number, body: unknown) {
const layer = stubGithubHttp(() => jsonResponse(status, body));
return Effect.runPromise(
verifyAccess(repo, secretToken).pipe(Effect.flip, Effect.provide(layer)),
);
}

test("a 401 reports an invalid or expired credential, not a permissions problem", async () => {
const error = await failure(401, { message: "Bad credentials" });
expect(error.message).toContain("invalid or expired");
expect(error.message).toMatch(/gh auth login|GH_TOKEN/);
});

test("a 403 reports an access problem without suggesting a new sign-in", async () => {
const error = await failure(403, { message: "Forbidden" });
expect(error.message).toContain("cannot access");
expect(error.message).not.toMatch(/gh auth login|sign in/i);
});

test("a 404 names the repository as not found or not visible", async () => {
const error = await failure(404, { message: "Not Found" });
expect(error.message).toContain("acme/widgets");
expect(error.message).toMatch(/not exist|not be visible/);
});
});

describe("ensureLabel", () => {
test("succeeds when the label is created", async () => {
const layer = stubGithubHttp((request) => {
Expand Down
Loading
Loading