@leitwerk-dev/github 0.0.0-bootstrap.0 → 0.2.1
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/README.md +139 -1
- package/dist/LICENSE +13 -0
- package/dist/authorization.d.ts +16 -0
- package/dist/authorization.d.ts.map +1 -0
- package/dist/binding.d.ts +5 -0
- package/dist/binding.d.ts.map +1 -0
- package/dist/capability.d.ts +11 -0
- package/dist/capability.d.ts.map +1 -0
- package/dist/chunk-6X3F3VHK.js +344 -0
- package/dist/chunk-6X3F3VHK.js.map +1 -0
- package/dist/client.d.ts +200 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/external.d.ts +150 -0
- package/dist/external.d.ts.map +1 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +790 -0
- package/dist/index.js.map +1 -0
- package/dist/issue-provider.d.ts +8 -0
- package/dist/issue-provider.d.ts.map +1 -0
- package/dist/issue-watcher.d.ts +31 -0
- package/dist/issue-watcher.d.ts.map +1 -0
- package/dist/poll-report.d.ts +22 -0
- package/dist/poll-report.d.ts.map +1 -0
- package/dist/provider.d.ts +8 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/testing/tool-fixture.d.ts +45 -0
- package/dist/testing/tool-fixture.d.ts.map +1 -0
- package/dist/testing.d.ts +145 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +322 -0
- package/dist/testing.js.map +1 -0
- package/dist/tools.d.ts +4 -0
- package/dist/tools.d.ts.map +1 -0
- package/package.json +54 -14
- package/src/authorization.ts +62 -0
- package/src/binding.ts +7 -0
- package/src/capability.ts +16 -0
- package/src/client.ts +526 -0
- package/src/external.ts +192 -0
- package/src/index.ts +65 -0
- package/src/issue-provider.ts +278 -0
- package/src/issue-watcher.ts +45 -0
- package/src/poll-report.ts +47 -0
- package/src/provider.ts +216 -0
- package/src/testing/tool-fixture.ts +126 -0
- package/src/testing.ts +466 -0
- package/src/tools.ts +287 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { coreHostCapabilities, type LeitwerkExtensionModule } from "@leitwerk-dev/process-sdk";
|
|
2
|
+
import { type GitHubIntegration, githubIntegration } from "./capability.js";
|
|
3
|
+
import { GitHubClient, parseGitHubProfiles } from "./client.js";
|
|
4
|
+
import { createGitHubProvider } from "./provider.js";
|
|
5
|
+
import { registerGitHubTools } from "./tools.js";
|
|
6
|
+
|
|
7
|
+
/** @internal */
|
|
8
|
+
const manifest = {
|
|
9
|
+
id: "github",
|
|
10
|
+
/** @internal */
|
|
11
|
+
version: "0.1.9",
|
|
12
|
+
} as const;
|
|
13
|
+
|
|
14
|
+
/** @public */
|
|
15
|
+
const extension: LeitwerkExtensionModule = {
|
|
16
|
+
manifest,
|
|
17
|
+
setupServer(api, config) {
|
|
18
|
+
const profiles = parseGitHubProfiles(config);
|
|
19
|
+
const integration: GitHubIntegration = {
|
|
20
|
+
client(profile) {
|
|
21
|
+
const value = profiles.get(profile);
|
|
22
|
+
if (!value) throw new Error(`Unknown GitHub profile '${profile}'`);
|
|
23
|
+
return new GitHubClient(value);
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
setupGitHubIntegration(api, integration);
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export default extension;
|
|
31
|
+
|
|
32
|
+
/** Register shared tools and polling with an explicit integration. @public */
|
|
33
|
+
export function setupGitHubIntegration(
|
|
34
|
+
api: Parameters<NonNullable<LeitwerkExtensionModule["setupServer"]>>[0],
|
|
35
|
+
integration: GitHubIntegration,
|
|
36
|
+
options: {
|
|
37
|
+
/** @public */
|
|
38
|
+
now?: () => number;
|
|
39
|
+
} = {},
|
|
40
|
+
) {
|
|
41
|
+
api.provide(githubIntegration, integration);
|
|
42
|
+
const deps = api.get(coreHostCapabilities.serverSetup);
|
|
43
|
+
if (!deps || Array.isArray(deps)) return;
|
|
44
|
+
registerGitHubTools(api, integration);
|
|
45
|
+
return createGitHubProvider(deps, integration, options);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export { resolveGitHubProjectBinding } from "./binding.js";
|
|
49
|
+
export type { GitHubIntegration } from "./capability.js";
|
|
50
|
+
export { githubIntegration } from "./capability.js";
|
|
51
|
+
export type {
|
|
52
|
+
GitHubCheckSummary,
|
|
53
|
+
GitHubGitIdentity,
|
|
54
|
+
GitHubIssue,
|
|
55
|
+
GitHubPullRequest,
|
|
56
|
+
} from "./client.js";
|
|
57
|
+
export {
|
|
58
|
+
GITHUB_CHECKS_KIND,
|
|
59
|
+
GITHUB_ISSUE_CANCELLED_KIND,
|
|
60
|
+
GITHUB_PR_FEEDBACK_KIND,
|
|
61
|
+
GITHUB_PR_STATE_KIND,
|
|
62
|
+
GITHUB_PR_TERMINAL_KIND,
|
|
63
|
+
githubExternal,
|
|
64
|
+
} from "./external.js";
|
|
65
|
+
export { githubIssueWatcherSource } from "./issue-watcher.js";
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { asUnknownRecord } from "@leitwerk-dev/domain";
|
|
2
|
+
import {
|
|
3
|
+
type CoreServerSetupDeps,
|
|
4
|
+
type ExternalSourceArmingLike,
|
|
5
|
+
matchesRepository as matchesConfiguredRepository,
|
|
6
|
+
parseRepositoryFeedbackConfig as parseFeedbackConfig,
|
|
7
|
+
parseRepositoryIssueCancelledConfig as parseIssueCancelledConfig,
|
|
8
|
+
parseRepositoryPullRequestConfig as parsePrConfig,
|
|
9
|
+
type RegisteredProcessWatcherLike,
|
|
10
|
+
repositoryFeedbackBatch,
|
|
11
|
+
} from "@leitwerk-dev/process-sdk";
|
|
12
|
+
import { sameSubscription } from "@leitwerk-dev/repository-rebase";
|
|
13
|
+
import { createPollSchedule, type emptyPollResult } from "@leitwerk-dev/watcher-utils";
|
|
14
|
+
import type { GitHubIntegration } from "./capability.js";
|
|
15
|
+
import type { GitHubIssue, GitHubRepository } from "./client.js";
|
|
16
|
+
import {
|
|
17
|
+
describeGitHubEvent,
|
|
18
|
+
GITHUB_CHECKS_KIND,
|
|
19
|
+
GITHUB_ISSUE_CANCELLED_KIND,
|
|
20
|
+
GITHUB_PR_FEEDBACK_KIND,
|
|
21
|
+
GITHUB_PR_TERMINAL_KIND,
|
|
22
|
+
} from "./external.js";
|
|
23
|
+
import {
|
|
24
|
+
type GitHubIssueWatcherConfig,
|
|
25
|
+
type GitHubIssueWatcherEvent,
|
|
26
|
+
githubIssueWatcherSource,
|
|
27
|
+
} from "./issue-watcher.js";
|
|
28
|
+
import { githubPollReporter } from "./poll-report.js";
|
|
29
|
+
|
|
30
|
+
function hasLabel(issue: GitHubIssue, label: string): boolean {
|
|
31
|
+
return issue.labels.some((candidate) => candidate.name === label);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function externalId(repo: GitHubRepository, issue: GitHubIssue): string {
|
|
35
|
+
return `github:${repo.full_name}#${issue.number}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export { matchesConfiguredRepository };
|
|
39
|
+
|
|
40
|
+
export function createGitHubIssuePolling(
|
|
41
|
+
deps: CoreServerSetupDeps,
|
|
42
|
+
integration: GitHubIntegration,
|
|
43
|
+
options: { now?: () => number } = {},
|
|
44
|
+
) {
|
|
45
|
+
const now = options.now ?? Date.now;
|
|
46
|
+
const due = createPollSchedule(now);
|
|
47
|
+
|
|
48
|
+
async function discover(
|
|
49
|
+
watcher: RegisteredProcessWatcherLike<GitHubIssueWatcherConfig, GitHubIssueWatcherEvent>,
|
|
50
|
+
result: ReturnType<typeof emptyPollResult>,
|
|
51
|
+
) {
|
|
52
|
+
const config = watcher.config;
|
|
53
|
+
const client = integration.client(config.profile);
|
|
54
|
+
for (const repo of await client.listRepositories()) {
|
|
55
|
+
if (!matchesConfiguredRepository(config, repo)) continue;
|
|
56
|
+
for (const issue of await client.listOpenIssues(repo.owner.login, repo.name)) {
|
|
57
|
+
if (!hasLabel(issue, config.labels.trigger) || hasLabel(issue, config.labels.done))
|
|
58
|
+
continue;
|
|
59
|
+
const id = externalId(repo, issue);
|
|
60
|
+
try {
|
|
61
|
+
if (deps.processes.listAll().some((process) => process.externalId === id)) {
|
|
62
|
+
result.skipped.push(id);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
const authorized = await client.authorizedTrigger(
|
|
66
|
+
repo.owner.login,
|
|
67
|
+
repo.name,
|
|
68
|
+
issue.number,
|
|
69
|
+
config.labels.trigger,
|
|
70
|
+
config.labels.done,
|
|
71
|
+
);
|
|
72
|
+
if (!authorized) {
|
|
73
|
+
result.skipped.push(`${id}:unauthorized`);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
const event: GitHubIssueWatcherEvent = {
|
|
77
|
+
profile: config.profile,
|
|
78
|
+
repository: repo,
|
|
79
|
+
issue: authorized.issue,
|
|
80
|
+
authorization: {
|
|
81
|
+
actor: authorized.actor,
|
|
82
|
+
eventId: authorized.eventId,
|
|
83
|
+
},
|
|
84
|
+
labels: config.labels,
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const guardedWatcher = {
|
|
88
|
+
...watcher,
|
|
89
|
+
async resolveLaunchAttempt(...args: Parameters<typeof watcher.resolveLaunchAttempt>) {
|
|
90
|
+
const attempt = await watcher.resolveLaunchAttempt(...args);
|
|
91
|
+
if (!attempt) return null;
|
|
92
|
+
return {
|
|
93
|
+
...attempt,
|
|
94
|
+
preparationChecks: [
|
|
95
|
+
...attempt.preparationChecks,
|
|
96
|
+
{
|
|
97
|
+
id: "github-trigger-authorization",
|
|
98
|
+
label: "Check GitHub trigger authorization",
|
|
99
|
+
async run() {
|
|
100
|
+
const rechecked = await client.authorizedTrigger(
|
|
101
|
+
repo.owner.login,
|
|
102
|
+
repo.name,
|
|
103
|
+
issue.number,
|
|
104
|
+
config.labels.trigger,
|
|
105
|
+
config.labels.done,
|
|
106
|
+
);
|
|
107
|
+
if (
|
|
108
|
+
!rechecked ||
|
|
109
|
+
rechecked.eventId !== authorized.eventId ||
|
|
110
|
+
rechecked.actor !== authorized.actor
|
|
111
|
+
)
|
|
112
|
+
throw new Error("GitHub trigger authorization changed before launch");
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
],
|
|
116
|
+
};
|
|
117
|
+
},
|
|
118
|
+
};
|
|
119
|
+
const launched = await deps.launchRuns.startWatcher(guardedWatcher, event, {
|
|
120
|
+
idempotencyKey: id,
|
|
121
|
+
});
|
|
122
|
+
if (launched.error) result.errors.push(`${id}:launch_failed:${launched.error}`);
|
|
123
|
+
else if (launched.process) result.created.push(id);
|
|
124
|
+
else result.skipped.push(id);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
result.errors.push(
|
|
127
|
+
`${id}:${error instanceof Error ? error.message : "discovery_failed"}`,
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async function pollExternal(result: ReturnType<typeof emptyPollResult>) {
|
|
135
|
+
const report = githubPollReporter(deps.externalSources, result);
|
|
136
|
+
const terminalArmings = deps.externalSources.listArmed(GITHUB_PR_TERMINAL_KIND);
|
|
137
|
+
const terminalInstances = new Set<string>();
|
|
138
|
+
async function poll<C extends { pollInterval?: string; disabled?: boolean }>(
|
|
139
|
+
kind: string,
|
|
140
|
+
parse: (value: unknown) => C | null,
|
|
141
|
+
read: (config: C, armed: ExternalSourceArmingLike) => Promise<void>,
|
|
142
|
+
) {
|
|
143
|
+
const armings =
|
|
144
|
+
kind === GITHUB_PR_TERMINAL_KIND ? terminalArmings : deps.externalSources.listArmed(kind);
|
|
145
|
+
for (const armed of armings) {
|
|
146
|
+
if (kind !== GITHUB_PR_TERMINAL_KIND && terminalInstances.has(armed.instanceId)) continue;
|
|
147
|
+
const config = parse(armed.resolved);
|
|
148
|
+
const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
|
|
149
|
+
if (!config || !due(key, config.pollInterval ?? "30s") || config.disabled) continue;
|
|
150
|
+
try {
|
|
151
|
+
await read(config, armed);
|
|
152
|
+
} catch (error) {
|
|
153
|
+
await report.observe(armed, {
|
|
154
|
+
refreshError: error instanceof Error ? error.message : "GitHub refresh failed",
|
|
155
|
+
});
|
|
156
|
+
const fallback = kind === GITHUB_CHECKS_KIND ? "checks_failed" : "poll_failed";
|
|
157
|
+
result.errors.push(`${armed.id}:${error instanceof Error ? error.message : fallback}`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
await poll(GITHUB_PR_TERMINAL_KIND, parsePrConfig, async (config, armed) => {
|
|
162
|
+
const pr = await integration
|
|
163
|
+
.client(config.profile)
|
|
164
|
+
.getPullRequest(config.owner, config.repo, config.prNumber);
|
|
165
|
+
if (!pr.merged && pr.state !== "closed") return;
|
|
166
|
+
if (
|
|
167
|
+
!deps.externalSources
|
|
168
|
+
.listArmed(GITHUB_PR_TERMINAL_KIND)
|
|
169
|
+
.some((current) => sameSubscription(armed, current))
|
|
170
|
+
)
|
|
171
|
+
return;
|
|
172
|
+
terminalInstances.add(armed.instanceId);
|
|
173
|
+
const outcome = pr.merged ? "merged" : "closed";
|
|
174
|
+
if (config.terminalOutcome && config.terminalOutcome !== outcome) return;
|
|
175
|
+
await report.fire(armed, { pullRequest: pr }, `${pr.number}:${outcome}`);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
await poll(
|
|
179
|
+
GITHUB_CHECKS_KIND,
|
|
180
|
+
(value) => ({ pollInterval: "30s", config: asUnknownRecord(value) ?? {} }),
|
|
181
|
+
async ({ config }, armed) => {
|
|
182
|
+
const client = integration.client(String(config.profile));
|
|
183
|
+
const pr = await client.getPullRequest(
|
|
184
|
+
String(config.owner),
|
|
185
|
+
String(config.repo),
|
|
186
|
+
Number(config.prNumber),
|
|
187
|
+
);
|
|
188
|
+
if (pr.state !== "open" || pr.head.sha !== config.headSha) return;
|
|
189
|
+
const checks = await client.getCheckSummary(
|
|
190
|
+
String(config.owner),
|
|
191
|
+
String(config.repo),
|
|
192
|
+
String(config.headSha),
|
|
193
|
+
);
|
|
194
|
+
if (checks.headSha !== config.headSha) return;
|
|
195
|
+
const refreshed = await client.getPullRequest(
|
|
196
|
+
String(config.owner),
|
|
197
|
+
String(config.repo),
|
|
198
|
+
Number(config.prNumber),
|
|
199
|
+
);
|
|
200
|
+
if (refreshed.state !== "open" || refreshed.merged || refreshed.head.sha !== checks.headSha)
|
|
201
|
+
return;
|
|
202
|
+
await report.observe(armed, {
|
|
203
|
+
observation: {
|
|
204
|
+
...describeGitHubEvent({ checks }),
|
|
205
|
+
observedAt: new Date(now()).toISOString(),
|
|
206
|
+
subject: `${config.owner}/${config.repo}#${config.prNumber}`,
|
|
207
|
+
revision: checks.headSha,
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
if (checks.status !== "failure") return;
|
|
211
|
+
await report.fire(
|
|
212
|
+
armed,
|
|
213
|
+
{ checks },
|
|
214
|
+
`${checks.headSha}:${checks.failed.map((run) => run.url).join(":")}`,
|
|
215
|
+
);
|
|
216
|
+
},
|
|
217
|
+
);
|
|
218
|
+
|
|
219
|
+
await poll(GITHUB_ISSUE_CANCELLED_KIND, parseIssueCancelledConfig, async (config, armed) => {
|
|
220
|
+
const issue = await integration
|
|
221
|
+
.client(config.profile)
|
|
222
|
+
.getIssue(config.owner, config.repo, config.issueNumber);
|
|
223
|
+
const reason =
|
|
224
|
+
issue.state === "closed"
|
|
225
|
+
? "issue_closed"
|
|
226
|
+
: hasLabel(issue, config.triggerLabel)
|
|
227
|
+
? null
|
|
228
|
+
: "trigger_label_removed";
|
|
229
|
+
if (!reason) return;
|
|
230
|
+
// A merge may close the issue between terminal polls. Preserve terminal
|
|
231
|
+
// reconciliation instead of treating that close as cancellation.
|
|
232
|
+
const terminal = terminalArmings
|
|
233
|
+
.filter((candidate) => candidate.instanceId === armed.instanceId)
|
|
234
|
+
.map((candidate) => parsePrConfig(candidate.resolved))
|
|
235
|
+
.find((candidate) => candidate && !candidate.disabled);
|
|
236
|
+
if (terminal) {
|
|
237
|
+
const pr = await integration
|
|
238
|
+
.client(terminal.profile)
|
|
239
|
+
.getPullRequest(terminal.owner, terminal.repo, terminal.prNumber);
|
|
240
|
+
if (pr.merged || pr.state === "closed") {
|
|
241
|
+
terminalInstances.add(armed.instanceId);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
await report.fire(armed, { issue, reason }, `${issue.number}:${reason}`);
|
|
246
|
+
});
|
|
247
|
+
await poll(GITHUB_PR_FEEDBACK_KIND, parseFeedbackConfig, async (config, armed) => {
|
|
248
|
+
const client = integration.client(config.profile);
|
|
249
|
+
const pr = await client.getPullRequest(config.owner, config.repo, config.prNumber);
|
|
250
|
+
if (pr.merged || pr.state !== "open") return;
|
|
251
|
+
const unseen = (
|
|
252
|
+
await client.listActionablePullRequestFeedback(config.owner, config.repo, config.prNumber)
|
|
253
|
+
).filter((item) => item.id > config[`${item.kind}Cursor`]);
|
|
254
|
+
|
|
255
|
+
const batch = repositoryFeedbackBatch(unseen, config, now());
|
|
256
|
+
if (batch) await report.fire(armed, batch.event, batch.mergeKey);
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return async (result: ReturnType<typeof emptyPollResult>) => {
|
|
261
|
+
const watchers = deps.processWatchers?.listBySource(githubIssueWatcherSource) ?? [];
|
|
262
|
+
for (const watcher of watchers) {
|
|
263
|
+
if (
|
|
264
|
+
!watcher.enabled ||
|
|
265
|
+
!due(`${watcher.processId}:${watcher.watcherId}`, watcher.config.pollInterval)
|
|
266
|
+
)
|
|
267
|
+
continue;
|
|
268
|
+
try {
|
|
269
|
+
await discover(watcher, result);
|
|
270
|
+
} catch (error) {
|
|
271
|
+
result.errors.push(
|
|
272
|
+
`${watcher.processId}:${watcher.watcherId}:${error instanceof Error ? error.message : "discovery_failed"}`,
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
await pollExternal(result);
|
|
277
|
+
};
|
|
278
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {
|
|
2
|
+
defineProcessWatcherSource,
|
|
3
|
+
parseRepositoryIssueWatcherConfig,
|
|
4
|
+
presentRepositoryIssueWatcherConfig,
|
|
5
|
+
type RepositoryIssueWatcherConfig,
|
|
6
|
+
} from "@leitwerk-dev/process-sdk";
|
|
7
|
+
import type { GitHubIssue, GitHubRepository } from "./client.js";
|
|
8
|
+
|
|
9
|
+
/** @public */
|
|
10
|
+
export interface GitHubIssueWatcherConfig extends RepositoryIssueWatcherConfig {}
|
|
11
|
+
|
|
12
|
+
/** @public */
|
|
13
|
+
export interface GitHubIssueWatcherEvent {
|
|
14
|
+
/** @public */
|
|
15
|
+
authorization: {
|
|
16
|
+
/** @internal */
|
|
17
|
+
actor: string;
|
|
18
|
+
/** @internal */
|
|
19
|
+
eventId: number;
|
|
20
|
+
};
|
|
21
|
+
/** @public */
|
|
22
|
+
profile: string;
|
|
23
|
+
/** @public */
|
|
24
|
+
repository: GitHubRepository;
|
|
25
|
+
/** @public */
|
|
26
|
+
issue: GitHubIssue;
|
|
27
|
+
/** @public */
|
|
28
|
+
labels: {
|
|
29
|
+
/** @public */
|
|
30
|
+
trigger: string;
|
|
31
|
+
/** @public */
|
|
32
|
+
done: string;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @public */
|
|
37
|
+
export const githubIssueWatcherSource = defineProcessWatcherSource<
|
|
38
|
+
GitHubIssueWatcherConfig,
|
|
39
|
+
GitHubIssueWatcherEvent
|
|
40
|
+
>({
|
|
41
|
+
id: "@leitwerk-public/github.issue",
|
|
42
|
+
label: "GitHub issue",
|
|
43
|
+
parseConfig: (raw) => parseRepositoryIssueWatcherConfig(raw, "github_issue", true),
|
|
44
|
+
presentConfig: presentRepositoryIssueWatcherConfig,
|
|
45
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createExternalSourcePollReporter,
|
|
3
|
+
type ExternalSourceArmingLike,
|
|
4
|
+
type ExternalSourceServiceLike,
|
|
5
|
+
} from "@leitwerk-dev/process-sdk";
|
|
6
|
+
import { sameSubscription } from "@leitwerk-dev/repository-rebase";
|
|
7
|
+
import {
|
|
8
|
+
GITHUB_CHECKS_KIND,
|
|
9
|
+
GITHUB_ISSUE_CANCELLED_KIND,
|
|
10
|
+
GITHUB_PR_FEEDBACK_KIND,
|
|
11
|
+
GITHUB_PR_STATE_KIND,
|
|
12
|
+
GITHUB_PR_TERMINAL_KIND,
|
|
13
|
+
GITHUB_RELEASE_KIND,
|
|
14
|
+
} from "./external.js";
|
|
15
|
+
|
|
16
|
+
export function githubPollReporter(
|
|
17
|
+
sources: ExternalSourceServiceLike,
|
|
18
|
+
result: { created: string[]; errors: string[] },
|
|
19
|
+
) {
|
|
20
|
+
const report = createExternalSourcePollReporter(sources, result, { forwardGeneration: true });
|
|
21
|
+
const current = (armed: ExternalSourceArmingLike) =>
|
|
22
|
+
[
|
|
23
|
+
GITHUB_CHECKS_KIND,
|
|
24
|
+
GITHUB_PR_STATE_KIND,
|
|
25
|
+
GITHUB_PR_TERMINAL_KIND,
|
|
26
|
+
GITHUB_PR_FEEDBACK_KIND,
|
|
27
|
+
GITHUB_ISSUE_CANCELLED_KIND,
|
|
28
|
+
GITHUB_RELEASE_KIND,
|
|
29
|
+
].some((kind) => sources.listArmed(kind).some((value) => sameSubscription(armed, value)));
|
|
30
|
+
return {
|
|
31
|
+
...report,
|
|
32
|
+
async fire(
|
|
33
|
+
armed: Parameters<typeof report.fire>[0],
|
|
34
|
+
event: Record<string, unknown>,
|
|
35
|
+
mergeKey: string,
|
|
36
|
+
) {
|
|
37
|
+
if (!current(armed as ExternalSourceArmingLike)) return false;
|
|
38
|
+
return report.fire(armed, event, mergeKey);
|
|
39
|
+
},
|
|
40
|
+
observe(
|
|
41
|
+
armed: Parameters<typeof report.observe>[0],
|
|
42
|
+
input: Parameters<typeof report.observe>[1],
|
|
43
|
+
) {
|
|
44
|
+
if (current(armed as ExternalSourceArmingLike)) return report.observe(armed, input);
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { asUnknownRecord } from "@leitwerk-dev/domain";
|
|
2
|
+
import type { CoreServerSetupDeps } from "@leitwerk-dev/process-sdk";
|
|
3
|
+
import { conflictEvidence, createConflictReporter } from "@leitwerk-dev/repository-rebase";
|
|
4
|
+
import { createPollSchedule, emptyPollResult } from "@leitwerk-dev/watcher-utils";
|
|
5
|
+
import type { GitHubIntegration } from "./capability.js";
|
|
6
|
+
import {
|
|
7
|
+
describeGitHubEvent,
|
|
8
|
+
GITHUB_PR_STATE_KIND,
|
|
9
|
+
GITHUB_RELEASE_KIND,
|
|
10
|
+
type GitHubPullRequestSourceConfig,
|
|
11
|
+
} from "./external.js";
|
|
12
|
+
import { createGitHubIssuePolling } from "./issue-provider.js";
|
|
13
|
+
import { githubPollReporter } from "./poll-report.js";
|
|
14
|
+
|
|
15
|
+
function parse(value: unknown): GitHubPullRequestSourceConfig | null {
|
|
16
|
+
const config = asUnknownRecord(value) ?? {};
|
|
17
|
+
if (
|
|
18
|
+
["profile", "owner", "repo", "headSha"].some(
|
|
19
|
+
(key) => typeof config[key] !== "string" || !(config[key] as string).trim(),
|
|
20
|
+
) ||
|
|
21
|
+
typeof config.prNumber !== "number"
|
|
22
|
+
)
|
|
23
|
+
return null;
|
|
24
|
+
return {
|
|
25
|
+
profile: config.profile as string,
|
|
26
|
+
owner: config.owner as string,
|
|
27
|
+
repo: config.repo as string,
|
|
28
|
+
prNumber: config.prNumber,
|
|
29
|
+
headSha: config.headSha as string,
|
|
30
|
+
lastConflictKey: typeof config.lastConflictKey === "string" ? config.lastConflictKey : null,
|
|
31
|
+
feedbackCursor: typeof config.feedbackCursor === "number" ? config.feedbackCursor : 0,
|
|
32
|
+
pollInterval: typeof config.pollInterval === "string" ? config.pollInterval : "30s",
|
|
33
|
+
disabled: config.disabled === true,
|
|
34
|
+
eventKinds: Array.isArray(config.eventKinds)
|
|
35
|
+
? config.eventKinds.filter(
|
|
36
|
+
(value): value is "checks" | "feedback" | "merged" | "closed" | "merge_conflict" =>
|
|
37
|
+
["checks", "feedback", "merged", "closed", "merge_conflict"].includes(String(value)),
|
|
38
|
+
)
|
|
39
|
+
: undefined,
|
|
40
|
+
checkStatuses: Array.isArray(config.checkStatuses)
|
|
41
|
+
? config.checkStatuses.filter((value): value is "pending" | "success" | "failure" =>
|
|
42
|
+
["pending", "success", "failure"].includes(String(value)),
|
|
43
|
+
)
|
|
44
|
+
: undefined,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function createGitHubProvider(
|
|
49
|
+
deps: CoreServerSetupDeps,
|
|
50
|
+
integration: GitHubIntegration,
|
|
51
|
+
options: { now?: () => number } = {},
|
|
52
|
+
) {
|
|
53
|
+
const due = createPollSchedule();
|
|
54
|
+
const pollIssues = createGitHubIssuePolling(deps, integration, options);
|
|
55
|
+
const reportConflict = createConflictReporter(deps.externalSources, GITHUB_PR_STATE_KIND);
|
|
56
|
+
return deps.polling.create({
|
|
57
|
+
id: "github",
|
|
58
|
+
pollInterval: () => "5s",
|
|
59
|
+
isEnabled: () => true,
|
|
60
|
+
defaultIntervalMs: 5_000,
|
|
61
|
+
async pollOnce() {
|
|
62
|
+
const result = emptyPollResult();
|
|
63
|
+
const report = githubPollReporter(deps.externalSources, result);
|
|
64
|
+
await pollIssues(result);
|
|
65
|
+
await report.poll(GITHUB_PR_STATE_KIND, async (armed) => {
|
|
66
|
+
const config = parse(armed.resolved);
|
|
67
|
+
if (!config) {
|
|
68
|
+
result.errors.push(`${armed.id}:invalid_config`);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
if (config.disabled) return;
|
|
72
|
+
const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
|
|
73
|
+
const now = options.now?.() ?? Date.now();
|
|
74
|
+
if (!due(key, config.pollInterval, now)) return;
|
|
75
|
+
try {
|
|
76
|
+
const client = integration.client(config.profile);
|
|
77
|
+
const pr = await client.getPullRequest(config.owner, config.repo, config.prNumber);
|
|
78
|
+
if (!config.eventKinds || config.eventKinds.includes("merge_conflict")) {
|
|
79
|
+
const conflict = conflictEvidence(config, pr, "github");
|
|
80
|
+
// GitHub's PR base SHA can lag the branch even while its state is behind.
|
|
81
|
+
if (conflict?.reason === "behind") {
|
|
82
|
+
const branch = await client.getCommit(config.owner, config.repo, conflict.baseBranch);
|
|
83
|
+
conflict.baseSha = branch.sha;
|
|
84
|
+
}
|
|
85
|
+
if (
|
|
86
|
+
await reportConflict(report, armed, conflict, config.lastConflictKey, {
|
|
87
|
+
summary: `PR #${pr.number} mergeability: ${pr.mergeable == null ? "unresolved" : (pr.mergeable_state ?? String(pr.mergeable))}`,
|
|
88
|
+
observedAt: new Date(now).toISOString(),
|
|
89
|
+
subject: `${config.owner}/${config.repo}#${pr.number}`,
|
|
90
|
+
revision: `${pr.head.sha}:${conflict?.baseSha ?? pr.base.sha}`,
|
|
91
|
+
})
|
|
92
|
+
)
|
|
93
|
+
return;
|
|
94
|
+
if (config.eventKinds?.length === 1) return;
|
|
95
|
+
}
|
|
96
|
+
let event: Record<string, unknown> | null = null;
|
|
97
|
+
let mergeKey = "";
|
|
98
|
+
if (pr.merged || pr.state === "closed") {
|
|
99
|
+
event = {
|
|
100
|
+
kind: pr.merged ? "merged" : "closed",
|
|
101
|
+
pullRequest: pr,
|
|
102
|
+
};
|
|
103
|
+
mergeKey = `terminal:${pr.number}:${pr.merged}`;
|
|
104
|
+
} else {
|
|
105
|
+
if (pr.head.sha !== config.headSha) return;
|
|
106
|
+
const readsFeedback = !config.eventKinds || config.eventKinds.includes("feedback");
|
|
107
|
+
const readsChecks = !config.eventKinds || config.eventKinds.includes("checks");
|
|
108
|
+
const [feedback, checks] = await Promise.all([
|
|
109
|
+
readsFeedback
|
|
110
|
+
? client.listActionablePullRequestFeedback(
|
|
111
|
+
config.owner,
|
|
112
|
+
config.repo,
|
|
113
|
+
config.prNumber,
|
|
114
|
+
)
|
|
115
|
+
: Promise.resolve([]),
|
|
116
|
+
readsChecks || (deps.externalSources.observe && armed.generation)
|
|
117
|
+
? client
|
|
118
|
+
.getCheckSummary(config.owner, config.repo, config.headSha)
|
|
119
|
+
.catch(async (error) => {
|
|
120
|
+
await report.observe(armed, {
|
|
121
|
+
refreshError:
|
|
122
|
+
error instanceof Error ? error.message : "Checks refresh failed",
|
|
123
|
+
});
|
|
124
|
+
if (readsChecks) throw error;
|
|
125
|
+
return null;
|
|
126
|
+
})
|
|
127
|
+
: Promise.resolve(null),
|
|
128
|
+
]);
|
|
129
|
+
if (checks && checks.headSha !== config.headSha) return;
|
|
130
|
+
const refreshed = await client.getPullRequest(
|
|
131
|
+
config.owner,
|
|
132
|
+
config.repo,
|
|
133
|
+
config.prNumber,
|
|
134
|
+
);
|
|
135
|
+
if (
|
|
136
|
+
refreshed.state !== "open" ||
|
|
137
|
+
refreshed.merged ||
|
|
138
|
+
refreshed.head.sha !== config.headSha
|
|
139
|
+
)
|
|
140
|
+
return;
|
|
141
|
+
if (checks && deps.externalSources.observe && armed.generation) {
|
|
142
|
+
const description = describeGitHubEvent({ kind: "checks", checks });
|
|
143
|
+
await report.observe(armed, {
|
|
144
|
+
observation: {
|
|
145
|
+
...description,
|
|
146
|
+
observedAt: new Date(now).toISOString(),
|
|
147
|
+
subject: `${config.owner}/${config.repo}#${config.prNumber}`,
|
|
148
|
+
revision: checks.headSha,
|
|
149
|
+
},
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
const unseen = feedback.filter(
|
|
153
|
+
(item) => item.id > config.feedbackCursor && item.author !== client.profile.botLogin,
|
|
154
|
+
);
|
|
155
|
+
if (unseen.length) {
|
|
156
|
+
const feedbackCursor = Math.max(...unseen.map((item) => item.id));
|
|
157
|
+
event = { kind: "feedback", feedback, feedbackCursor };
|
|
158
|
+
mergeKey = `feedback:${feedbackCursor}`;
|
|
159
|
+
} else if (readsChecks && checks && checks.status !== "pending") {
|
|
160
|
+
event = { kind: "checks", checks };
|
|
161
|
+
mergeKey = `checks:${checks.headSha}:${checks.status}`;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
if (
|
|
165
|
+
!event ||
|
|
166
|
+
(config.eventKinds &&
|
|
167
|
+
!config.eventKinds.includes(
|
|
168
|
+
String(event.kind) as (typeof config.eventKinds)[number],
|
|
169
|
+
)) ||
|
|
170
|
+
(event.kind === "checks" &&
|
|
171
|
+
config.checkStatuses &&
|
|
172
|
+
!config.checkStatuses.includes(
|
|
173
|
+
(event.checks as { status: "pending" | "success" | "failure" }).status,
|
|
174
|
+
))
|
|
175
|
+
)
|
|
176
|
+
return;
|
|
177
|
+
await report.fire(armed, event, mergeKey);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
await report.observe(armed, {
|
|
180
|
+
refreshError: error instanceof Error ? error.message : "PR refresh failed",
|
|
181
|
+
});
|
|
182
|
+
throw error;
|
|
183
|
+
}
|
|
184
|
+
});
|
|
185
|
+
await report.poll(GITHUB_RELEASE_KIND, async (armed) => {
|
|
186
|
+
const config = asUnknownRecord(armed.resolved) ?? {};
|
|
187
|
+
if (
|
|
188
|
+
typeof config.profile !== "string" ||
|
|
189
|
+
typeof config.owner !== "string" ||
|
|
190
|
+
typeof config.repo !== "string" ||
|
|
191
|
+
typeof config.mergeSha !== "string"
|
|
192
|
+
)
|
|
193
|
+
return;
|
|
194
|
+
if (config.disabled === true) return;
|
|
195
|
+
const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
|
|
196
|
+
const now = options.now?.() ?? Date.now();
|
|
197
|
+
if (!due(key, typeof config.pollInterval === "string" ? config.pollInterval : "30s", now))
|
|
198
|
+
return;
|
|
199
|
+
const client = integration.client(config.profile);
|
|
200
|
+
for (const release of await client.listReleases(config.owner, config.repo)) {
|
|
201
|
+
if (release.draft || release.prerelease) continue;
|
|
202
|
+
const commit = await client.getCommit(config.owner, config.repo, release.tag_name);
|
|
203
|
+
if (!(await client.isAncestor(config.owner, config.repo, config.mergeSha, commit.sha)))
|
|
204
|
+
continue;
|
|
205
|
+
await report.fire(
|
|
206
|
+
armed,
|
|
207
|
+
{ release, commitSha: commit.sha },
|
|
208
|
+
`${release.id}:${commit.sha}`,
|
|
209
|
+
);
|
|
210
|
+
break;
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
return result;
|
|
214
|
+
},
|
|
215
|
+
});
|
|
216
|
+
}
|