@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.
- package/LICENSE +21 -0
- package/README.md +52 -2
- package/package.json +30 -4
- package/src/actions.ts +389 -0
- package/src/cockpit/actions.ts +94 -0
- package/src/cockpit/index.tsx +19 -0
- package/src/cockpit/page.tsx +158 -0
- package/src/cockpit/pulls.ts +103 -0
- package/src/flow.ts +232 -0
- package/src/gitlab.ts +263 -0
- package/src/index.ts +765 -0
- package/src/merge.ts +309 -0
- package/src/normalize.ts +186 -0
- package/src/observe.ts +464 -0
- package/src/prs.ts +122 -0
- package/src/queries.ts +152 -0
- package/src/record-types.ts +353 -0
- package/src/records.ts +8 -0
- package/src/secrets.ts +40 -0
- package/src/servers.ts +121 -0
- package/src/targets.ts +82 -0
- package/src/workflows/push-reaction.ts +59 -0
- package/test/actions.test.ts +235 -0
- package/test/cockpit-actions.test.ts +55 -0
- package/test/cockpit-pulls.test.ts +58 -0
- package/test/fake-gitlab.ts +452 -0
- package/test/flow.test.ts +239 -0
- package/test/gitlab.test.ts +91 -0
- package/test/merge.test.ts +251 -0
- package/test/observe.test.ts +454 -0
- package/test/prs.test.ts +125 -0
- package/test/push-reaction.test.ts +92 -0
- package/test/queries.test.ts +144 -0
- package/test/script-surface.test.ts +185 -0
- package/test/support.ts +109 -0
- package/test/targets.test.ts +42 -0
- package/tsconfig.json +15 -0
package/src/queries.ts
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The query builders of the forge records: what a workflow script waits for (`wait(prHead(pr), {
|
|
3
|
+
* timeout })`) or reads (`read.records(pipelineOf(...))`) with the data typed by the record, and a
|
|
4
|
+
* handler subscribes to.
|
|
5
|
+
*
|
|
6
|
+
* A builder names a pull request, a commit or a repository the way an action does, by `{ host, path }`
|
|
7
|
+
* and a number: a record's own repository, which also holds the project id, is accepted and read for
|
|
8
|
+
* its name. A name that is not one is refused when the query is made, not when the run reaches it.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { queryOf } from "@niwa-labs/core";
|
|
12
|
+
import type { TypeQuery } from "@niwa-labs/core";
|
|
13
|
+
import type { z } from "zod";
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
ChecksObserved,
|
|
17
|
+
JobObserved,
|
|
18
|
+
MergeArmed,
|
|
19
|
+
MergeDisarmed,
|
|
20
|
+
MergeSettled,
|
|
21
|
+
PipelineObserved,
|
|
22
|
+
PrClosed,
|
|
23
|
+
PrComment,
|
|
24
|
+
PrHead,
|
|
25
|
+
PrMerged,
|
|
26
|
+
PrOpened,
|
|
27
|
+
PrReview,
|
|
28
|
+
PrUpdated,
|
|
29
|
+
Pushed,
|
|
30
|
+
Sha,
|
|
31
|
+
} from "./record-types.ts";
|
|
32
|
+
import type { PipelineKind } from "./record-types.ts";
|
|
33
|
+
import { RepoName } from "./targets.ts";
|
|
34
|
+
|
|
35
|
+
/** A pull request as a builder is given it: the repository by name, and the number in the project. */
|
|
36
|
+
export interface PrKey {
|
|
37
|
+
readonly repo: { readonly host: string; readonly path: string };
|
|
38
|
+
readonly number: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** What a builder takes of a repository: its name; a project id beside it is not read. */
|
|
42
|
+
export interface RepoKey {
|
|
43
|
+
readonly host: string;
|
|
44
|
+
readonly path: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The name of a repository, checked. */
|
|
48
|
+
function repoOf(repo: RepoKey): RepoName {
|
|
49
|
+
return RepoName.parse({ host: repo.host, path: repo.path });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The filter on the pull request a record names as `pr`. */
|
|
53
|
+
function prFilter(pr: PrKey): { "pr.repo.host": string; "pr.repo.path": string; "pr.number": number } {
|
|
54
|
+
const repo = repoOf(pr.repo);
|
|
55
|
+
if (!Number.isInteger(pr.number) || pr.number < 1) throw new TypeError(`not a pull request number: ${String(pr.number)}`);
|
|
56
|
+
return { "pr.repo.host": repo.host, "pr.repo.path": repo.path, "pr.number": pr.number };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
type Data<R extends { readonly schema: z.ZodType }> = z.output<R["schema"]>;
|
|
60
|
+
|
|
61
|
+
/** A pull request was opened, or opened again. */
|
|
62
|
+
export function prOpened(pr: PrKey): TypeQuery<Data<typeof PrOpened>> {
|
|
63
|
+
return queryOf(PrOpened, prFilter(pr));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The title, the target branch or the draft flag of a pull request changed. */
|
|
67
|
+
export function prUpdated(pr: PrKey): TypeQuery<Data<typeof PrUpdated>> {
|
|
68
|
+
return queryOf(PrUpdated, prFilter(pr));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The head of a pull request moved: new commits, a rebase, a force push. */
|
|
72
|
+
export function prHead(pr: PrKey): TypeQuery<Data<typeof PrHead>> {
|
|
73
|
+
return queryOf(PrHead, prFilter(pr));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Somebody approved a pull request, or took an approval back. */
|
|
77
|
+
export function prReview(pr: PrKey): TypeQuery<Data<typeof PrReview>> {
|
|
78
|
+
return queryOf(PrReview, prFilter(pr));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Somebody commented on a pull request. */
|
|
82
|
+
export function prComment(pr: PrKey): TypeQuery<Data<typeof PrComment>> {
|
|
83
|
+
return queryOf(PrComment, prFilter(pr));
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A pull request was merged. */
|
|
87
|
+
export function prMerged(pr: PrKey): TypeQuery<Data<typeof PrMerged>> {
|
|
88
|
+
return queryOf(PrMerged, prFilter(pr));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** A pull request was closed without a merge. */
|
|
92
|
+
export function prClosed(pr: PrKey): TypeQuery<Data<typeof PrClosed>> {
|
|
93
|
+
return queryOf(PrClosed, prFilter(pr));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** What the pipelines of the head of a pull request say, together, changed. */
|
|
97
|
+
export function prChecks(pr: PrKey): TypeQuery<Data<typeof ChecksObserved>> {
|
|
98
|
+
return queryOf(ChecksObserved, prFilter(pr));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The server took a merge of a pull request that it will make later. */
|
|
102
|
+
export function mergeArmed(pr: PrKey): TypeQuery<Data<typeof MergeArmed>> {
|
|
103
|
+
return queryOf(MergeArmed, prFilter(pr));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A merge the server had taken was called off. */
|
|
107
|
+
export function mergeDisarmed(pr: PrKey): TypeQuery<Data<typeof MergeDisarmed>> {
|
|
108
|
+
return queryOf(MergeDisarmed, prFilter(pr));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** A merge the server had taken is over: the pull request was merged or closed there. */
|
|
112
|
+
export function mergeSettled(pr: PrKey): TypeQuery<Data<typeof MergeSettled>> {
|
|
113
|
+
return queryOf(MergeSettled, prFilter(pr));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The pipelines of a commit, one record for each state one of them was seen in. A commit is the one
|
|
118
|
+
* the change ran for (a pull request's head, or the commit of a branch or tag), and `kind` takes only
|
|
119
|
+
* the pipelines of that kind: a merge result, say, among a head's pipelines.
|
|
120
|
+
*/
|
|
121
|
+
export function pipelineOf(opts: { repo: RepoKey; sha: string; kind?: PipelineKind }): TypeQuery<Data<typeof PipelineObserved>> {
|
|
122
|
+
const repo = repoOf(opts.repo);
|
|
123
|
+
return queryOf(PipelineObserved, {
|
|
124
|
+
"repo.host": repo.host,
|
|
125
|
+
"repo.path": repo.path,
|
|
126
|
+
sourceSha: Sha.parse(opts.sha),
|
|
127
|
+
...(opts.kind === undefined ? {} : { kind: opts.kind }),
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The pipelines that ran for a pull request, as the server numbers it. */
|
|
132
|
+
export function pipelinesOfPr(pr: PrKey): TypeQuery<Data<typeof PipelineObserved>> {
|
|
133
|
+
const { "pr.repo.host": host, "pr.repo.path": path, "pr.number": number } = prFilter(pr);
|
|
134
|
+
return queryOf(PipelineObserved, { "repo.host": host, "repo.path": path, pr: number });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The jobs of one pipeline. */
|
|
138
|
+
export function jobsOf(opts: { repo: RepoKey; pipeline: number }): TypeQuery<Data<typeof JobObserved>> {
|
|
139
|
+
const repo = repoOf(opts.repo);
|
|
140
|
+
if (!Number.isInteger(opts.pipeline) || opts.pipeline < 1) throw new TypeError(`not a pipeline id: ${String(opts.pipeline)}`);
|
|
141
|
+
return queryOf(JobObserved, { "repo.host": repo.host, "repo.path": repo.path, pipeline: opts.pipeline });
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Commits pushed to a repository, or to one of its branches or tags.
|
|
146
|
+
* A ref is the name the server gives it, `main` or `v1.2`, without `refs/heads/`.
|
|
147
|
+
*/
|
|
148
|
+
export function pushed(repo: RepoKey, ref?: string): TypeQuery<Data<typeof Pushed>> {
|
|
149
|
+
const name = repoOf(repo);
|
|
150
|
+
if (ref !== undefined && ref.length === 0) throw new TypeError("a ref is not empty");
|
|
151
|
+
return queryOf(Pushed, { "repo.host": name.host, "repo.path": name.path, ...(ref === undefined ? {} : { ref }) });
|
|
152
|
+
}
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The records of the forge module: what it observed on a GitLab server, and what it did there.
|
|
3
|
+
*
|
|
4
|
+
* An observed record has an id that says where the fact came from (`Source`): an event of the
|
|
5
|
+
* server's own event log carries the server's event id, so the same event is written once however
|
|
6
|
+
* often it is read; a change the module saw between two polls carries the version of its
|
|
7
|
+
* observation and the state before it, so `open → closed → open` is three records and not one. A
|
|
8
|
+
* transition of a pull request is written once under an id of its own whichever of the two tells it.
|
|
9
|
+
* A change that came and went between two polls is invisible, and a record never claims more than
|
|
10
|
+
* what was seen.
|
|
11
|
+
*
|
|
12
|
+
* Records hold ids, states, authors, sizes and digests of foreign content, never the content: the
|
|
13
|
+
* text of a comment is read with `forge.comment.read`, whose result is the step's own.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { record } from "@niwa-labs/core";
|
|
17
|
+
import { z } from "zod";
|
|
18
|
+
|
|
19
|
+
import { ForgeHost, ProjectPath, RefName } from "./targets.ts";
|
|
20
|
+
|
|
21
|
+
/** A full commit id. */
|
|
22
|
+
export const Sha = z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/, "a full commit id");
|
|
23
|
+
export type Sha = z.infer<typeof Sha>;
|
|
24
|
+
|
|
25
|
+
/** A repository the module knows: the server, the path of the project and its id, which survives a rename. */
|
|
26
|
+
export const Repo = z.strictObject({ host: ForgeHost, path: ProjectPath, projectId: z.number().int().positive() });
|
|
27
|
+
export type Repo = z.infer<typeof Repo>;
|
|
28
|
+
|
|
29
|
+
/** A pull request (a GitLab merge request): its repository and its number in the project. */
|
|
30
|
+
export const PrRef = z.strictObject({ repo: Repo, number: z.number().int().positive() });
|
|
31
|
+
export type PrRef = z.infer<typeof PrRef>;
|
|
32
|
+
|
|
33
|
+
/** Where an observed fact came from: the server's event log, or a change seen between two polls. */
|
|
34
|
+
export const Source = z.discriminatedUnion("kind", [
|
|
35
|
+
z.strictObject({ kind: z.literal("event"), id: z.number().int().positive() }),
|
|
36
|
+
z.strictObject({ kind: z.literal("observed"), version: z.number().int().positive() }),
|
|
37
|
+
]);
|
|
38
|
+
export type Source = z.infer<typeof Source>;
|
|
39
|
+
|
|
40
|
+
/** Who did something on the server, by the server's username. */
|
|
41
|
+
export const ForgeUser = z.string().min(1);
|
|
42
|
+
|
|
43
|
+
/** What a pipeline ran on: the head of a pull request, its merge with the target, a merge train, a branch, a tag, a schedule. */
|
|
44
|
+
export const PipelineKind = z.enum(["head", "merge-result", "train", "branch", "tag", "schedule"]);
|
|
45
|
+
export type PipelineKind = z.infer<typeof PipelineKind>;
|
|
46
|
+
|
|
47
|
+
/** Where a pipeline or a job stands, in GitLab's words. */
|
|
48
|
+
export const RunState = z.enum([
|
|
49
|
+
"created",
|
|
50
|
+
"waiting_for_resource",
|
|
51
|
+
"preparing",
|
|
52
|
+
"pending",
|
|
53
|
+
"running",
|
|
54
|
+
"success",
|
|
55
|
+
"failed",
|
|
56
|
+
"canceled",
|
|
57
|
+
"skipped",
|
|
58
|
+
"manual",
|
|
59
|
+
"scheduled",
|
|
60
|
+
]);
|
|
61
|
+
export type RunState = z.infer<typeof RunState>;
|
|
62
|
+
|
|
63
|
+
/** A pipeline as the module records it. */
|
|
64
|
+
export const Pipeline = z.strictObject({
|
|
65
|
+
repo: Repo,
|
|
66
|
+
pipeline: z.number().int().positive(),
|
|
67
|
+
kind: PipelineKind,
|
|
68
|
+
ref: z.string().min(1),
|
|
69
|
+
/** The commit of the change: the head of the pull request, or the commit of the branch or tag. */
|
|
70
|
+
sourceSha: Sha,
|
|
71
|
+
/** The commit of the target branch a merge result or a train was made on. */
|
|
72
|
+
targetSha: Sha.optional(),
|
|
73
|
+
/** The commit a merge result or a train ran on: the merge of `sourceSha` into `targetSha`. */
|
|
74
|
+
mergeSha: Sha.optional(),
|
|
75
|
+
state: RunState,
|
|
76
|
+
/** The pull request a pipeline of a pull request ran for. */
|
|
77
|
+
pr: z.number().int().positive().optional(),
|
|
78
|
+
});
|
|
79
|
+
export type Pipeline = z.infer<typeof Pipeline>;
|
|
80
|
+
|
|
81
|
+
/** A pipeline changed its state: one record per state the module saw. */
|
|
82
|
+
export const PipelineObserved = record(
|
|
83
|
+
"forge.pipeline",
|
|
84
|
+
Pipeline.extend({ previous: RunState.optional(), source: Source }),
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
/** A job of a pipeline changed its state. */
|
|
88
|
+
export const JobObserved = record(
|
|
89
|
+
"forge.job",
|
|
90
|
+
z.strictObject({
|
|
91
|
+
repo: Repo,
|
|
92
|
+
pipeline: z.number().int().positive(),
|
|
93
|
+
job: z.number().int().positive(),
|
|
94
|
+
name: z.string().min(1),
|
|
95
|
+
stage: z.string().min(1),
|
|
96
|
+
state: RunState,
|
|
97
|
+
previous: RunState.optional(),
|
|
98
|
+
source: Source,
|
|
99
|
+
}),
|
|
100
|
+
);
|
|
101
|
+
|
|
102
|
+
/** What the pipelines of the head of a pull request say, together. */
|
|
103
|
+
export const ChecksState = z.enum(["none", "pending", "green", "red"]);
|
|
104
|
+
export type ChecksState = z.infer<typeof ChecksState>;
|
|
105
|
+
|
|
106
|
+
/** The checks of a pull request changed: computed by the module from the pipelines of its head. */
|
|
107
|
+
export const ChecksObserved = record(
|
|
108
|
+
"forge.checks",
|
|
109
|
+
z.strictObject({
|
|
110
|
+
pr: PrRef,
|
|
111
|
+
head: Sha,
|
|
112
|
+
state: ChecksState,
|
|
113
|
+
previous: ChecksState.optional(),
|
|
114
|
+
/** The latest pipeline of the head, which decides the state. */
|
|
115
|
+
pipeline: z.number().int().positive().optional(),
|
|
116
|
+
source: Source,
|
|
117
|
+
}),
|
|
118
|
+
);
|
|
119
|
+
|
|
120
|
+
/** Commits were pushed to a branch or a tag. */
|
|
121
|
+
export const Pushed = record(
|
|
122
|
+
"forge.push",
|
|
123
|
+
z.strictObject({
|
|
124
|
+
repo: Repo,
|
|
125
|
+
ref: z.string().min(1),
|
|
126
|
+
refType: z.enum(["branch", "tag"]),
|
|
127
|
+
/** The commit before the push; absent for a new ref. */
|
|
128
|
+
before: Sha.optional(),
|
|
129
|
+
/** The commit after the push; absent for a removed ref. */
|
|
130
|
+
after: Sha.optional(),
|
|
131
|
+
author: ForgeUser.optional(),
|
|
132
|
+
source: Source,
|
|
133
|
+
}),
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* A pull request as it was opened, or opened again: a closed pull request that is reopened is
|
|
138
|
+
* written again with `reopened`, so a subscriber sees `open → closed → open` as three records.
|
|
139
|
+
*/
|
|
140
|
+
export const PrOpened = record(
|
|
141
|
+
"forge.pr.opened",
|
|
142
|
+
z.strictObject({
|
|
143
|
+
pr: PrRef,
|
|
144
|
+
title: z.string(),
|
|
145
|
+
/** The branch the change is on. */
|
|
146
|
+
branch: RefName,
|
|
147
|
+
/** The branch it is to be merged into. */
|
|
148
|
+
base: RefName,
|
|
149
|
+
author: ForgeUser.optional(),
|
|
150
|
+
reopened: z.boolean().optional(),
|
|
151
|
+
source: Source,
|
|
152
|
+
}),
|
|
153
|
+
);
|
|
154
|
+
|
|
155
|
+
/** The title, the target branch or the draft flag of a pull request changed. */
|
|
156
|
+
export const PrUpdated = record(
|
|
157
|
+
"forge.pr.updated",
|
|
158
|
+
z.strictObject({
|
|
159
|
+
pr: PrRef,
|
|
160
|
+
title: z.string(),
|
|
161
|
+
base: RefName,
|
|
162
|
+
draft: z.boolean(),
|
|
163
|
+
source: Source,
|
|
164
|
+
}),
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
/** The head of a pull request moved: new commits, a rebase, a force push. */
|
|
168
|
+
export const PrHead = record(
|
|
169
|
+
"forge.pr.head",
|
|
170
|
+
z.strictObject({ pr: PrRef, head: Sha, previous: Sha.optional(), source: Source }),
|
|
171
|
+
);
|
|
172
|
+
|
|
173
|
+
/** Somebody approved a pull request, or took an approval back. */
|
|
174
|
+
export const PrReview = record(
|
|
175
|
+
"forge.pr.review",
|
|
176
|
+
z.strictObject({ pr: PrRef, reviewer: ForgeUser, state: z.enum(["approved", "unapproved"]), source: Source }),
|
|
177
|
+
);
|
|
178
|
+
|
|
179
|
+
/** Somebody commented on a pull request. The text is foreign content: the record holds its size and digest. */
|
|
180
|
+
export const PrComment = record(
|
|
181
|
+
"forge.pr.comment",
|
|
182
|
+
z.strictObject({
|
|
183
|
+
pr: PrRef,
|
|
184
|
+
comment: z.number().int().positive(),
|
|
185
|
+
discussion: z.string().min(1).optional(),
|
|
186
|
+
author: ForgeUser,
|
|
187
|
+
size: z.number().int().nonnegative(),
|
|
188
|
+
digest: z.string().regex(/^sha256:[0-9a-f]{64}$/),
|
|
189
|
+
source: Source,
|
|
190
|
+
}),
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
/** A pull request was merged. */
|
|
194
|
+
export const PrMerged = record(
|
|
195
|
+
"forge.pr.merged",
|
|
196
|
+
z.strictObject({
|
|
197
|
+
pr: PrRef,
|
|
198
|
+
base: RefName,
|
|
199
|
+
/** The head of the pull request that was merged. */
|
|
200
|
+
head: Sha.optional(),
|
|
201
|
+
/** The commit the merge made on the base: a merge commit, a squash, or the rebased head. */
|
|
202
|
+
mergeSha: Sha.optional(),
|
|
203
|
+
by: ForgeUser.optional(),
|
|
204
|
+
source: Source,
|
|
205
|
+
}),
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
/** A pull request was closed without a merge. */
|
|
209
|
+
export const PrClosed = record("forge.pr.closed", z.strictObject({ pr: PrRef, by: ForgeUser.optional(), source: Source }));
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* A repository is watched: the module polls it and records what it sees. `since` is the last event of
|
|
213
|
+
* the server's log at that moment: the events before it are history, not news.
|
|
214
|
+
*/
|
|
215
|
+
export const RepoWatched = record("forge.repo.watched", z.strictObject({ repo: Repo, since: z.number().int().nonnegative() }));
|
|
216
|
+
|
|
217
|
+
/** A repository is not watched any more. */
|
|
218
|
+
export const RepoUnwatched = record("forge.repo.unwatched", z.strictObject({ repo: Repo }));
|
|
219
|
+
|
|
220
|
+
/** How a merge was asked for: at once, when the pipeline succeeds, or by a merge train. */
|
|
221
|
+
export const MergeWhen = z.enum(["now", "pipeline", "train"]);
|
|
222
|
+
export type MergeWhen = z.infer<typeof MergeWhen>;
|
|
223
|
+
|
|
224
|
+
/** How the commits of a pull request land on its base: squashed, or by the project's merge method (`merge`, `rebase`). */
|
|
225
|
+
export const MergeMethod = z.enum(["merge", "squash", "rebase"]);
|
|
226
|
+
export type MergeMethod = z.infer<typeof MergeMethod>;
|
|
227
|
+
|
|
228
|
+
type MergeState = { phase: "open" | "merging" | "armed" | "cancelling" | "merged"; operation: string; basedOn?: string };
|
|
229
|
+
/** GitLab keeps the project ID when the project path changes. */
|
|
230
|
+
export function mergeKey(pr: PrRef): string {
|
|
231
|
+
return JSON.stringify([pr.repo.host, pr.repo.projectId, pr.number]);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const mergeGuard = {
|
|
235
|
+
group: "forge.merge",
|
|
236
|
+
key: (data: { pr: PrRef }) => mergeKey(data.pr),
|
|
237
|
+
initial: (): MergeState => ({ phase: "open", operation: "" }),
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
function owned(state: MergeState, operation: string, ...phases: MergeState["phase"][]) {
|
|
241
|
+
if (!phases.includes(state.phase) || state.operation !== operation) {
|
|
242
|
+
return { code: "stale-merge", reason: `the merge is ${state.phase} under operation ${state.operation}` };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* A merge is about to be asked of the server. Written before the request leaves, so a call that was
|
|
248
|
+
* cut off can be checked: without this record the request was never sent.
|
|
249
|
+
*/
|
|
250
|
+
export const MergeStarted = record(
|
|
251
|
+
"forge.pr.merge.started",
|
|
252
|
+
z.strictObject({ operation: z.string().min(1), pr: PrRef, expectHead: Sha, method: MergeMethod, when: MergeWhen }),
|
|
253
|
+
{ guard: {
|
|
254
|
+
...mergeGuard,
|
|
255
|
+
admit: state => state.phase === "open" ? undefined : { code: "merge-busy", reason: `the merge is ${state.phase}` },
|
|
256
|
+
fold: (_state, data): MergeState => ({ phase: "merging", operation: data.operation }),
|
|
257
|
+
} },
|
|
258
|
+
);
|
|
259
|
+
|
|
260
|
+
export const MergeRefused = record("forge.pr.merge.refused", z.strictObject({
|
|
261
|
+
pr: PrRef, operation: z.string().min(1), reason: z.string(), terminal: z.boolean(), failed: z.boolean(),
|
|
262
|
+
}), { guard: {
|
|
263
|
+
...mergeGuard,
|
|
264
|
+
admit: (state, data) => owned(state, data.operation, "merging"),
|
|
265
|
+
fold: (_state, data): MergeState => ({ phase: data.terminal ? "merged" : "open", operation: data.operation }),
|
|
266
|
+
} });
|
|
267
|
+
|
|
268
|
+
export const CancelStarted = record("forge.pr.merge.cancel.started", z.strictObject({
|
|
269
|
+
pr: PrRef, operation: z.string().min(1), basedOn: z.string().min(1), mode: z.enum(["auto-merge", "train"]),
|
|
270
|
+
}), { guard: {
|
|
271
|
+
...mergeGuard,
|
|
272
|
+
admit: (state, data) => owned(state, data.basedOn, "armed"),
|
|
273
|
+
fold: (_state, data): MergeState => ({ phase: "cancelling", operation: data.operation, basedOn: data.basedOn }),
|
|
274
|
+
} });
|
|
275
|
+
|
|
276
|
+
export const CancelRefused = record("forge.pr.merge.cancel.refused", z.strictObject({
|
|
277
|
+
pr: PrRef, operation: z.string().min(1), basedOn: z.string().min(1), error: z.string().optional(),
|
|
278
|
+
}), { guard: {
|
|
279
|
+
...mergeGuard,
|
|
280
|
+
admit: (state, data) => owned(state, data.operation, "cancelling") ??
|
|
281
|
+
(state.basedOn === data.basedOn ? undefined : { code: "stale-merge", reason: "a different merge was armed" }),
|
|
282
|
+
fold: (_state, data): MergeState => ({ phase: "armed", operation: data.basedOn }),
|
|
283
|
+
} });
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* The server took a merge it will make later: an automatic merge when the pipeline succeeds, or a
|
|
287
|
+
* place in a merge train. Nothing in niwa can stop it any more except `forge.pr.merge.cancel`.
|
|
288
|
+
*/
|
|
289
|
+
export const MergeArmed = record(
|
|
290
|
+
"forge.pr.merge.armed",
|
|
291
|
+
z.strictObject({
|
|
292
|
+
operation: z.string().min(1), pr: PrRef,
|
|
293
|
+
mode: z.enum(["auto-merge", "train"]),
|
|
294
|
+
/** The server's own name for what it took: `<host>/<path>!<n>` for the merge request. */
|
|
295
|
+
externalId: z.string().min(1),
|
|
296
|
+
expectHead: Sha,
|
|
297
|
+
}),
|
|
298
|
+
{ guard: {
|
|
299
|
+
...mergeGuard,
|
|
300
|
+
admit: (state, data) => owned(state, data.operation, "merging"),
|
|
301
|
+
fold: (_state, data): MergeState => ({ phase: "armed", operation: data.operation }),
|
|
302
|
+
} },
|
|
303
|
+
);
|
|
304
|
+
|
|
305
|
+
/** A merge the server had taken was called off, by `forge.pr.merge.cancel`. */
|
|
306
|
+
export const MergeDisarmed = record(
|
|
307
|
+
"forge.pr.merge.disarmed",
|
|
308
|
+
z.strictObject({ cancelled: z.boolean(), operation: z.string().min(1), pr: PrRef, externalId: z.string().min(1) }),
|
|
309
|
+
{ guard: {
|
|
310
|
+
...mergeGuard,
|
|
311
|
+
admit: (state, data) => owned(state, data.operation, "armed", "cancelling"),
|
|
312
|
+
fold: (_state, data): MergeState => ({ phase: "open", operation: data.operation }),
|
|
313
|
+
} },
|
|
314
|
+
);
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* A merge the server had taken is over without niwa having seen it merged or called off: the pull
|
|
318
|
+
* request was merged or closed there. Written for the merges niwa listed as pending, whether or not
|
|
319
|
+
* the repository is watched, and so it never says `forge.pr.merged`, which is for those who watch.
|
|
320
|
+
*/
|
|
321
|
+
export const MergeSettled = record(
|
|
322
|
+
"forge.pr.merge.settled",
|
|
323
|
+
z.strictObject({ operation: z.string().min(1), pr: PrRef, externalId: z.string().min(1), outcome: z.enum(["merged", "closed"]), mergeSha: Sha.optional() }),
|
|
324
|
+
{ guard: {
|
|
325
|
+
...mergeGuard,
|
|
326
|
+
admit: (state, data) => owned(state, data.operation, "armed", "merging", "cancelling"),
|
|
327
|
+
fold: (_state, data): MergeState => ({ phase: data.outcome === "merged" ? "merged" : "open", operation: data.operation }),
|
|
328
|
+
} },
|
|
329
|
+
);
|
|
330
|
+
|
|
331
|
+
/** Every record type of the forge module. */
|
|
332
|
+
export const FORGE_TYPES = [
|
|
333
|
+
RepoWatched,
|
|
334
|
+
RepoUnwatched,
|
|
335
|
+
Pushed,
|
|
336
|
+
PrOpened,
|
|
337
|
+
PrUpdated,
|
|
338
|
+
PrHead,
|
|
339
|
+
PrReview,
|
|
340
|
+
PrComment,
|
|
341
|
+
PrMerged,
|
|
342
|
+
PrClosed,
|
|
343
|
+
PipelineObserved,
|
|
344
|
+
JobObserved,
|
|
345
|
+
ChecksObserved,
|
|
346
|
+
MergeStarted,
|
|
347
|
+
MergeRefused,
|
|
348
|
+
CancelStarted,
|
|
349
|
+
CancelRefused,
|
|
350
|
+
MergeArmed,
|
|
351
|
+
MergeDisarmed,
|
|
352
|
+
MergeSettled,
|
|
353
|
+
] as const;
|
package/src/records.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// The records entry: the record types of the forge module, the typed references to its actions, the
|
|
2
|
+
// targets their rules name and the query builders of its records (`prMerged(pr)`, `pipelineOf(...)`),
|
|
3
|
+
// for the plugins and scripts that read them without the module.
|
|
4
|
+
|
|
5
|
+
export * from "./record-types.ts";
|
|
6
|
+
export * from "./actions.ts";
|
|
7
|
+
export * from "./targets.ts";
|
|
8
|
+
export * from "./queries.ts";
|
package/src/secrets.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The token of a server, resolved where a call runs.
|
|
3
|
+
*
|
|
4
|
+
* The configuration names a secret, `secret("GITLAB_TOKEN")`; its value is the owner's and is read
|
|
5
|
+
* the way the host reads every secret: from the file `<home>/secrets/<name>`, readable by its owner
|
|
6
|
+
* alone, or from the variable `NIWA_SECRET_<name>` of the host's environment. One secret serves every
|
|
7
|
+
* module that names it. The value goes into a request header and nowhere else: every message here
|
|
8
|
+
* names the secret, never its value.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { readFileSync, statSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
|
|
14
|
+
import { ForgeError } from "./gitlab.ts";
|
|
15
|
+
|
|
16
|
+
/** The value of the secret called `name`. */
|
|
17
|
+
export function resolveSecret(home: string, name: string, env: Readonly<Record<string, string | undefined>>): string {
|
|
18
|
+
const path = join(home, "secrets", name);
|
|
19
|
+
let mode: number | undefined;
|
|
20
|
+
try {
|
|
21
|
+
const stat = statSync(path);
|
|
22
|
+
if (stat.isFile()) mode = stat.mode;
|
|
23
|
+
} catch {
|
|
24
|
+
// Not a file: the environment may have it.
|
|
25
|
+
}
|
|
26
|
+
if (mode !== undefined) {
|
|
27
|
+
if ((mode & 0o077) !== 0) {
|
|
28
|
+
throw new ForgeError("unsafe-secret", `the file of the secret "${name}" must be readable by its owner alone (mode 0600)`);
|
|
29
|
+
}
|
|
30
|
+
return nonEmpty(name, readFileSync(path, "utf8").replace(/\r?\n$/, ""));
|
|
31
|
+
}
|
|
32
|
+
const fromEnv = env[`NIWA_SECRET_${name}`];
|
|
33
|
+
if (fromEnv !== undefined) return nonEmpty(name, fromEnv);
|
|
34
|
+
throw new ForgeError("unknown-secret", `no secret "${name}": ${path} does not exist and NIWA_SECRET_${name} is not set`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function nonEmpty(name: string, value: string): string {
|
|
38
|
+
if (value.length === 0) throw new ForgeError("unknown-secret", `the secret "${name}" is empty`);
|
|
39
|
+
return value;
|
|
40
|
+
}
|
package/src/servers.ts
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The servers the module is configured with, and the repositories it knows on them.
|
|
3
|
+
*
|
|
4
|
+
* One client per server, made when it is first needed and kept, so its ETags and its counts of the
|
|
5
|
+
* limit live as long as the host. The token is resolved for each request: a secret the owner
|
|
6
|
+
* replaces is taken without a restart.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { seq } from "@niwa-labs/core";
|
|
10
|
+
import type { JournalReader } from "@niwa-labs/core";
|
|
11
|
+
|
|
12
|
+
import type { SecretRef } from "./actions.ts";
|
|
13
|
+
import { ForgeError, GitLab } from "./gitlab.ts";
|
|
14
|
+
import type { FetchLike } from "./gitlab.ts";
|
|
15
|
+
import { RepoUnwatched, RepoWatched } from "./record-types.ts";
|
|
16
|
+
import type { Repo } from "./record-types.ts";
|
|
17
|
+
import { resolveSecret } from "./secrets.ts";
|
|
18
|
+
import type { RepoName } from "./targets.ts";
|
|
19
|
+
|
|
20
|
+
/** A GitLab server the module speaks to. */
|
|
21
|
+
export interface ForgeServer {
|
|
22
|
+
/** The name of the server as targets name it: its host, without a port. */
|
|
23
|
+
readonly host: string;
|
|
24
|
+
/** Its base URL. Default: `https://<host>`. */
|
|
25
|
+
readonly url?: string;
|
|
26
|
+
/** The secret that holds its token, such as `secret("GITLAB_TOKEN")`. */
|
|
27
|
+
readonly token: SecretRef;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What the servers need from the host. */
|
|
31
|
+
export interface ServersPlace {
|
|
32
|
+
readonly home: () => string;
|
|
33
|
+
readonly now: () => number;
|
|
34
|
+
readonly fetch: FetchLike;
|
|
35
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A repository watched now, and the last event of its log when it was watched. */
|
|
39
|
+
export interface Watched {
|
|
40
|
+
readonly repo: Repo;
|
|
41
|
+
readonly since: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The repositories watched now, by `<host>/<path>`, folded from the journal. */
|
|
45
|
+
export function watching(journal: JournalReader | undefined): Map<string, Watched> {
|
|
46
|
+
const watched = new Map<string, Watched>();
|
|
47
|
+
if (journal === undefined) return watched;
|
|
48
|
+
for (const stored of journal.since(seq(0), [RepoWatched.name, RepoUnwatched.name])) {
|
|
49
|
+
if (stored.type === RepoWatched.name) {
|
|
50
|
+
const parsed = RepoWatched.schema.safeParse(stored.data);
|
|
51
|
+
if (parsed.success) watched.set(repoKey(parsed.data.repo), parsed.data);
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const parsed = RepoUnwatched.schema.safeParse(stored.data);
|
|
55
|
+
if (parsed.success) watched.delete(repoKey(parsed.data.repo));
|
|
56
|
+
}
|
|
57
|
+
return watched;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The repositories watched now, by `<host>/<path>`. */
|
|
61
|
+
export function watchedRepos(journal: JournalReader | undefined): Map<string, Repo> {
|
|
62
|
+
return new Map([...watching(journal)].map(([key, one]) => [key, one.repo]));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The key of a repository: `<host>/<path>`. */
|
|
66
|
+
export function repoKey(repo: RepoName): string {
|
|
67
|
+
return `${repo.host}/${repo.path}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export class Servers {
|
|
71
|
+
readonly #byHost = new Map<string, ForgeServer>();
|
|
72
|
+
readonly #clients = new Map<string, GitLab>();
|
|
73
|
+
readonly #place: ServersPlace;
|
|
74
|
+
|
|
75
|
+
constructor(servers: readonly ForgeServer[], place: ServersPlace) {
|
|
76
|
+
for (const server of servers) {
|
|
77
|
+
if (this.#byHost.has(server.host)) throw new TypeError(`forge: the server "${server.host}" is configured twice`);
|
|
78
|
+
this.#byHost.set(server.host, server);
|
|
79
|
+
}
|
|
80
|
+
this.#place = place;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The hosts configured. */
|
|
84
|
+
hosts(): string[] {
|
|
85
|
+
return [...this.#byHost.keys()];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The client of a server. */
|
|
89
|
+
client(host: string): GitLab {
|
|
90
|
+
const known = this.#clients.get(host);
|
|
91
|
+
if (known !== undefined) return known;
|
|
92
|
+
const server = this.#byHost.get(host);
|
|
93
|
+
if (server === undefined) throw new ForgeError("unknown-server", `no GitLab server "${host}" is configured`);
|
|
94
|
+
const made = new GitLab({
|
|
95
|
+
url: server.url ?? `https://${host}`,
|
|
96
|
+
token: () => resolveSecret(this.#place.home(), server.token.secret, this.#place.env),
|
|
97
|
+
fetch: this.#place.fetch,
|
|
98
|
+
now: this.#place.now,
|
|
99
|
+
});
|
|
100
|
+
this.#clients.set(host, made);
|
|
101
|
+
return made;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The repository of a name: as it is watched, else as the server says now. */
|
|
105
|
+
async repo(name: RepoName, journal: JournalReader | undefined): Promise<Repo> {
|
|
106
|
+
const watched = watchedRepos(journal).get(repoKey(name));
|
|
107
|
+
if (watched !== undefined) return watched;
|
|
108
|
+
return await this.lookup(name);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The repository of a name, as the server says now. */
|
|
112
|
+
async lookup(name: RepoName): Promise<Repo> {
|
|
113
|
+
const project = await this.client(name.host).get<{ id: number }>(`/projects/${encodeURIComponent(name.path)}`);
|
|
114
|
+
return { host: name.host, path: name.path, projectId: project.id };
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The path of a project's resource in the API. */
|
|
119
|
+
export function projectPath(repo: Repo, rest = ""): string {
|
|
120
|
+
return `/projects/${String(repo.projectId)}${rest}`;
|
|
121
|
+
}
|