Public: anyone can read this; the crew can change it.

`forge new --template NAME` starts a forge from a template, listing templates when NAME is missing #13955

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13945-forge-new-template-name-starts-a-forge-f → main 5 commits fork 3 threads · 3 unresolved

  • Merged. scout/13945-forge-new-template-name-starts-a-forge-f was merged into main as bc1cef4.

Review

Sign in to review this change.
7 files changed +180 −2
docs/CLI.md +1
@@ -360,6 +360,7 @@ name is exit 2.
360360
361361 Flags:
362362
363 - `--template [NAME]` — make a *forge* named `<name>` from a template instead, through the door the `/templates` page uses (`POST /api/v1/forges`), and print the link to send. No NAME, or one the forge does not know, lists the templates and exits 2.
363364 - `--private` — only you can see it (public otherwise).
364365 - `--owner org` — make it under an organization you belong to.
365366 - `--root DIR` — the library folder to clone into.
docs/features/new-forge-template.md +12
@@ -6,6 +6,18 @@ The template's code becomes the child's own `forge` repository. It keeps the tem
66
77 Code: `src/spawn/templates.ts` (ids and words), `src/spawn/forge_code.ts` (the fork), `src/actions/spawn.ts` (the checks).
88
9 ## From the command line: forge new --template
10
11 `forge new <name> --template NAME` makes a forge from a template through the same door as the page (`POST /api/v1/forges`), signed in as the CLI is (`forge login`). On success it prints `made forge <name> from <template>` and, on the next line, the claim link to send to whoever will own the forge.
12
13 - `forge new kids --template starter` makes the forge `kids` from Starter app and prints its link.
14 - `forge new kids --template` (no NAME) lists the templates `/templates` offers, one per line with its title and sentence, and exits 2; nothing is made.
15 - A NAME the forge does not know (the door's 404 `unknown_template`) says "there is no such template", lists them the same way, and exits 2.
16 - No forge name (`forge new --template starter`) says what to type and exits 2; nothing is posted.
17 - A refused token (401) exits 3, as for every command that needs `forge login`; 403, 409 and 422 exit 5 with the forge's sentence; anything else exits 1.
18
19 Code: `src/cli/new_template.ts`, the two calls in `src/cli/api.ts` (`templates`, `newForge`). Test: `test/cli-new-template.test.ts`.
20
921 ## The list: /templates
1022
1123 `/templates` lists what a new forge can start from: the built-in templates, then the template repositories you can read. Each row has one sentence and one secondary button, "Start a forge", which opens `/forges/new?template=<id>` with that template chosen. Signed out works too: a stranger lands on the same form with the template kept. `?template=` is accepted only when spawn accepts it (`parseTemplate`); anything else leaves Blank chosen, and it is never echoed. The plan (`do=plan`) shows "It starts from the <b>…</b> template".
src/cli/api.ts +28
@@ -288,6 +288,34 @@ export class ForgeApi {
288288 );
289289 }
290290
291 /** The templates a forge may start from: the public table `/templates` offers. */
292 async templates(): Promise<ApiResult<{ id: string; title: string; says: string }[]>> {
293 const out = await this.call<{ templates?: unknown }>("/api/v1/forges/templates");
294 if (!out.ok) return out;
295 const rows = Array.isArray(out.value.templates) ? out.value.templates : [];
296 return ok(
297 rows.flatMap((r: unknown) => {
outdated

The doc comment above ("the answer's owner and name… Never built from what was typed") belongs to newApp, which now starts after newForge. Put these two methods before that comment block so newApp keeps its doc and templates() gets its own.

298 const t = r as Record<string, unknown>;
299 return typeof t["id"] === "string" && typeof t["title"] === "string"
300 ? [{ id: t["id"], title: t["title"], says: typeof t["says"] === "string" ? t["says"] : "" }]
301 : [];
302 }),
303 );
304 }
305
306 /** `POST /api/v1/forges`, the door the page's form posts to: make a forge from a template. */
307 async newForge(input: { name: string; template: string }): Promise<ApiResult<{ name: string; claimUrl: string | null }>> {
308 const out = await this.call<Record<string, unknown>>("/api/v1/forges", {
309 method: "POST",
310 body: JSON.stringify({ ...input, dryRun: false }),
311 });
312 if (!out.ok) return out;
313 return ok({
314 name: str(out.value["name"]) ?? input.name,
315 claimUrl: str(out.value["claimUrl"]) ?? null,
316 });
317 }
318
291319 /**
292320 * Make an app (`POST /api/v1/apps`). The repo comes back as a `Pin`. The
293321 * API's repo JSON carries no `cloneUrl` today, so the URL is derived from
src/cli/commands/new.ts +3 −1
@@ -6,6 +6,7 @@ import { EXIT } from "../exit.ts";
66 import { inert, type Out } from "../out.ts";
77 import { cloneOne } from "../sync.ts";
88 import { G } from "../../tui/term/screen.ts";
9 import { newFromTemplate } from "../new_template.ts";
910 import type { Command } from "./types.ts";
1011
1112 /** A path part from the forge's answer that cannot climb out of the root. */
@@ -18,6 +19,7 @@ const SAFE_PART = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1819 * and clones nothing.
1920 */
2021 async function newApp(out: Out, args: Args): Promise<number> {
22 if (args.flag("template")) return newFromTemplate(out, args);
2123 const [name, ...words] = args.positional;
2224 if (name === undefined || name.trim() === "") {
2325 out.err("forge new: what is it called? e.g. forge new notes \"a notes app\"");
@@ -73,7 +75,7 @@ export const command: Command = {
7375 name: "new",
7476 usage: {
7577 synopsis: "forge new <name> [words…]",
76 flags: "[--private] [--owner org] [--root DIR]",
78 flags: "[--template [NAME]] [--private] [--owner org] [--root DIR]",
7779 },
7880 run: (out, args) => newApp(out, args),
7981 };
src/cli/main.ts +1 −1
@@ -36,7 +36,7 @@ export { EXIT };
3636 /** Every command by name, built once from `commands/index.ts`. */
3737 const TABLE = new Map(commands.map((c) => [c.name, c]));
3838
39 const VALUE_FLAGS = ["token", "interval", "root", "url", "limit", "repo", "kind", "reason", "owner", "variants", "from", "table", "file", "page"];
39 const VALUE_FLAGS = ["token", "interval", "root", "url", "limit", "repo", "kind", "reason", "owner", "template", "variants", "from", "table", "file", "page"];
4040
4141 export async function main(
4242 argv: readonly string[],
src/cli/new_template.ts added +43
@@ -0,0 +1,43 @@
1 import { ForgeApi } from "./api.ts";
2 import type { Args } from "./args.ts";
3 import { requireConfig } from "./context.ts";
4 import { EXIT } from "./exit.ts";
5 import { inert, type Out } from "./out.ts";
6
7 /** The templates, one per line, as `/templates` offers them. */
8 async function listTemplates(out: Out, api: ForgeApi, why: string): Promise<number> {
9 out.err(`forge new: ${why}`);
10 const got = await api.templates();
11 if (got.ok) for (const t of got.value) out.err(` ${inert(t.id)} ${inert(t.title)}: ${inert(t.says)}`);
12 else out.err(` (could not list them: ${inert(got.error.message)})`);
13 out.err(" forge new <name> --template NAME");
14 return EXIT.usage;
15 }
16
17 /**
18 * `forge new <name> --template NAME`: a forge from a template, through the same door as the
19 * page's form (`POST /api/v1/forges`, `spawnDoor`). No NAME, or one the forge does not know,
20 * lists the templates and exits 2; a known one prints the link to send.
21 */
22 export async function newFromTemplate(out: Out, args: Args): Promise<number> {
23 const loaded = await requireConfig(out);
24 if (typeof loaded === "number") return loaded;
25 const api = new ForgeApi(loaded.url, loaded.token);
26 const template = (args.value("template") ?? "").trim();
27 if (template === "") return listTemplates(out, api, "which template? Pick one:");

This branch (no forge name) has no test; add one asserting exit 2 and that nothing is posted.

28 const name = (args.positional[0] ?? "").trim();
29 if (name === "") {
30 out.err("forge new: what is the forge called? e.g. forge new kids --template starter");
31 return EXIT.usage;
32 }
33 const made = await api.newForge({ name, template });

The 401 to EXIT.notConfigured and 403/409/422 to EXIT.refused mappings are untested; cover at least 401.

34 if (!made.ok) {
35 if (made.error.code === "unknown_template") return listTemplates(out, api, "there is no such template. Pick one:");
36 out.err(`forge new: ${inert(made.error.message)}`);
37 if (made.error.status === 401) return EXIT.notConfigured;
38 return [403, 409, 422].includes(made.error.status) ? EXIT.refused : EXIT.failed;
39 }
40 out.line(`made forge ${inert(made.value.name)} from ${inert(template)}`);
41 if (made.value.claimUrl !== null) out.line(inert(made.value.claimUrl));
42 return EXIT.ok;
43 }
test/cli-new-template.test.ts added +92
@@ -0,0 +1,92 @@
1 /**
2 * `forge new --template`: the list (exit 2), the forge made with its link, and the unknown name.
3 */
4
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { EXIT } from "../src/cli/main.ts";
7
8 const CLI = new URL("../src/cli/main.ts", import.meta.url).pathname;
9
10 describe("forge new --template", () => {
11 let server: ReturnType<typeof Bun.serve>;
12 let base = "";
13 let bodies: Record<string, unknown>[] = [];
14
15 beforeAll(() => {
16 server = Bun.serve({
17 port: 0,
18 hostname: "127.0.0.1",
19 async fetch(req) {
20 const path = new URL(req.url).pathname;
21 if (path === "/api/v1/forges/templates")
22 return Response.json({ templates: [{ id: "blank", title: "Blank", says: "Only the apps." }, { id: "starter", title: "Starter app", says: "A server." }] });
23 if (req.headers.get("authorization") !== "Bearer t0k") return Response.json({ error: "unauthorized" }, { status: 401 });
24 if (req.method === "POST" && path === "/api/v1/forges") {
25 const b = (await req.json()) as Record<string, unknown>;
26 bodies.push(b);
27 if (b["template"] === "boom") return Response.json({ error: "internal", message: "It broke." }, { status: 500 });
28 if (b["template"] !== "starter" && b["template"] !== "blank")
29 return Response.json({ error: "unknown_template", message: "There is no such template." }, { status: 404 });
30 return Response.json({ name: b["name"], claimUrl: "https://kids.example.test/claim#abc" }, { status: 201 });
31 }
32 return Response.json({ error: "not_found" }, { status: 404 });
33 },
34 });
35 base = `http://127.0.0.1:${server.port}`;
36 });
37 afterAll(() => server.stop(true));
38
39 async function forge(args: string[], token = "t0k") {
40 const proc = Bun.spawn(["bun", CLI, ...args], {
41 env: { PATH: process.env["PATH"] ?? "", HOME: process.env["HOME"] ?? "", FORGE_URL: base, FORGE_TOKEN: token, FORGE_KEYCHAIN: "0", NO_COLOR: "1" },
42 stdin: "ignore", stdout: "pipe", stderr: "pipe",
43 });
44 const [out, err, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
45 return { code, out, err };
46 }
47
48 test("no NAME lists the templates, exit 2, makes nothing", async () => {
49 bodies = [];
50 const r = await forge(["new", "kids", "--template"]);
51 expect(r.code).toBe(EXIT.usage);
52 expect(r.err).toContain("starter");
53 expect(r.err).toContain("blank");
54 expect(bodies).toEqual([]);
55 });
56
57 test("an unknown NAME lists them, exit 2", async () => {
58 const r = await forge(["new", "kids", "--template", "nope"]);
59 expect(r.code).toBe(EXIT.usage);
60 expect(r.err).toContain("no such template");
61 expect(r.err).toContain("starter");
62 });
63
64 test("a known NAME makes the forge through the door and prints the link", async () => {
65 bodies = [];
66 const r = await forge(["new", "kids", "--template", "starter"]);
67 expect(r.code).toBe(EXIT.ok);
68 expect(bodies).toEqual([{ name: "kids", template: "starter", dryRun: false }]);
69 expect(r.out).toContain("https://kids.example.test/claim#abc");
70 });
71
72 test("a missing forge name says what to type, exit 2, posts nothing", async () => {
73 bodies = [];
74 const r = await forge(["new", "--template", "starter"]);
75 expect(r.code).toBe(EXIT.usage);
76 expect(r.err).toContain("what is the forge called?");
77 expect(bodies).toEqual([]);
78 });
79
80 test("a token the forge refuses (401) exits as not configured", async () => {
81 bodies = [];
82 const r = await forge(["new", "kids", "--template", "starter"], "wrong");
83 expect(r.code).toBe(EXIT.notConfigured);
84 expect(bodies).toEqual([]);
85 });
86
87 test("a server error exits as failed, with the forge's sentence", async () => {
88 const r = await forge(["new", "kids", "--template", "boom"]);
89 expect(r.code).toBe(EXIT.failed);
90 expect(r.err).toContain("It broke.");
91 });
92 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs