docks-kit 0.24.0 → 0.26.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/AGENTS.md +21 -136
- package/README.md +54 -9
- package/cli/dist/docks-kit.js +24688 -0
- package/cli/docs/command-guards.md +1 -1
- package/cli/docs/install.md +30 -9
- package/cli/docs/omp-context.md +1 -1
- package/cli/docs/omp-models.md +5 -4
- package/cli/docs/sync-layers.md +46 -75
- package/cli/docs/toolchain.md +4 -5
- package/cli/src/agentDocs/agentFirstCheck.ts +786 -0
- package/cli/src/agentDocs/bridgeCheck.ts +226 -0
- package/cli/src/agentDocs/commands.ts +63 -0
- package/cli/src/agentDocs/prTemplate.ts +211 -0
- package/cli/src/agentDocs/services.ts +202 -0
- package/cli/src/agentDocs/shared.ts +730 -0
- package/cli/src/agentDocs/verifySkill.ts +136 -0
- package/cli/src/argv.ts +25 -1
- package/cli/src/commands/agentDocs.ts +29 -0
- package/cli/src/commands/plan.ts +29 -0
- package/cli/src/commands/skill.ts +29 -0
- package/cli/src/commands/update.ts +90 -31
- package/cli/src/engine-native/DESIGN.md +5 -6
- package/cli/src/engine-native/engineCtx.ts +0 -3
- package/cli/src/engine-native/failures.ts +2 -2
- package/cli/src/engine-native/ompChild.ts +1 -1
- package/cli/src/engine-native/ompKitPlugin.ts +7 -16
- package/cli/src/engine-native/ompPlugins.ts +205 -221
- package/cli/src/engine-native/ompSync.ts +5 -14
- package/cli/src/generated/sotPayload.ts +308 -12
- package/cli/src/main.ts +12 -3
- package/cli/src/plan/bytes.ts +110 -0
- package/cli/src/plan/checkout.ts +341 -0
- package/cli/src/plan/commands.ts +1192 -0
- package/cli/src/plan/github.ts +816 -0
- package/cli/src/plan/records.ts +623 -0
- package/cli/src/plan/repository.ts +53 -0
- package/cli/src/plan/reviews.ts +292 -0
- package/cli/src/plan/services.ts +256 -0
- package/cli/src/plan/types.ts +164 -0
- package/cli/src/skills/commands.ts +142 -0
- package/cli/src/skills/config.json +30 -0
- package/cli/src/skills/files.ts +74 -0
- package/cli/src/skills/frontmatter.ts +148 -0
- package/cli/src/skills/guard.ts +366 -0
- package/cli/src/skills/kitGate.ts +406 -0
- package/cli/src/skills/rubric.ts +143 -0
- package/cli/tsconfig.json +1 -0
- package/package.json +7 -4
- package/cli/src/engine-native/ompMarketplace.ts +0 -140
|
@@ -0,0 +1,816 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The gh adapter of `docks-kit plan`: gh processes, the GraphQL transport with pagination, the plan issue snapshot,
|
|
3
|
+
* the guarded issue write, and the pull request read. The argv shapes and queries match plan.mjs byte for byte. Each
|
|
4
|
+
* response is decoded with a Schema; a decode failure gives the plan.mjs message of that check.
|
|
5
|
+
*/
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
import { Effect, Predicate, Schema } from "effect";
|
|
10
|
+
|
|
11
|
+
import { PLAN_LABELS, token } from "./records";
|
|
12
|
+
import { stateDirectory } from "./repository";
|
|
13
|
+
import {
|
|
14
|
+
MAX_OUTPUT_MIB,
|
|
15
|
+
PlanFiles,
|
|
16
|
+
PlanProcess,
|
|
17
|
+
PlanRepository,
|
|
18
|
+
type ProcessResult,
|
|
19
|
+
} from "./services";
|
|
20
|
+
import {
|
|
21
|
+
field,
|
|
22
|
+
GhError,
|
|
23
|
+
GraphqlError,
|
|
24
|
+
PlanRefusal,
|
|
25
|
+
type Closer,
|
|
26
|
+
type FileError,
|
|
27
|
+
type IssueComment,
|
|
28
|
+
type IssueSummary,
|
|
29
|
+
type LabelNode,
|
|
30
|
+
type ParentLink,
|
|
31
|
+
type PlanIssue,
|
|
32
|
+
type PullRequestNode,
|
|
33
|
+
type RepositoryInfo,
|
|
34
|
+
type SpawnError,
|
|
35
|
+
} from "./types";
|
|
36
|
+
|
|
37
|
+
const ACTING_LOGIN_ERROR =
|
|
38
|
+
"cannot resolve the acting GitHub login (the GraphQL viewer.login lookup returned nothing)";
|
|
39
|
+
const PAGE_INFO = "pageInfo{hasNextPage endCursor}";
|
|
40
|
+
const PULL_REQUEST_FIELDS = "number url state mergedAt baseRefName repository{nameWithOwner}";
|
|
41
|
+
const PULL_REQUEST_CONNECTION = `nodes{${PULL_REQUEST_FIELDS}} ${PAGE_INFO}`;
|
|
42
|
+
const REPOSITORY_LABELS = PLAN_LABELS.map(
|
|
43
|
+
(name) => `${name.split(":").at(-1)}:label(name:"${name}"){name id}`,
|
|
44
|
+
).join(" ");
|
|
45
|
+
// The pre-write read returns the body to compare and the node ids that the write mutation needs.
|
|
46
|
+
const PRE_WRITE_FIELDS = "id,body,updatedAt,assignees";
|
|
47
|
+
// The last field of a write mutation returns the stored state that the post-write checks read.
|
|
48
|
+
const STORED_ISSUE_FIELDS = `body labels(first:100){nodes{name} ${PAGE_INFO}}`;
|
|
49
|
+
// A plan list row and a sub-issue row: enough to derive the status of each issue.
|
|
50
|
+
export const ISSUE_SUMMARY_FIELDS = `number title state stateReason labels(first:100){nodes{name} ${PAGE_INFO}}`;
|
|
51
|
+
// The snapshot pages every issue label with its node id, so a write removes labels from the complete list.
|
|
52
|
+
const ISSUE_LABEL_FIELDS = "name id";
|
|
53
|
+
const ASSIGNEE_FIELDS = "... on Actor{login}";
|
|
54
|
+
// `fullDatabaseId` is the number after `#issuecomment-` in the comment URL, the id that an authority event names.
|
|
55
|
+
const COMMENT_FIELDS = "fullDatabaseId body createdAt author{login}";
|
|
56
|
+
const LABELED_EVENT_FIELDS = "... on LabeledEvent{label{name}}";
|
|
57
|
+
const CLOSED_EVENT_FIELDS = `... on ClosedEvent{createdAt closer{__typename ... on PullRequest{${PULL_REQUEST_FIELDS}} ... on Commit{oid associatedPullRequests(first:100){${PULL_REQUEST_CONNECTION}}}}}`;
|
|
58
|
+
|
|
59
|
+
export type GhServices = PlanProcess | PlanRepository;
|
|
60
|
+
/** The failures of a gh read. */
|
|
61
|
+
export type GhFailure = GhError | GraphqlError | SpawnError;
|
|
62
|
+
|
|
63
|
+
// Schemas of the response fields that the checks of plan.mjs read. A Struct ignores the fields it does not name.
|
|
64
|
+
// `Date.parse` decides a valid time, as in plan.mjs: `DateTime.make` reads a time without a zone as UTC.
|
|
65
|
+
const ParsableTime = Schema.String.check(
|
|
66
|
+
Schema.makeFilter((text: string) => Number.isFinite(Date.parse(text))),
|
|
67
|
+
);
|
|
68
|
+
const NonBlankString = Schema.String.check(Schema.makeFilter((text: string) => !!text.trim()));
|
|
69
|
+
const PageInfo = Schema.Struct({
|
|
70
|
+
hasNextPage: Schema.Boolean,
|
|
71
|
+
endCursor: Schema.NullOr(Schema.String),
|
|
72
|
+
});
|
|
73
|
+
const Connection = Schema.Struct({ nodes: Schema.Array(Schema.ObjectKeyword), pageInfo: PageInfo });
|
|
74
|
+
const RepositoryName = Schema.Struct({ nameWithOwner: Schema.String });
|
|
75
|
+
const PullRequestFields = Schema.Struct({
|
|
76
|
+
number: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
|
|
77
|
+
url: Schema.String,
|
|
78
|
+
state: Schema.String,
|
|
79
|
+
mergedAt: Schema.NullOr(Schema.String),
|
|
80
|
+
baseRefName: Schema.String,
|
|
81
|
+
repository: RepositoryName,
|
|
82
|
+
});
|
|
83
|
+
const CommitFields = Schema.Struct({
|
|
84
|
+
oid: Schema.NonEmptyString,
|
|
85
|
+
associatedPullRequests: Schema.optionalKey(Schema.Unknown),
|
|
86
|
+
});
|
|
87
|
+
const ClosedEvent = Schema.Struct({
|
|
88
|
+
createdAt: ParsableTime,
|
|
89
|
+
closer: Schema.NullOr(Schema.Struct({ __typename: Schema.NonEmptyString })),
|
|
90
|
+
});
|
|
91
|
+
const LabelName = Schema.Struct({ name: Schema.String });
|
|
92
|
+
const LabelWithId = Schema.Struct({ name: Schema.String, id: Schema.NonEmptyString });
|
|
93
|
+
const OptionalLabel = Schema.NullOr(LabelWithId);
|
|
94
|
+
const Assignee = Schema.Struct({ login: Schema.NonEmptyString });
|
|
95
|
+
const CommentFields = Schema.Struct({
|
|
96
|
+
fullDatabaseId: Schema.String.check(Schema.isPattern(/^[1-9]\d*$/)),
|
|
97
|
+
body: Schema.String,
|
|
98
|
+
createdAt: ParsableTime,
|
|
99
|
+
author: Schema.NullOr(Schema.Struct({ login: Schema.String })),
|
|
100
|
+
});
|
|
101
|
+
const LabeledEvent = Schema.Struct({ label: LabelName });
|
|
102
|
+
const SummaryFields = Schema.Struct({
|
|
103
|
+
number: Schema.Int,
|
|
104
|
+
title: Schema.String,
|
|
105
|
+
state: Schema.String,
|
|
106
|
+
stateReason: Schema.NullOr(Schema.String),
|
|
107
|
+
labels: Schema.optionalKey(Schema.Unknown),
|
|
108
|
+
});
|
|
109
|
+
const ParentFields = Schema.NullOr(
|
|
110
|
+
Schema.Struct({ number: Schema.Int, repository: RepositoryName }),
|
|
111
|
+
);
|
|
112
|
+
const IssueFields = Schema.Struct({
|
|
113
|
+
number: Schema.Finite,
|
|
114
|
+
title: Schema.String,
|
|
115
|
+
body: Schema.String,
|
|
116
|
+
state: Schema.String,
|
|
117
|
+
stateReason: Schema.NullOr(Schema.String),
|
|
118
|
+
url: Schema.String,
|
|
119
|
+
createdAt: Schema.String,
|
|
120
|
+
updatedAt: Schema.String,
|
|
121
|
+
});
|
|
122
|
+
const RepositoryFields = Schema.Struct({
|
|
123
|
+
nameWithOwner: Schema.String.check(Schema.isPattern(/^[^/]+\/[^/]+$/)),
|
|
124
|
+
visibility: Schema.String,
|
|
125
|
+
});
|
|
126
|
+
const DefaultBranch = Schema.Struct({ name: Schema.String });
|
|
127
|
+
const PreWriteFields = Schema.Struct({
|
|
128
|
+
id: Schema.NonEmptyString,
|
|
129
|
+
body: Schema.String,
|
|
130
|
+
assignees: Schema.Array(
|
|
131
|
+
Schema.Struct({ id: Schema.NonEmptyString, login: Schema.optionalKey(Schema.Unknown) }),
|
|
132
|
+
),
|
|
133
|
+
});
|
|
134
|
+
const StoredIssue = Schema.Struct({
|
|
135
|
+
body: Schema.String,
|
|
136
|
+
labels: Schema.Struct({ nodes: Schema.Array(Schema.Unknown) }),
|
|
137
|
+
});
|
|
138
|
+
const PullRequestFieldsRead = Schema.Struct({
|
|
139
|
+
url: Schema.String,
|
|
140
|
+
merged: Schema.Boolean,
|
|
141
|
+
mergedAt: Schema.optionalKey(Schema.Unknown),
|
|
142
|
+
baseRefName: Schema.String,
|
|
143
|
+
body: Schema.NullOr(Schema.String),
|
|
144
|
+
});
|
|
145
|
+
const ClosingReference = Schema.Struct({ number: Schema.Int, repository: RepositoryName });
|
|
146
|
+
const RestIssue = Schema.Struct({ id: Schema.Int });
|
|
147
|
+
|
|
148
|
+
/** Decode `input` with `schema`; a failure becomes the error that `onError` makes. */
|
|
149
|
+
const decodeWith = <T, E>(
|
|
150
|
+
schema: Schema.ConstraintDecoder<T>,
|
|
151
|
+
onError: () => E,
|
|
152
|
+
): ((input: unknown) => Effect.Effect<T, E>) => {
|
|
153
|
+
const decode = Schema.decodeUnknownEffect(schema);
|
|
154
|
+
return (input) => decode(input).pipe(Effect.mapError(onError));
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const malformed = <T>(
|
|
158
|
+
schema: Schema.ConstraintDecoder<T>,
|
|
159
|
+
name: string,
|
|
160
|
+
): ((input: unknown) => Effect.Effect<T, GraphqlError>) =>
|
|
161
|
+
decodeWith(
|
|
162
|
+
schema,
|
|
163
|
+
() => new GraphqlError({ message: `gh api graphql returned malformed ${name}` }),
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
const ghCommand = (argv: ReadonlyArray<string>): string => argv.slice(0, 2).join(" ");
|
|
167
|
+
|
|
168
|
+
/** Start gh and refuse only when it cannot run, so that a caller can read a failed exit. */
|
|
169
|
+
export const ghResult = Effect.fn("plan.ghResult")(function* (argv: ReadonlyArray<string>) {
|
|
170
|
+
const processes = yield* PlanProcess;
|
|
171
|
+
const result = yield* processes.run("gh", argv);
|
|
172
|
+
if (result.error?.code === "ENOENT")
|
|
173
|
+
return yield* new GhError({ message: "gh is not installed or not on PATH" });
|
|
174
|
+
if (result.error?.code === "ENOBUFS")
|
|
175
|
+
return yield* new GhError({
|
|
176
|
+
message: `gh ${ghCommand(argv)} output exceeded ${MAX_OUTPUT_MIB} MiB`,
|
|
177
|
+
});
|
|
178
|
+
if (result.error)
|
|
179
|
+
return yield* new GhError({ message: `gh ${ghCommand(argv)} failed: ${result.error.message}` });
|
|
180
|
+
return result;
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
export const ghOutput = Effect.fn("plan.ghOutput")(function* (
|
|
184
|
+
argv: ReadonlyArray<string>,
|
|
185
|
+
result: ProcessResult,
|
|
186
|
+
) {
|
|
187
|
+
if (result.status === 0) return result.stdout;
|
|
188
|
+
const detail = result.stderr.trim() || `exit ${result.status}`;
|
|
189
|
+
return yield* new GhError({ message: `gh ${ghCommand(argv)} failed: ${detail}` });
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
export const runGh = Effect.fn("plan.runGh")(function* (argv: ReadonlyArray<string>) {
|
|
193
|
+
return yield* ghOutput(argv, yield* ghResult(argv));
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
|
|
197
|
+
|
|
198
|
+
export const parseJson = Effect.fn("plan.parseJson")(function* (output: string, command: string) {
|
|
199
|
+
return yield* decodeJson(output).pipe(
|
|
200
|
+
Effect.mapError(() => new GhError({ message: `${command} returned invalid JSON` })),
|
|
201
|
+
);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
/** Run `gh api graphql` with the given fields and return the response data. */
|
|
205
|
+
export const graphqlData = Effect.fn("plan.graphqlData")(function* (fields: ReadonlyArray<string>) {
|
|
206
|
+
const response = yield* parseJson(yield* runGh(["api", "graphql", ...fields]), "gh api graphql");
|
|
207
|
+
const errors = field(response, "errors");
|
|
208
|
+
if (!response || (errors !== undefined && (!Array.isArray(errors) || errors.length))) {
|
|
209
|
+
const message = field(field(errors, "0"), "message") ?? "malformed errors";
|
|
210
|
+
return yield* new GraphqlError({
|
|
211
|
+
message: `gh api graphql returned errors: ${String(message)}`,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
const data = field(response, "data");
|
|
215
|
+
if (!Predicate.isObjectOrArray(data))
|
|
216
|
+
return yield* new GraphqlError({ message: "gh api graphql returned missing data" });
|
|
217
|
+
return data;
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
export const graphql = Effect.fn("plan.graphql")(function* (
|
|
221
|
+
query: string,
|
|
222
|
+
variables: Readonly<Record<string, string | number>> = {},
|
|
223
|
+
) {
|
|
224
|
+
const fields = ["-f", `query=${query}`, "-F", "owner={owner}", "-F", "name={repo}"];
|
|
225
|
+
for (const [key, value] of Object.entries(variables)) fields.push("-F", `${key}=${value}`);
|
|
226
|
+
return yield* graphqlData(fields);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
export function issueConnectionSelection(
|
|
230
|
+
connection: string,
|
|
231
|
+
nodeFields: string,
|
|
232
|
+
extraArgs = "",
|
|
233
|
+
after = false,
|
|
234
|
+
): string {
|
|
235
|
+
return `${connection}(first:100${after ? ",after:$after" : ""}${extraArgs}){nodes{${nodeFields}} ${PAGE_INFO}}`;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Read every page of a connection, up to `limit` nodes. */
|
|
239
|
+
export const connectionNodes = Effect.fn("plan.connectionNodes")(function* (
|
|
240
|
+
initial: unknown,
|
|
241
|
+
name: string,
|
|
242
|
+
nextPage: (cursor: string) => Effect.Effect<unknown, GhFailure, PlanProcess>,
|
|
243
|
+
limit = Number.POSITIVE_INFINITY,
|
|
244
|
+
) {
|
|
245
|
+
const decodePage = malformed(Connection, name);
|
|
246
|
+
const nodes: Array<object> = [];
|
|
247
|
+
const seen = new Set<string>();
|
|
248
|
+
let connection = initial;
|
|
249
|
+
for (;;) {
|
|
250
|
+
const page = yield* decodePage(connection);
|
|
251
|
+
nodes.push(...page.nodes);
|
|
252
|
+
if (!page.pageInfo.hasNextPage || nodes.length >= limit) return nodes;
|
|
253
|
+
const cursor = page.pageInfo.endCursor;
|
|
254
|
+
if (cursor === null || !cursor || seen.has(cursor))
|
|
255
|
+
return yield* new GraphqlError({
|
|
256
|
+
message: `gh api graphql returned malformed ${name} cursor`,
|
|
257
|
+
});
|
|
258
|
+
seen.add(cursor);
|
|
259
|
+
connection = yield* nextPage(cursor);
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
const decodePullRequests = malformed(Schema.Array(PullRequestFields), "closing pull requests");
|
|
264
|
+
|
|
265
|
+
export const pullRequestNodes = (
|
|
266
|
+
nodes: ReadonlyArray<unknown>,
|
|
267
|
+
): Effect.Effect<ReadonlyArray<PullRequestNode>, GraphqlError> => decodePullRequests(nodes);
|
|
268
|
+
|
|
269
|
+
/** Every node of an issue connection, from the first page in `initial` on. */
|
|
270
|
+
export const issueNodes = Effect.fn("plan.issueNodes")(function* (
|
|
271
|
+
issueNumber: number,
|
|
272
|
+
initial: unknown,
|
|
273
|
+
connection: string,
|
|
274
|
+
nodeFields: string,
|
|
275
|
+
extraArgs = "",
|
|
276
|
+
) {
|
|
277
|
+
const name = connection.includes(":") ? connection.split(":")[0] : connection;
|
|
278
|
+
const selection = issueConnectionSelection(connection, nodeFields, extraArgs, true);
|
|
279
|
+
const query = `query($owner:String!,$name:String!,$number:Int!,$after:String!){repository(owner:$owner,name:$name){issue(number:$number){${selection}}}}`;
|
|
280
|
+
return yield* connectionNodes(initial, name, (after) =>
|
|
281
|
+
graphql(query, { number: issueNumber, after }).pipe(
|
|
282
|
+
Effect.map((data) => field(field(field(data, "repository"), "issue"), name)),
|
|
283
|
+
),
|
|
284
|
+
);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
/** Every pull request associated with the commit that closed a plan. */
|
|
288
|
+
export const associatedNodes = Effect.fn("plan.associatedNodes")(function* (
|
|
289
|
+
commit: Extract<Closer, { readonly __typename: "Commit" }>,
|
|
290
|
+
) {
|
|
291
|
+
const query = `query($owner:String!,$name:String!,$oid:String!,$after:String!){repository(owner:$owner,name:$name){commit:object(expression:$oid){... on Commit{associatedPullRequests(first:100,after:$after){${PULL_REQUEST_CONNECTION}}}}}}`;
|
|
292
|
+
return yield* connectionNodes(
|
|
293
|
+
commit.associatedPullRequests,
|
|
294
|
+
"associated pull requests",
|
|
295
|
+
(after) =>
|
|
296
|
+
graphql(query, { oid: commit.oid, after }).pipe(
|
|
297
|
+
Effect.map((data) =>
|
|
298
|
+
field(field(field(data, "repository"), "commit"), "associatedPullRequests"),
|
|
299
|
+
),
|
|
300
|
+
),
|
|
301
|
+
);
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
/** Issue rows read through ISSUE_SUMMARY_FIELDS, with every label page as a plain list. */
|
|
305
|
+
export const issueSummaries = Effect.fn("plan.issueSummaries")(function* (
|
|
306
|
+
nodes: ReadonlyArray<object>,
|
|
307
|
+
name: string,
|
|
308
|
+
) {
|
|
309
|
+
const rows = yield* malformed(Schema.Array(SummaryFields), name)(nodes);
|
|
310
|
+
const decodeLabels = malformed(Schema.Array(LabelName), name);
|
|
311
|
+
const summaries: Array<IssueSummary> = [];
|
|
312
|
+
for (const row of rows) {
|
|
313
|
+
const labels = yield* decodeLabels(yield* issueNodes(row.number, row.labels, "labels", "name"));
|
|
314
|
+
summaries.push({
|
|
315
|
+
number: row.number,
|
|
316
|
+
title: row.title,
|
|
317
|
+
state: row.state,
|
|
318
|
+
stateReason: row.stateReason,
|
|
319
|
+
labels,
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
return summaries;
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
export interface SnapshotOptions {
|
|
326
|
+
readonly acting?: boolean;
|
|
327
|
+
readonly labelLookup?: boolean;
|
|
328
|
+
readonly comments?: boolean;
|
|
329
|
+
readonly history?: boolean;
|
|
330
|
+
readonly defaultBranch?: boolean;
|
|
331
|
+
readonly closure?: boolean;
|
|
332
|
+
readonly children?: boolean;
|
|
333
|
+
readonly parent?: boolean;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
export interface RepositorySnapshot {
|
|
337
|
+
readonly login: string | undefined;
|
|
338
|
+
readonly viewerId: string | undefined;
|
|
339
|
+
/** Each plan label name maps to its node id, or to null when the repository lacks the label. */
|
|
340
|
+
readonly labelIds: ReadonlyMap<string, string | null> | undefined;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
export interface IssueSnapshot extends RepositorySnapshot {
|
|
344
|
+
readonly issue: PlanIssue;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const decodeClosure = malformed(
|
|
348
|
+
Schema.Struct({ nodes: Schema.Array(Schema.Unknown) }),
|
|
349
|
+
"latest closure",
|
|
350
|
+
);
|
|
351
|
+
const decodeClosedEvent = malformed(ClosedEvent, "latest closure");
|
|
352
|
+
const decodeCommit = malformed(CommitFields, "closing commit");
|
|
353
|
+
|
|
354
|
+
/** The closer and the time of the latest close event in `latestClosure`. */
|
|
355
|
+
const latestCloser = Effect.fn("plan.latestCloser")(function* (latestClosure: unknown) {
|
|
356
|
+
const { nodes } = yield* decodeClosure(latestClosure);
|
|
357
|
+
if (nodes.length > 1)
|
|
358
|
+
return yield* new GraphqlError({ message: "gh api graphql returned malformed latest closure" });
|
|
359
|
+
if (nodes.length === 0) return { closer: undefined, closedEventAt: undefined };
|
|
360
|
+
const event = yield* decodeClosedEvent(nodes[0]);
|
|
361
|
+
const rawCloser = field(nodes[0], "closer");
|
|
362
|
+
let closer: Closer | null = null;
|
|
363
|
+
if (event.closer?.__typename === "PullRequest")
|
|
364
|
+
closer = { __typename: "PullRequest", ...(yield* pullRequestNodes([rawCloser]))[0] };
|
|
365
|
+
else if (event.closer?.__typename === "Commit")
|
|
366
|
+
closer = { __typename: "Commit", ...(yield* decodeCommit(rawCloser)) };
|
|
367
|
+
else if (event.closer) closer = { __typename: "Other" };
|
|
368
|
+
return { closer, closedEventAt: event.createdAt };
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
function snapshotQuery(number: number | undefined, options: SnapshotOptions): string {
|
|
372
|
+
const issueFields =
|
|
373
|
+
number === undefined
|
|
374
|
+
? ""
|
|
375
|
+
: [
|
|
376
|
+
"number title body state stateReason url createdAt updatedAt",
|
|
377
|
+
issueConnectionSelection("labels", ISSUE_LABEL_FIELDS),
|
|
378
|
+
issueConnectionSelection("assignedActors", ASSIGNEE_FIELDS),
|
|
379
|
+
options.comments ? issueConnectionSelection("comments", COMMENT_FIELDS) : "",
|
|
380
|
+
options.history
|
|
381
|
+
? issueConnectionSelection(
|
|
382
|
+
"history:timelineItems",
|
|
383
|
+
LABELED_EVENT_FIELDS,
|
|
384
|
+
",itemTypes:[LABELED_EVENT]",
|
|
385
|
+
)
|
|
386
|
+
: "",
|
|
387
|
+
options.closure
|
|
388
|
+
? `latestClosure:timelineItems(last:1,itemTypes:[CLOSED_EVENT]){nodes{${CLOSED_EVENT_FIELDS}}}`
|
|
389
|
+
: "",
|
|
390
|
+
options.children ? issueConnectionSelection("subIssues", ISSUE_SUMMARY_FIELDS) : "",
|
|
391
|
+
options.parent ? "parent{number repository{nameWithOwner}}" : "",
|
|
392
|
+
].join(" ");
|
|
393
|
+
return `query($owner:String!,$name:String!${number === undefined ? "" : ",$number:Int!"}){${options.acting ? "viewer{login id}" : ""} repository(owner:$owner,name:$name){nameWithOwner visibility ${options.defaultBranch ? "defaultBranchRef{name}" : ""} ${options.labelLookup ? REPOSITORY_LABELS : ""} ${number === undefined ? "" : `issue(number:$number){${issueFields}}`}}}`;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
const decodeRepository = malformed(RepositoryFields, "repository");
|
|
397
|
+
const decodeDefaultBranch = malformed(DefaultBranch, "default branch");
|
|
398
|
+
const decodeLogin = decodeWith(
|
|
399
|
+
NonBlankString,
|
|
400
|
+
() => new GraphqlError({ message: ACTING_LOGIN_ERROR }),
|
|
401
|
+
);
|
|
402
|
+
const decodeViewerId = malformed(Schema.NonEmptyString, "viewer");
|
|
403
|
+
const decodeOptionalLabel = malformed(OptionalLabel, "repository labels");
|
|
404
|
+
|
|
405
|
+
/** The repository part of a snapshot. It records the repository for the later writes of the command. */
|
|
406
|
+
const readRepository = Effect.fn("plan.readRepository")(function* (
|
|
407
|
+
number: number | undefined,
|
|
408
|
+
options: SnapshotOptions,
|
|
409
|
+
) {
|
|
410
|
+
const data = yield* graphql(
|
|
411
|
+
snapshotQuery(number, options),
|
|
412
|
+
number === undefined ? {} : { number },
|
|
413
|
+
);
|
|
414
|
+
const repo = field(data, "repository");
|
|
415
|
+
const { nameWithOwner, visibility } = yield* decodeRepository(repo);
|
|
416
|
+
const defaultBranch = options.defaultBranch
|
|
417
|
+
? (yield* decodeDefaultBranch(field(repo, "defaultBranchRef"))).name
|
|
418
|
+
: undefined;
|
|
419
|
+
const repository = yield* PlanRepository;
|
|
420
|
+
repository.current = { nameWithOwner, visibility, defaultBranch } satisfies RepositoryInfo;
|
|
421
|
+
const viewer = field(data, "viewer");
|
|
422
|
+
const login = options.acting ? yield* decodeLogin(field(viewer, "login")) : undefined;
|
|
423
|
+
const viewerId = options.acting ? yield* decodeViewerId(field(viewer, "id")) : undefined;
|
|
424
|
+
let labelIds: Map<string, string | null> | undefined;
|
|
425
|
+
if (options.labelLookup) {
|
|
426
|
+
labelIds = new Map();
|
|
427
|
+
for (const name of PLAN_LABELS) {
|
|
428
|
+
const label = yield* decodeOptionalLabel(field(repo, name.split(":").at(-1) ?? name));
|
|
429
|
+
if (label !== null && token(label.name) !== name)
|
|
430
|
+
return yield* new GraphqlError({
|
|
431
|
+
message: "gh api graphql returned malformed repository labels",
|
|
432
|
+
});
|
|
433
|
+
labelIds.set(name, label?.id ?? null);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
const snapshot: RepositorySnapshot = { login, viewerId, labelIds };
|
|
437
|
+
return { repo, snapshot };
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
/** The repository read of a command without an issue: the acting login and the plan label ids. */
|
|
441
|
+
export const readRepositorySnapshot = Effect.fn("plan.readRepositorySnapshot")(function* (
|
|
442
|
+
options: SnapshotOptions,
|
|
443
|
+
) {
|
|
444
|
+
return (yield* readRepository(undefined, options)).snapshot;
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
const decodeIssue = malformed(IssueFields, "plan issue");
|
|
448
|
+
const ownersMessage = "plan issue labels or assignees";
|
|
449
|
+
const decodeIssueLabels = malformed(Schema.Array(LabelWithId), ownersMessage);
|
|
450
|
+
const decodeAssignees = malformed(Schema.Array(Assignee), ownersMessage);
|
|
451
|
+
const decodeComments = malformed(Schema.Array(CommentFields), "issue comments");
|
|
452
|
+
const decodeHistory = malformed(Schema.Array(LabeledEvent), "label history");
|
|
453
|
+
const decodeParent = malformed(ParentFields, "parent issue");
|
|
454
|
+
|
|
455
|
+
/** One GraphQL read of the repository and the plan issue, with the connections that `options` select. */
|
|
456
|
+
export const readSnapshot = Effect.fn("plan.readSnapshot")(function* (
|
|
457
|
+
number: number,
|
|
458
|
+
options: SnapshotOptions = {},
|
|
459
|
+
) {
|
|
460
|
+
const { repo, snapshot } = yield* readRepository(number, options);
|
|
461
|
+
const rawIssue = field(repo, "issue");
|
|
462
|
+
const issue = yield* decodeIssue(rawIssue);
|
|
463
|
+
if (issue.number !== number)
|
|
464
|
+
return yield* new GraphqlError({ message: "gh api graphql returned malformed plan issue" });
|
|
465
|
+
const labelPages = yield* issueNodes(
|
|
466
|
+
number,
|
|
467
|
+
field(rawIssue, "labels"),
|
|
468
|
+
"labels",
|
|
469
|
+
ISSUE_LABEL_FIELDS,
|
|
470
|
+
);
|
|
471
|
+
const assigneePages = yield* issueNodes(
|
|
472
|
+
number,
|
|
473
|
+
field(rawIssue, "assignedActors"),
|
|
474
|
+
"assignedActors",
|
|
475
|
+
ASSIGNEE_FIELDS,
|
|
476
|
+
);
|
|
477
|
+
const labels: ReadonlyArray<LabelNode> = yield* decodeIssueLabels(labelPages);
|
|
478
|
+
const assignees = yield* decodeAssignees(assigneePages);
|
|
479
|
+
const comments: ReadonlyArray<IssueComment> = options.comments
|
|
480
|
+
? yield* decodeComments(
|
|
481
|
+
yield* issueNodes(number, field(rawIssue, "comments"), "comments", COMMENT_FIELDS),
|
|
482
|
+
)
|
|
483
|
+
: [];
|
|
484
|
+
const history = options.history
|
|
485
|
+
? (yield* decodeHistory(
|
|
486
|
+
yield* issueNodes(
|
|
487
|
+
number,
|
|
488
|
+
field(rawIssue, "history"),
|
|
489
|
+
"history:timelineItems",
|
|
490
|
+
LABELED_EVENT_FIELDS,
|
|
491
|
+
",itemTypes:[LABELED_EVENT]",
|
|
492
|
+
),
|
|
493
|
+
)).map((event) => event.label)
|
|
494
|
+
: [];
|
|
495
|
+
const closure = options.closure
|
|
496
|
+
? yield* latestCloser(field(rawIssue, "latestClosure"))
|
|
497
|
+
: { closer: undefined, closedEventAt: undefined };
|
|
498
|
+
const children = options.children
|
|
499
|
+
? yield* issueSummaries(
|
|
500
|
+
yield* issueNodes(number, field(rawIssue, "subIssues"), "subIssues", ISSUE_SUMMARY_FIELDS),
|
|
501
|
+
"sub-issues",
|
|
502
|
+
)
|
|
503
|
+
: [];
|
|
504
|
+
const parent: ParentLink | null | undefined = options.parent
|
|
505
|
+
? yield* decodeParent(field(rawIssue, "parent"))
|
|
506
|
+
: undefined;
|
|
507
|
+
const planIssue: PlanIssue = {
|
|
508
|
+
number,
|
|
509
|
+
title: issue.title,
|
|
510
|
+
body: issue.body,
|
|
511
|
+
state: issue.state,
|
|
512
|
+
stateReason: issue.stateReason,
|
|
513
|
+
url: issue.url,
|
|
514
|
+
labels,
|
|
515
|
+
assignees,
|
|
516
|
+
comments,
|
|
517
|
+
history,
|
|
518
|
+
closer: closure.closer,
|
|
519
|
+
closedEventAt: closure.closedEventAt,
|
|
520
|
+
children,
|
|
521
|
+
parent,
|
|
522
|
+
claimantId: undefined,
|
|
523
|
+
};
|
|
524
|
+
const result: IssueSnapshot = { ...snapshot, issue: planIssue };
|
|
525
|
+
return result;
|
|
526
|
+
});
|
|
527
|
+
|
|
528
|
+
/** The repository that the latest snapshot named. Every caller reads a snapshot first. */
|
|
529
|
+
export const currentRepository = Effect.fn("plan.currentRepository")(function* () {
|
|
530
|
+
const repository = yield* PlanRepository;
|
|
531
|
+
if (repository.current === undefined)
|
|
532
|
+
return yield* Effect.die(new Error("no repository was read before a write"));
|
|
533
|
+
return repository.current;
|
|
534
|
+
});
|
|
535
|
+
|
|
536
|
+
const decodePreWrite = decodeWith(
|
|
537
|
+
PreWriteFields,
|
|
538
|
+
() => new GhError({ message: "gh issue view returned malformed plan issue" }),
|
|
539
|
+
);
|
|
540
|
+
|
|
541
|
+
/** The pre-write read: the issue as GitHub stores it now, with the node ids that the write mutation needs. */
|
|
542
|
+
export const preWriteIssue = Effect.fn("plan.preWriteIssue")(function* (number: number) {
|
|
543
|
+
const { nameWithOwner } = yield* currentRepository();
|
|
544
|
+
const output = yield* runGh([
|
|
545
|
+
"issue",
|
|
546
|
+
"view",
|
|
547
|
+
String(number),
|
|
548
|
+
"--json",
|
|
549
|
+
PRE_WRITE_FIELDS,
|
|
550
|
+
"--repo",
|
|
551
|
+
nameWithOwner,
|
|
552
|
+
]);
|
|
553
|
+
return yield* decodePreWrite(yield* parseJson(output, "gh issue view"));
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
/** The pre-write read before a state change that a rerun cannot take back: a later owner is refused. */
|
|
557
|
+
export const ownedPreWriteIssue = Effect.fn("plan.ownedPreWriteIssue")(function* (
|
|
558
|
+
number: number,
|
|
559
|
+
login: string | undefined,
|
|
560
|
+
) {
|
|
561
|
+
const current = yield* preWriteIssue(number);
|
|
562
|
+
if (current.assignees.some((owner) => !Predicate.isString(owner.login) || !owner.login))
|
|
563
|
+
return yield* new GhError({ message: "gh issue view returned malformed plan issue" });
|
|
564
|
+
const foreign = current.assignees.find((owner) => owner.login !== login);
|
|
565
|
+
if (foreign)
|
|
566
|
+
return yield* new PlanRefusal({
|
|
567
|
+
message: `plan #${number} is owned by ${String(foreign.login)}`,
|
|
568
|
+
});
|
|
569
|
+
return current;
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
const decodeCreatedLabel = malformed(LabelWithId, "repository labels");
|
|
573
|
+
|
|
574
|
+
/** A status write can target a phase label that the repository lacks: create it as `new` does, then read its id. */
|
|
575
|
+
export const createdLabelId = Effect.fn("plan.createdLabelId")(function* (name: string) {
|
|
576
|
+
const { nameWithOwner } = yield* currentRepository();
|
|
577
|
+
yield* runGh(["label", "create", name, "--repo", nameWithOwner]);
|
|
578
|
+
const query = `query($owner:String!,$name:String!){repository(owner:$owner,name:$name){label(name:${JSON.stringify(name)}){name id}}}`;
|
|
579
|
+
const label = yield* decodeCreatedLabel(
|
|
580
|
+
field(field(yield* graphql(query), "repository"), "label"),
|
|
581
|
+
);
|
|
582
|
+
if (token(label.name) !== name)
|
|
583
|
+
return yield* new GraphqlError({
|
|
584
|
+
message: "gh api graphql returned malformed repository labels",
|
|
585
|
+
});
|
|
586
|
+
return label.id;
|
|
587
|
+
});
|
|
588
|
+
|
|
589
|
+
/** Write `body` to a new private temporary file, run `use` with its path, and remove the file. */
|
|
590
|
+
export const withBodyFile = <A, E, R>(
|
|
591
|
+
body: string,
|
|
592
|
+
use: (file: string) => Effect.Effect<A, E, R>,
|
|
593
|
+
): Effect.Effect<A, E | FileError, R | PlanFiles> =>
|
|
594
|
+
Effect.acquireUseRelease(
|
|
595
|
+
stateDirectory().pipe(
|
|
596
|
+
Effect.map((directory) => path.join(directory, `body-${process.pid}-${randomUUID()}.md`)),
|
|
597
|
+
),
|
|
598
|
+
(file) =>
|
|
599
|
+
PlanFiles.use((files) => files.createExclusive(file, body, 0o600)).pipe(
|
|
600
|
+
Effect.andThen(use(file)),
|
|
601
|
+
),
|
|
602
|
+
(file) => PlanFiles.use((files) => files.remove(file)),
|
|
603
|
+
);
|
|
604
|
+
|
|
605
|
+
export interface IssueWrite {
|
|
606
|
+
readonly body?: string;
|
|
607
|
+
readonly add?: string;
|
|
608
|
+
readonly remove?: ReadonlyArray<string>;
|
|
609
|
+
readonly labelIds?: ReadonlyMap<string, string | null>;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
interface MutationField {
|
|
613
|
+
readonly mutation: string;
|
|
614
|
+
readonly input: string;
|
|
615
|
+
readonly payload: "issue" | "labelable";
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
const decodeStored = malformed(StoredIssue, "stored plan issue");
|
|
619
|
+
const decodeStoredLabels = malformed(Schema.Array(LabelName), "labels");
|
|
620
|
+
|
|
621
|
+
// A write is the pre-write read plus one GraphQL request (#89). GitHub runs its mutation fields in order:
|
|
622
|
+
// updateIssue first, so the body and the claim of an unassigned plan land in one write; then discrete label
|
|
623
|
+
// additions and removals, so a label that someone else adds meanwhile survives. The last field returns the
|
|
624
|
+
// stored state, which the post-write checks read.
|
|
625
|
+
export const writeIssueIfUnchanged = Effect.fn("plan.writeIssueIfUnchanged")(function* (
|
|
626
|
+
issue: PlanIssue,
|
|
627
|
+
{ body, add, remove = [], labelIds }: IssueWrite = {},
|
|
628
|
+
) {
|
|
629
|
+
const claimantId = issue.claimantId;
|
|
630
|
+
if (body === undefined && !add && remove.length === 0 && claimantId === undefined) return;
|
|
631
|
+
const current = yield* preWriteIssue(issue.number);
|
|
632
|
+
if (current.body !== issue.body)
|
|
633
|
+
return yield* new PlanRefusal({ message: "plan issue changed remotely; re-read and retry" });
|
|
634
|
+
// A claim follows the pre-write read: an owner that appeared after the snapshot is refused before any write.
|
|
635
|
+
const foreign =
|
|
636
|
+
claimantId === undefined
|
|
637
|
+
? undefined
|
|
638
|
+
: current.assignees.find((owner) => owner.id !== claimantId);
|
|
639
|
+
if (foreign)
|
|
640
|
+
return yield* new PlanRefusal({
|
|
641
|
+
message: `plan #${issue.number} is owned by ${String(foreign.login)}`,
|
|
642
|
+
});
|
|
643
|
+
const idLists: Array<readonly [string, ReadonlyArray<string>]> = [];
|
|
644
|
+
const fields: Array<MutationField> = [];
|
|
645
|
+
if (body !== undefined || claimantId !== undefined) {
|
|
646
|
+
const input = ["id:$issue"];
|
|
647
|
+
if (body !== undefined) input.push("body:$body");
|
|
648
|
+
if (claimantId !== undefined) {
|
|
649
|
+
idLists.push([
|
|
650
|
+
"assignees",
|
|
651
|
+
[...new Set([...current.assignees.map((owner) => owner.id), claimantId])],
|
|
652
|
+
]);
|
|
653
|
+
input.push("assigneeIds:$assignees");
|
|
654
|
+
}
|
|
655
|
+
fields.push({ mutation: "updateIssue", input: input.join(","), payload: "issue" });
|
|
656
|
+
}
|
|
657
|
+
if (add) {
|
|
658
|
+
idLists.push(["add", [labelIds?.get(add) ?? (yield* createdLabelId(add))]]);
|
|
659
|
+
fields.push({
|
|
660
|
+
mutation: "addLabelsToLabelable",
|
|
661
|
+
input: "labelableId:$issue,labelIds:$add",
|
|
662
|
+
payload: "labelable",
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
const removed = new Set(remove.map(token));
|
|
666
|
+
const removeIds = issue.labels
|
|
667
|
+
.filter((label) => removed.has(token(label.name)))
|
|
668
|
+
.map((label) => label.id);
|
|
669
|
+
if (removeIds.length) {
|
|
670
|
+
idLists.push(["remove", removeIds]);
|
|
671
|
+
fields.push({
|
|
672
|
+
mutation: "removeLabelsFromLabelable",
|
|
673
|
+
input: "labelableId:$issue,labelIds:$remove",
|
|
674
|
+
payload: "labelable",
|
|
675
|
+
});
|
|
676
|
+
}
|
|
677
|
+
const declarations = [
|
|
678
|
+
"$issue:ID!",
|
|
679
|
+
...(body === undefined ? [] : ["$body:String!"]),
|
|
680
|
+
...idLists.map(([name]) => `$${name}:[ID!]!`),
|
|
681
|
+
];
|
|
682
|
+
const selections = fields.map(({ mutation, input, payload }, index) => {
|
|
683
|
+
const stored =
|
|
684
|
+
payload === "issue"
|
|
685
|
+
? `issue{${STORED_ISSUE_FIELDS}}`
|
|
686
|
+
: `labelable{... on Issue{${STORED_ISSUE_FIELDS}}}`;
|
|
687
|
+
return `${mutation}(input:{${input}}){${index === fields.length - 1 ? stored : "clientMutationId"}}`;
|
|
688
|
+
});
|
|
689
|
+
const send = (bodyFile?: string) =>
|
|
690
|
+
graphqlData([
|
|
691
|
+
"-f",
|
|
692
|
+
`query=mutation(${declarations.join(",")}){${selections.join(" ")}}`,
|
|
693
|
+
"-f",
|
|
694
|
+
`issue=${current.id}`,
|
|
695
|
+
// gh passes an @file field byte for byte; any other -F value gets type conversion and placeholder filling.
|
|
696
|
+
...(bodyFile === undefined ? [] : ["-F", `body=@${bodyFile}`]),
|
|
697
|
+
...idLists.flatMap(([name, ids]) => ids.flatMap((id) => ["-f", `${name}[]=${id}`])),
|
|
698
|
+
]);
|
|
699
|
+
const data = body === undefined ? yield* send() : yield* withBodyFile(body, send);
|
|
700
|
+
const last = fields[fields.length - 1];
|
|
701
|
+
const rawStored = field(field(data, last.mutation), last.payload);
|
|
702
|
+
const stored = yield* decodeStored(rawStored);
|
|
703
|
+
if (body !== undefined && stored.body !== body)
|
|
704
|
+
return yield* new PlanRefusal({ message: "plan issue body differs after edit" });
|
|
705
|
+
if (!add && remove.length === 0) return;
|
|
706
|
+
const storedLabels = yield* decodeStoredLabels(
|
|
707
|
+
yield* issueNodes(issue.number, field(rawStored, "labels"), "labels", "name"),
|
|
708
|
+
);
|
|
709
|
+
const names = storedLabels.map((label) => token(label.name));
|
|
710
|
+
if ((add && !names.includes(add)) || remove.some((label) => names.includes(token(label))))
|
|
711
|
+
return yield* new PlanRefusal({ message: "plan issue labels differ after edit" });
|
|
712
|
+
});
|
|
713
|
+
|
|
714
|
+
export interface PullRequestRead {
|
|
715
|
+
readonly number: number;
|
|
716
|
+
readonly url: string;
|
|
717
|
+
readonly merged: boolean;
|
|
718
|
+
readonly mergedAt: string | null;
|
|
719
|
+
readonly baseRefName: string;
|
|
720
|
+
readonly body: string | null;
|
|
721
|
+
readonly closesPlan: boolean;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
const decodePullRequest = malformed(
|
|
725
|
+
Schema.Struct({
|
|
726
|
+
nameWithOwner: Schema.String,
|
|
727
|
+
pullRequest: PullRequestFieldsRead,
|
|
728
|
+
}),
|
|
729
|
+
"pull request",
|
|
730
|
+
);
|
|
731
|
+
const decodeClosingReferences = malformed(
|
|
732
|
+
Schema.Array(ClosingReference),
|
|
733
|
+
"closing issue references",
|
|
734
|
+
);
|
|
735
|
+
|
|
736
|
+
// Pull request `number`: whether, when, and where it merged, its description, and whether GitHub lists plan
|
|
737
|
+
// `planNumber` of this repository among the issues that it closes.
|
|
738
|
+
export const readPullRequest = Effect.fn("plan.readPullRequest")(function* (
|
|
739
|
+
number: number,
|
|
740
|
+
planNumber: number,
|
|
741
|
+
) {
|
|
742
|
+
const references = (after: boolean): string =>
|
|
743
|
+
issueConnectionSelection(
|
|
744
|
+
"closingIssuesReferences",
|
|
745
|
+
"number repository{nameWithOwner}",
|
|
746
|
+
"",
|
|
747
|
+
after,
|
|
748
|
+
);
|
|
749
|
+
const query = `query($owner:String!,$name:String!,$pr:Int!){repository(owner:$owner,name:$name){nameWithOwner pullRequest(number:$pr){url merged mergedAt baseRefName body ${references(false)}}}}`;
|
|
750
|
+
const rawRepo = field(yield* graphql(query, { pr: number }), "repository");
|
|
751
|
+
const repo = yield* decodePullRequest(rawRepo);
|
|
752
|
+
const { pullRequest } = repo;
|
|
753
|
+
const mergedAt = pullRequest.mergedAt;
|
|
754
|
+
if (
|
|
755
|
+
pullRequest.merged &&
|
|
756
|
+
!(Predicate.isString(mergedAt) && Number.isFinite(Date.parse(mergedAt)))
|
|
757
|
+
)
|
|
758
|
+
return yield* new GraphqlError({ message: "gh api graphql returned malformed pull request" });
|
|
759
|
+
const pageQuery = `query($owner:String!,$name:String!,$pr:Int!,$after:String!){repository(owner:$owner,name:$name){pullRequest(number:$pr){${references(true)}}}}`;
|
|
760
|
+
const closed = yield* decodeClosingReferences(
|
|
761
|
+
yield* connectionNodes(
|
|
762
|
+
field(field(rawRepo, "pullRequest"), "closingIssuesReferences"),
|
|
763
|
+
"closing issue references",
|
|
764
|
+
(after) =>
|
|
765
|
+
graphql(pageQuery, { pr: number, after }).pipe(
|
|
766
|
+
Effect.map((data) =>
|
|
767
|
+
field(field(field(data, "repository"), "pullRequest"), "closingIssuesReferences"),
|
|
768
|
+
),
|
|
769
|
+
),
|
|
770
|
+
),
|
|
771
|
+
);
|
|
772
|
+
const read: PullRequestRead = {
|
|
773
|
+
number,
|
|
774
|
+
url: pullRequest.url,
|
|
775
|
+
merged: pullRequest.merged,
|
|
776
|
+
mergedAt: Predicate.isString(mergedAt) ? mergedAt : null,
|
|
777
|
+
baseRefName: pullRequest.baseRefName,
|
|
778
|
+
body: pullRequest.body,
|
|
779
|
+
closesPlan: closed.some(
|
|
780
|
+
(issue) =>
|
|
781
|
+
issue.number === planNumber && issue.repository.nameWithOwner === repo.nameWithOwner,
|
|
782
|
+
),
|
|
783
|
+
};
|
|
784
|
+
return read;
|
|
785
|
+
});
|
|
786
|
+
|
|
787
|
+
const decodeRestIssue = decodeWith(
|
|
788
|
+
RestIssue,
|
|
789
|
+
() => new GhError({ message: "gh api returned a malformed issue" }),
|
|
790
|
+
);
|
|
791
|
+
|
|
792
|
+
// A gh release without `issue create --parent` gets the REST sub-issues API, which takes the issue's database id.
|
|
793
|
+
export const linkSubIssue = Effect.fn("plan.linkSubIssue")(
|
|
794
|
+
function* (parent: number, number: number) {
|
|
795
|
+
const { nameWithOwner } = yield* currentRepository();
|
|
796
|
+
const child = yield* decodeRestIssue(
|
|
797
|
+
yield* parseJson(yield* runGh(["api", `repos/${nameWithOwner}/issues/${number}`]), "gh api"),
|
|
798
|
+
);
|
|
799
|
+
yield* runGh([
|
|
800
|
+
"api",
|
|
801
|
+
`repos/${nameWithOwner}/issues/${parent}/sub_issues`,
|
|
802
|
+
"--method",
|
|
803
|
+
"POST",
|
|
804
|
+
"-F",
|
|
805
|
+
`sub_issue_id=${child.id}`,
|
|
806
|
+
]);
|
|
807
|
+
},
|
|
808
|
+
(effect, parent, number) =>
|
|
809
|
+
Effect.mapError(
|
|
810
|
+
effect,
|
|
811
|
+
(error) =>
|
|
812
|
+
new GhError({
|
|
813
|
+
message: `plan #${number} was created, but its link to parent #${parent} failed: ${error.message}`,
|
|
814
|
+
}),
|
|
815
|
+
),
|
|
816
|
+
);
|