@niwa-labs/forge 0.0.0-stage → 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,92 @@
1
+ // The push reaction: a built-in workflow of forge and git, offered only when it is asked for, that
2
+ // answers which worktrees a push to their base branch left behind.
3
+
4
+ import { afterEach, expect, test } from "bun:test";
5
+ import { realpathSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+
8
+ import { eventually, git, tempDir, workflow } from "@niwa-labs/testing";
9
+
10
+ import { forgeRepoSync, forgeRepoWatch } from "../src/index.ts";
11
+ import { sha } from "./fake-gitlab.ts";
12
+ import { BILLING, forgeHost } from "./support.ts";
13
+ import type { ForgeHost } from "./support.ts";
14
+
15
+ const hosts: ForgeHost[] = [];
16
+ afterEach(async () => {
17
+ for (const host of hosts.splice(0)) await host.stop();
18
+ });
19
+
20
+ /** A git repository on `main` with one commit. */
21
+ async function repository(remote?: string): Promise<string> {
22
+ const dir = realpathSync(await tempDir("checkout"));
23
+ const run = (...args: string[]) => {
24
+ const done = Bun.spawnSync(["git", ...args], { cwd: dir, env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } });
25
+ if (done.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${done.stderr.toString()}`);
26
+ };
27
+ run("init", "-q", "-b", "main");
28
+ writeFileSync(join(dir, "README"), "billing\n");
29
+ run("add", "README");
30
+ run("commit", "-q", "-m", "Start");
31
+ if (remote !== undefined) run("remote", "add", "origin", remote);
32
+ return dir;
33
+ }
34
+
35
+ const installations = async (host: ForgeHost) => ((await host.niwa.call("workflow.installation.list" as never, {} as never)) as { items: unknown[] }).items;
36
+
37
+ test("on a push to a branch, the run names the worktrees of the repository's checkouts made from that branch", async () => {
38
+ const checkout = await repository();
39
+ const other = await repository();
40
+ const host = await forgeHost({
41
+ before: [git({ cleanup: false })],
42
+ after: [workflow()],
43
+ forge: { pushReaction: { checkouts: { "gitlab.example.com/acme/billing": [checkout] } } },
44
+ });
45
+ hosts.push(host);
46
+ await eventually(async () => (await installations(host)).length === 1, 20_000, "the push reaction was not installed");
47
+
48
+ const create = (repo: string) => host.niwa.call("git.worktree.create" as never, { repo, base: "main", description: "work" } as never) as Promise<{ id: string }>;
49
+ const ours = await create(checkout);
50
+ await create(other);
51
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
52
+ host.server.event(host.billing, { action_name: "pushed to", push_data: { ref: "main", ref_type: "branch", commit_from: sha("main-1"), commit_to: sha("main-2") } });
53
+ host.server.event(host.billing, { action_name: "pushed new", push_data: { ref: "v1.0", ref_type: "tag", commit_from: null, commit_to: sha("main-2") } });
54
+ await host.niwa.call(forgeRepoSync, { repo: BILLING });
55
+
56
+ const finished = async () => (await host.records(["workflow.run.finished"])).map((one) => (one.data as { outcome: { result?: unknown } }).outcome.result);
57
+ await eventually(async () => (await finished()).length >= 1, 20_000, "the push reaction did not finish");
58
+ expect(await finished()).toEqual([{ ref: "main", behind: [ours.id] }]);
59
+ }, 60_000);
60
+
61
+ test("without a list of checkouts, the run finds the worktrees whose base pushes to the repository that was pushed to", async () => {
62
+ const cloned = await repository("https://gitlab.example.com/acme/billing.git");
63
+ const elsewhere = await repository("https://gitlab.example.com/acme/shipping.git");
64
+ const unconnected = await repository();
65
+ const host = await forgeHost({ before: [git({ cleanup: false })], after: [workflow()], forge: { pushReaction: {} } });
66
+ hosts.push(host);
67
+ await eventually(async () => (await installations(host)).length === 1, 20_000, "the push reaction was not installed");
68
+
69
+ const create = (repo: string) => host.niwa.call("git.worktree.create" as never, { repo, base: "main", description: "work" } as never) as Promise<{ id: string }>;
70
+ const ours = await create(cloned);
71
+ await create(elsewhere);
72
+ await create(unconnected);
73
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
74
+ host.server.event(host.billing, { action_name: "pushed to", push_data: { ref: "main", ref_type: "branch", commit_from: sha("main-1"), commit_to: sha("main-2") } });
75
+ await host.niwa.call(forgeRepoSync, { repo: BILLING });
76
+
77
+ const finished = async () => (await host.records(["workflow.run.finished"])).map((one) => (one.data as { outcome: { result?: unknown } }).outcome.result);
78
+ await eventually(async () => (await finished()).length >= 1, 20_000, "the push reaction did not finish");
79
+ expect(await finished()).toEqual([{ ref: "main", behind: [ours.id] }]);
80
+ }, 60_000);
81
+
82
+ test("without the option nothing is offered, and a host without the workflow module serves", async () => {
83
+ const bare = await forgeHost();
84
+ hosts.push(bare);
85
+ const described = (await bare.niwa.describe()).actions.map((one) => one.name as string);
86
+ expect(described).not.toContain("forge.push.config");
87
+
88
+ const withWorkflow = await forgeHost({ after: [workflow()] });
89
+ hosts.push(withWorkflow);
90
+ await new Promise((resolve) => setTimeout(resolve, 200));
91
+ expect(await installations(withWorkflow)).toEqual([]);
92
+ });
@@ -0,0 +1,144 @@
1
+ // The query builders of the forge records: the records of one pull request, commit or repository, as
2
+ // a script waits for them, a reader reads them and a handler subscribes to them. A filter is held to
3
+ // the data the record's own schema gives, so a path that names no field of it cannot pass.
4
+
5
+ import { expect, test } from "bun:test";
6
+
7
+ import { resolveQuery } from "@niwa-labs/core";
8
+ import type { TypeQuery } from "@niwa-labs/core";
9
+
10
+ import {
11
+ ChecksObserved,
12
+ JobObserved,
13
+ MergeArmed,
14
+ MergeDisarmed,
15
+ MergeSettled,
16
+ PipelineObserved,
17
+ PrClosed,
18
+ PrComment,
19
+ PrHead,
20
+ PrMerged,
21
+ PrOpened,
22
+ PrReview,
23
+ PrUpdated,
24
+ Pushed,
25
+ } from "../src/record-types.ts";
26
+ import {
27
+ jobsOf,
28
+ mergeArmed,
29
+ mergeDisarmed,
30
+ mergeSettled,
31
+ pipelineOf,
32
+ pipelinesOfPr,
33
+ prChecks,
34
+ prClosed,
35
+ prComment,
36
+ prHead,
37
+ prMerged,
38
+ prOpened,
39
+ prReview,
40
+ prUpdated,
41
+ pushed,
42
+ } from "../src/queries.ts";
43
+ import type { PrKey } from "../src/queries.ts";
44
+ import { sha } from "./fake-gitlab.ts";
45
+
46
+ const repo = { host: "gitlab.example.com", path: "acme/billing", projectId: 42 };
47
+ const pr = { repo, number: 7 };
48
+ const other = { repo, number: 8 };
49
+ const head = sha("topic-1");
50
+ const source = { kind: "observed", version: 1 } as const;
51
+
52
+ /** The value at a dotted path of data, as the journal's equality filter reads it. */
53
+ function at(data: unknown, path: string): unknown {
54
+ return path.split(".").reduce<unknown>((value, key) => (value as Record<string, unknown> | undefined)?.[key], data);
55
+ }
56
+
57
+ /** The names of the types a query holds, as the journal reads them. */
58
+ function names(query: TypeQuery<any>): string[] {
59
+ return (resolveQuery(query).types ?? []).map(String);
60
+ }
61
+
62
+ /** Whether data answers the filter of a query: equality on every path. */
63
+ function answers(query: TypeQuery<any>, data: unknown): boolean {
64
+ return Object.entries(resolveQuery(query).filter ?? {}).every(([path, value]) => at(data, path) === value);
65
+ }
66
+
67
+ const prData = { pr: { repo, number: 7 } };
68
+ const pipelineData = { repo, pipeline: 5, kind: "merge-result", ref: "refs/merge-requests/7/merge", sourceSha: head, state: "running", pr: 7, source };
69
+
70
+ test("a pull request's records are queries of their type, filtered on its repository and number", () => {
71
+ const filter = { "pr.repo.host": repo.host, "pr.repo.path": repo.path, "pr.number": 7 };
72
+ expect(prHead(pr)).toEqual({ types: [PrHead], filter });
73
+ expect(prMerged(pr)).toEqual({ types: [PrMerged], filter });
74
+ expect(prClosed(pr)).toEqual({ types: [PrClosed], filter });
75
+ expect(prChecks(pr)).toEqual({ types: [ChecksObserved], filter });
76
+ expect(names(prHead(pr))).toEqual(["forge.pr.head"]);
77
+ expect(resolveQuery(prHead(pr)).filter).toEqual(filter);
78
+ expect(names(mergeArmed(pr))).toEqual(["forge.pr.merge.armed"]);
79
+ });
80
+
81
+ test("every pull request builder holds a record of its pull request and no other", () => {
82
+ const cases: Array<[TypeQuery<any>, (key: PrKey) => TypeQuery<any>, unknown]> = [
83
+ [prOpened(pr), prOpened, PrOpened],
84
+ [prUpdated(pr), prUpdated, PrUpdated],
85
+ [prHead(pr), prHead, PrHead],
86
+ [prReview(pr), prReview, PrReview],
87
+ [prComment(pr), prComment, PrComment],
88
+ [prMerged(pr), prMerged, PrMerged],
89
+ [prClosed(pr), prClosed, PrClosed],
90
+ [prChecks(pr), prChecks, ChecksObserved],
91
+ [mergeArmed(pr), mergeArmed, MergeArmed],
92
+ [mergeDisarmed(pr), mergeDisarmed, MergeDisarmed],
93
+ [mergeSettled(pr), mergeSettled, MergeSettled],
94
+ ];
95
+ for (const [query, build, type] of cases) {
96
+ expect(query.types).toEqual([type as never]);
97
+ expect(answers(query, prData)).toBe(true);
98
+ expect(answers(build(other), prData)).toBe(false);
99
+ expect(answers(build({ repo: { ...repo, path: "acme/other" }, number: 7 }), prData)).toBe(false);
100
+ }
101
+ });
102
+
103
+ test("a repository given with its project id is read for its name only", () => {
104
+ expect(prHead({ repo: { host: repo.host, path: repo.path }, number: 7 })).toEqual(prHead(pr));
105
+ });
106
+
107
+ test("the pipelines of a commit are filtered on the commit, and on the kind when one is asked", () => {
108
+ const all = pipelineOf({ repo, sha: head });
109
+ expect(all).toEqual({ types: [PipelineObserved], filter: { "repo.host": repo.host, "repo.path": repo.path, sourceSha: head } });
110
+ const merged = pipelineOf({ repo, sha: head, kind: "merge-result" });
111
+ expect(resolveQuery(merged).filter).toEqual({ "repo.host": repo.host, "repo.path": repo.path, sourceSha: head, kind: "merge-result" });
112
+ expect(answers(all, pipelineData)).toBe(true);
113
+ expect(answers(merged, pipelineData)).toBe(true);
114
+ expect(answers(pipelineOf({ repo, sha: head, kind: "head" }), pipelineData)).toBe(false);
115
+ expect(answers(pipelineOf({ repo, sha: sha("another") }), pipelineData)).toBe(false);
116
+ });
117
+
118
+ test("the pipelines of a pull request are filtered on the number the server gave the pipeline", () => {
119
+ expect(answers(pipelinesOfPr(pr), pipelineData)).toBe(true);
120
+ expect(answers(pipelinesOfPr(other), pipelineData)).toBe(false);
121
+ });
122
+
123
+ test("the jobs of a pipeline, and the pushes to a repository or a ref", () => {
124
+ const job = { repo, pipeline: 5, job: 9, name: "test", stage: "test", state: "running", source };
125
+ expect(jobsOf({ repo, pipeline: 5 }).types).toEqual([JobObserved]);
126
+ expect(answers(jobsOf({ repo, pipeline: 5 }), job)).toBe(true);
127
+ expect(answers(jobsOf({ repo, pipeline: 6 }), job)).toBe(false);
128
+
129
+ const push = { repo, ref: "main", refType: "branch", after: head, source };
130
+ expect(pushed(repo).types).toEqual([Pushed]);
131
+ expect(answers(pushed(repo), push)).toBe(true);
132
+ expect(answers(pushed(repo, "main"), push)).toBe(true);
133
+ expect(answers(pushed(repo, "release"), push)).toBe(false);
134
+ });
135
+
136
+ test("a name that is not a repository, a number or a commit is refused when the query is made", () => {
137
+ expect(() => prHead({ repo: { host: "https://gitlab.example.com", path: "acme/billing" }, number: 7 })).toThrow();
138
+ expect(() => prHead({ repo, number: 0 })).toThrow();
139
+ expect(() => prHead({ repo, number: 1.5 })).toThrow();
140
+ expect(() => pipelineOf({ repo, sha: "abc" })).toThrow();
141
+ expect(() => pipelinesOfPr({ repo: { host: repo.host, path: "billing" }, number: 1 })).toThrow();
142
+ expect(() => jobsOf({ repo, pipeline: 0 })).toThrow();
143
+ expect(() => pushed(repo, "")).toThrow();
144
+ });
@@ -0,0 +1,185 @@
1
+ // The query builders and flow helpers in a real workflow script, on a host that runs the workflow
2
+ // module over a fake GitLab server: the script waits for and reads forge records by the builders and
3
+ // gets the data typed, and the check of the script follows a builder to the record it names.
4
+ //
5
+ // A script here imports the module by the path of its entry file; a stored script imports it by the
6
+ // name of the package, as a delivery script in a repository that depends on forge does.
7
+
8
+ import { afterEach, expect, test } from "bun:test";
9
+ import { realpathSync } from "node:fs";
10
+ import { mkdir, symlink, writeFile } from "node:fs/promises";
11
+ import { join } from "node:path";
12
+
13
+ import { eventually, requests, timers, workflow } from "@niwa-labs/testing";
14
+
15
+ import { forgeRepoSync, forgeRepoWatch } from "../src/index.ts";
16
+ import { sha } from "./fake-gitlab.ts";
17
+ import { BILLING, forgeHost, openMr } from "./support.ts";
18
+ import type { ForgeHost } from "./support.ts";
19
+
20
+ const hosts: ForgeHost[] = [];
21
+ afterEach(async () => {
22
+ for (const host of hosts.splice(0)) await host.stop();
23
+ }, 60_000);
24
+
25
+ const RECORDS = join(import.meta.dir, "..", "src", "records.ts");
26
+ const FLOW = join(import.meta.dir, "..", "src", "flow.ts");
27
+
28
+ async function served(): Promise<ForgeHost> {
29
+ const host = await forgeHost({ after: [requests(), timers([]), workflow()] });
30
+ hosts.push(host);
31
+ await host.niwa.call(forgeRepoWatch, { repo: BILLING });
32
+ return host;
33
+ }
34
+
35
+ async function scriptIn(host: ForgeHost, name: string, lines: readonly string[]): Promise<string> {
36
+ await mkdir(host.home, { recursive: true });
37
+ const file = join(host.home, name);
38
+ await writeFile(file, lines.join("\n"));
39
+ return file;
40
+ }
41
+
42
+ const call = (host: ForgeHost, name: string, input: unknown): Promise<any> => host.niwa.call(name as never, input as never) as Promise<any>;
43
+ const sync = (host: ForgeHost) => host.niwa.call(forgeRepoSync, { repo: BILLING });
44
+
45
+ async function resultOf(host: ForgeHost, run: string): Promise<unknown> {
46
+ await eventually(
47
+ async () => (await host.niwa.records.read({ types: ["workflow.run.finished"], filter: { run } })).length === 1,
48
+ 20_000,
49
+ "the run should finish",
50
+ );
51
+ const [finished] = await host.niwa.records.read({ types: ["workflow.run.finished"], filter: { run } });
52
+ return (finished?.data as { outcome: unknown }).outcome;
53
+ }
54
+
55
+ /** Wait until the run is suspended on a record. */
56
+ const suspended = (host: ForgeHost) =>
57
+ eventually(async () => (await host.niwa.records.read({ types: ["niwa.invocation.state"], filter: { state: "waiting" } })).length > 0, 20_000, "the run should wait");
58
+
59
+ const REPO = JSON.stringify({ host: BILLING.host, path: BILLING.path });
60
+
61
+ test("a script reads a pipeline's records and waits for a pull request's merge by builders, with the data typed", async () => {
62
+ const host = await served();
63
+ const mr = openMr(host);
64
+ const pipeline = host.server.pipeline(host.billing, { sha: sha("topic-1"), ref: "refs/merge-requests/7/head", source: "merge_request_event" });
65
+ await sync(host);
66
+ const file = await scriptIn(host, "merged.ts", [
67
+ `import { pipelineOf, prMerged } from ${JSON.stringify(RECORDS)};`,
68
+ `const repo = ${REPO};`,
69
+ 'export default workflow({ uses: ["niwa.records.read"], output: z.json() }, async () => {',
70
+ ` const seen = await read.records(pipelineOf({ repo, sha: ${JSON.stringify(sha("topic-1"))} }));`,
71
+ " const states: string[] = seen.records.map((row) => row.data.state);",
72
+ ' const merged = await wait(prMerged({ repo, number: 7 }), { from: seen.next, timeout: "5m" });',
73
+ ' if ("timedOut" in merged) return { states, merged: false, mergeSha: null };',
74
+ " const mergeSha: string | undefined = merged.data.mergeSha;",
75
+ " return { states, merged: true, mergeSha: mergeSha ?? null };",
76
+ "});",
77
+ ]);
78
+ expect((await call(host, "workflow.check", { file })).errors).toEqual([]);
79
+ const { run } = await call(host, "workflow.start", { file });
80
+ await suspended(host);
81
+ Object.assign(mr, { state: "merged", merge_commit_sha: sha("merge-7") });
82
+ pipeline.status = "success";
83
+ host.server.event(host.billing, { action_name: "accepted", target_type: "MergeRequest", target_iid: 7, author: { username: "marge" } });
84
+ await sync(host);
85
+ expect(await resultOf(host, run)).toEqual({ status: "done", result: { states: ["running"], merged: true, mergeSha: sha("merge-7") } });
86
+ }, 60_000);
87
+
88
+ test("flow helpers imported by a script wait for the head of a pull request and for a pipeline through the same queries", async () => {
89
+ const host = await served();
90
+ const mr = openMr(host);
91
+ await sync(host);
92
+ const file = await scriptIn(host, "flow.ts", [
93
+ `import { untilHeadMoved, untilPipeline } from ${JSON.stringify(FLOW)};`,
94
+ `const repo = ${REPO};`,
95
+ `export default workflow({ uses: ["niwa.records.read", "forge.pipeline.read@gitlab.example.com/acme/billing"], output: z.json() }, async () => {`,
96
+ ' const moved = await untilHeadMoved("head", { pr: { repo, number: 7 }, timeout: "5m" });',
97
+ " if (!moved.moved) return { moved: false, head: null, previous: null, ci: null };",
98
+ ` const ci = await untilPipeline("ci", { repo, sha: moved.head, deadline: "5m" });`,
99
+ " return { moved: true, head: moved.head, previous: moved.previous ?? null, ci: ci.outcome };",
100
+ "});",
101
+ ]);
102
+ expect((await call(host, "workflow.check", { file })).errors).toEqual([]);
103
+ const { run } = await call(host, "workflow.start", { file });
104
+ await suspended(host);
105
+ mr.sha = sha("topic-2");
106
+ host.server.pipeline(host.billing, { sha: sha("topic-2"), ref: "refs/merge-requests/7/head", source: "merge_request_event", status: "success" });
107
+ await sync(host);
108
+ expect(await resultOf(host, run)).toEqual({ status: "done", result: { moved: true, head: sha("topic-2"), previous: sha("topic-1"), ci: "green" } });
109
+ }, 60_000);
110
+
111
+ test("the check of a script holds the data of a builder's wait to the record's schema", async () => {
112
+ const host = await served();
113
+ const script = (access: string) =>
114
+ scriptIn(host, `check-${access.length}.ts`, [
115
+ `import { prHead } from ${JSON.stringify(RECORDS)};`,
116
+ `const repo = ${REPO};`,
117
+ "export default workflow({ output: z.json() }, async () => {",
118
+ ' const moved = await wait(prHead({ repo, number: 7 }), { timeout: "1m" });',
119
+ ` return "timedOut" in moved ? null : ${access};`,
120
+ "});",
121
+ ]);
122
+ expect((await call(host, "workflow.check", { file: await script("moved.data.head") })).errors).toEqual([]);
123
+ const wrong = (await call(host, "workflow.check", { file: await script("moved.data.tip") })).errors as Array<{ code: string }>;
124
+ expect(wrong.map((one) => one.code)).toEqual(["TS2339"]);
125
+ }, 60_000);
126
+
127
+ /**
128
+ * Register a script written where the package is installed, as a delivery script in a repository that
129
+ * depends on forge is: the stored copy imports `@niwa-labs/forge/flow` by the name of the package.
130
+ */
131
+ async function registeredByName(host: ForgeHost, name: string, lines: readonly string[]): Promise<string> {
132
+ const dir = join(host.home, "by-name");
133
+ await mkdir(join(dir, "node_modules", "@niwa-labs"), { recursive: true });
134
+ await symlink(realpathSync(join(import.meta.dir, "..")), join(dir, "node_modules", "@niwa-labs", "forge"), "dir").catch(() => undefined);
135
+ const file = join(dir, name);
136
+ await writeFile(file, lines.join("\n"));
137
+ return (await call(host, "workflow.register", { file })).id;
138
+ }
139
+
140
+ test("a stored script imports forge's flow helpers by the name of the package", async () => {
141
+ const host = await served();
142
+ const id = await registeredByName(host, "land.ts", [
143
+ 'import { durationMs, land } from "@niwa-labs/forge/flow";',
144
+ 'export default workflow({ description: "Land with the forge helpers", output: z.json() }, async () => ({ minute: durationMs("1m"), land: typeof land }));',
145
+ ]);
146
+ const { run } = await call(host, "workflow.start", { id });
147
+ expect(await resultOf(host, run)).toEqual({ status: "done", result: { minute: 60_000, land: "function" } });
148
+ }, 60_000);
149
+
150
+ test("an automatic landing in a stored script ends when the merge is recorded, not when its other waits time out", async () => {
151
+ const host = await served();
152
+ const mr = openMr(host);
153
+ await sync(host);
154
+ const id = await registeredByName(host, "land-auto.ts", [
155
+ 'import { land } from "@niwa-labs/forge/flow";',
156
+ `const repo = ${REPO};`,
157
+ 'export default workflow({ description: "Land when the pipeline passes", uses: ["niwa.records.read", "forge.pr.merge@gitlab.example.com/acme/billing/pr/7", "forge.pr.read@gitlab.example.com/acme/billing/pr/7"], output: z.json() }, async () =>',
158
+ ` land("land", { pr: { repo, number: 7 }, expectHead: ${JSON.stringify(sha("topic-1"))}, method: "merge", auto: true }));`,
159
+ ]);
160
+ const { run } = await call(host, "workflow.start", { id });
161
+ await suspended(host);
162
+ expect(mr.merge_when_pipeline_succeeds).toBe(true);
163
+ Object.assign(mr, { state: "merged", merge_commit_sha: sha("merge-7") });
164
+ host.server.event(host.billing, { action_name: "accepted", target_type: "MergeRequest", target_iid: 7, author: { username: "marge" } });
165
+ await sync(host);
166
+ expect(await resultOf(host, run)).toEqual({ status: "done", result: { outcome: "merged", sha: sha("merge-7") } });
167
+ }, 60_000);
168
+
169
+ test("a stored script waits until a pull request is merged or closed, whichever is recorded first", async () => {
170
+ const host = await served();
171
+ const mr = openMr(host);
172
+ await sync(host);
173
+ const id = await registeredByName(host, "ended.ts", [
174
+ 'import { untilPrEnded } from "@niwa-labs/forge/flow";',
175
+ `const repo = ${REPO};`,
176
+ 'export default workflow({ description: "Wait for the end of a pull request", uses: ["niwa.records.read"], output: z.json() }, async () =>',
177
+ ' untilPrEnded("ended", { pr: { repo, number: 7 }, timeout: "1h" }));',
178
+ ]);
179
+ const { run } = await call(host, "workflow.start", { id });
180
+ await suspended(host);
181
+ mr.state = "closed";
182
+ host.server.event(host.billing, { action_name: "closed", target_type: "MergeRequest", target_iid: 7, author: { username: "marge" } });
183
+ await sync(host);
184
+ expect(await resultOf(host, run)).toMatchObject({ status: "done", result: { ended: "closed", by: "marge" } });
185
+ }, 60_000);
@@ -0,0 +1,109 @@
1
+ // What the forge tests share: a host with the module installed over a fake GitLab server, the token
2
+ // in the host's secrets, clients that hold a grant, and the module's actions as it built them.
3
+
4
+ import { chmodSync, mkdirSync, writeFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+
7
+ import { grant, principalOf } from "@niwa-labs/core";
8
+ import type { Action, StoredRecord } from "@niwa-labs/core";
9
+ import { plugin } from "@niwa-labs/plugin";
10
+ import type { Plugin } from "@niwa-labs/plugin";
11
+ import { connect, createNiwa, tempHome } from "@niwa-labs/testing";
12
+ import type { NiwaApi } from "@niwa-labs/testing";
13
+
14
+ import { forge, secret } from "../src/index.ts";
15
+ import type { ForgeOptions } from "../src/index.ts";
16
+ import { FakeGitLab, sha } from "./fake-gitlab.ts";
17
+ import type { FakeProject } from "./fake-gitlab.ts";
18
+
19
+ export const HOST = "gitlab.example.com";
20
+ export const BILLING = { host: HOST, path: "acme/billing" };
21
+
22
+ /** The module, with its actions kept as it registers them, so a test can ask an action's check. */
23
+ export function capturing(made: Plugin): { plugin: Plugin; actions: Map<string, Action<any, any>> } {
24
+ const actions = new Map<string, Action<any, any>>();
25
+ const wrapped = plugin(
26
+ made.name,
27
+ (api) => {
28
+ const spy = new Proxy(api, {
29
+ get(target, key) {
30
+ if (key === "action") {
31
+ return (one: Action<any, any>) => {
32
+ actions.set(one.name, one);
33
+ target.action(one);
34
+ };
35
+ }
36
+ const value: unknown = Reflect.get(target, key);
37
+ return typeof value === "function" ? value.bind(target) : value;
38
+ },
39
+ });
40
+ made.setup(spy);
41
+ },
42
+ { version: made.version },
43
+ );
44
+ return { plugin: wrapped, actions };
45
+ }
46
+
47
+ export interface ForgeHostOptions {
48
+ /** The mode of the token's file; `false` writes no file. Default: 0o600. */
49
+ readonly tokenMode?: number | false;
50
+ readonly env?: ForgeOptions["env"];
51
+ /** More plugins, installed before forge. */
52
+ readonly before?: readonly Plugin[];
53
+ /** More plugins, installed after forge. */
54
+ readonly after?: readonly Plugin[];
55
+ readonly forge?: Partial<ForgeOptions>;
56
+ }
57
+
58
+ /** A host with the forge module over a fake server that has the project acme/billing (42) and acme/payroll (43). */
59
+ export async function forgeHost(opts: ForgeHostOptions = {}) {
60
+ const server = new FakeGitLab();
61
+ const billing = server.project(42, "acme/billing");
62
+ const payroll = server.project(43, "acme/payroll");
63
+ const home = await tempHome();
64
+ const mode = opts.tokenMode ?? 0o600;
65
+ if (mode !== false) {
66
+ mkdirSync(join(home.path, "secrets"), { recursive: true });
67
+ const file = join(home.path, "secrets", "GITLAB_TOKEN");
68
+ writeFileSync(file, `${server.token}\n`);
69
+ chmodSync(file, mode);
70
+ }
71
+ const { plugin: module, actions } = capturing(
72
+ forge({ servers: [{ host: HOST, url: server.url, token: secret("GITLAB_TOKEN") }], fetch: server.fetch, env: opts.env ?? {}, poll: false, ...opts.forge }),
73
+ );
74
+ const niwa = createNiwa({ home: home.path });
75
+ niwa.use(...(opts.before ?? []), module, ...(opts.after ?? []));
76
+ await niwa.serve();
77
+ const clients: NiwaApi[] = [];
78
+ return {
79
+ niwa,
80
+ home: home.path,
81
+ server,
82
+ billing,
83
+ payroll,
84
+ actions,
85
+ /** A client whose grant is these rules. */
86
+ async as(rules: string[]): Promise<NiwaApi> {
87
+ const token = niwa.issueToken(principalOf("session", `caller-${String(clients.length)}`), { grant: grant(rules) });
88
+ const client = await connect({ home: home.path, id: `session:caller-${String(clients.length)}`, token });
89
+ clients.push(client);
90
+ return client;
91
+ },
92
+ /** Every record of the journal. */
93
+ async records(types?: string[]): Promise<StoredRecord[]> {
94
+ return await niwa.records.read(types === undefined ? {} : { types });
95
+ },
96
+ async stop() {
97
+ for (const client of clients) await client.close().catch(() => {});
98
+ await niwa.close();
99
+ await home.cleanup();
100
+ },
101
+ };
102
+ }
103
+
104
+ export type ForgeHost = Awaited<ReturnType<typeof forgeHost>>;
105
+
106
+ /** An open merge request of acme/billing on the branch `topic`, at a head named by `word`. */
107
+ export function openMr(host: ForgeHost, iid = 7, word = "topic-1", project: FakeProject = host.billing) {
108
+ return host.server.mr(project, { iid, source_branch: "topic", sha: sha(word) });
109
+ }
@@ -0,0 +1,42 @@
1
+ // The targets a grant names: a repository, a pull request, a ref, and the templates a run fills.
2
+
3
+ import { expect, test } from "bun:test";
4
+
5
+ import { fillRule, grant, match } from "@niwa-labs/core";
6
+
7
+ import { RepoName, forgePipelineRetry, forgePrEnsure, forgePrMerge, forgePrRead, prRule, refRule } from "../src/records.ts";
8
+
9
+ const repo = { host: "gitlab.example.com", path: "acme/billing" };
10
+ const head = "a".repeat(40);
11
+
12
+ test("a pull request, a ref and a repository have the targets a rule names", () => {
13
+ expect(forgePrMerge.target?.({ repo, number: 7, expectHead: head, method: "merge" })).toBe("gitlab.example.com/acme/billing/pr/7");
14
+ expect(forgePipelineRetry.target?.({ repo, ref: "feature/login", pipeline: 3 })).toBe("gitlab.example.com/acme/billing/ref/feature/login");
15
+ expect(forgePrRead.target?.({ repo, number: 7 })).toBe("gitlab.example.com/acme/billing");
16
+ });
17
+
18
+ test("a pull request that does not exist yet is pr/new, which a rule on every pull request covers", () => {
19
+ const target = forgePrEnsure.target?.({ repo, branch: "topic", base: "main", title: "Topic" });
20
+ expect(target).toBe("gitlab.example.com/acme/billing/pr/new");
21
+ expect(match(grant(["forge.pr.ensure@gitlab.example.com/acme/billing/pr/*"]), "call", "forge.pr.ensure", target)).toBeDefined();
22
+ });
23
+
24
+ test("a template filled from the input of a run covers that repository's pull requests and no other's", () => {
25
+ const rule = fillRule(prRule("forge.pr.merge"), { repo });
26
+ expect(rule).toBe("forge.pr.merge@gitlab.example.com/acme/billing/pr/*");
27
+ const rules = grant([rule]);
28
+ const ours = forgePrMerge.target?.({ repo, number: 7, expectHead: head, method: "merge" });
29
+ const theirs = forgePrMerge.target?.({ repo: { ...repo, path: "acme/payroll" }, number: 7, expectHead: head, method: "merge" });
30
+ expect(match(rules, "call", "forge.pr.merge", ours, { irreversible: true })).toBeDefined();
31
+ expect(match(rules, "call", "forge.pr.merge", theirs, { irreversible: true })).toBeUndefined();
32
+ expect(fillRule(refRule("forge.pipeline.retry"), { repo })).toBe("forge.pipeline.retry@gitlab.example.com/acme/billing/ref/*");
33
+ });
34
+
35
+ test("a repository name cannot widen a target: no wildcard, no port, no empty segment", () => {
36
+ expect(RepoName.safeParse({ host: "gitlab.example.com", path: "acme/*" }).success).toBe(false);
37
+ expect(RepoName.safeParse({ host: "gitlab.example.com:8443", path: "acme/billing" }).success).toBe(false);
38
+ expect(RepoName.safeParse({ host: "gitlab.example.com", path: "acme//billing" }).success).toBe(false);
39
+ expect(RepoName.safeParse({ host: "gitlab.example.com", path: "billing" }).success).toBe(false);
40
+ expect(forgePipelineRetry.input.safeParse({ repo, ref: "release/*", pipeline: 1 }).success).toBe(false);
41
+ expect(forgePipelineRetry.input.safeParse({ repo, ref: "a//b", pipeline: 1 }).success).toBe(false);
42
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "lib": [
5
+ "ESNext",
6
+ "DOM",
7
+ "DOM.Iterable",
8
+ "DOM.AsyncIterable"
9
+ ],
10
+ "jsx": "react-jsx"
11
+ },
12
+ "include": [
13
+ "src"
14
+ ]
15
+ }