@rmartz/pr-policy 1.6.0 → 1.7.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.
@@ -8,7 +8,7 @@ import {
8
8
  postVerdict,
9
9
  resolveRepoTarget,
10
10
  selectChecks
11
- } from "../chunk-UI7QG6XT.js";
11
+ } from "../chunk-JJ5AKEQ3.js";
12
12
 
13
13
  // src/bin/pr-policy.ts
14
14
  import { readFile } from "fs/promises";
@@ -1796,10 +1796,10 @@ function buildReport(findings) {
1796
1796
  outcome = "pending";
1797
1797
  title = `Waiting on ${plural(holds.length, "human sign-off")}`;
1798
1798
  }
1799
- const lines2 = findings.map(
1799
+ const lines = findings.map(
1800
1800
  (finding) => `- ${ICONS[finding.effect]} **${finding.check}**: ${finding.message}`
1801
1801
  );
1802
- const summary = lines2.length > 0 ? lines2.join("\n") : "No policy findings.";
1802
+ const summary = lines.length > 0 ? lines.join("\n") : "No policy findings.";
1803
1803
  return { outcome, title, summary, findings };
1804
1804
  }
1805
1805
 
@@ -2091,6 +2091,48 @@ async function removeLabel(repo, issue, label, call = {}) {
2091
2091
  return out !== null ? out.trim() : null;
2092
2092
  }
2093
2093
 
2094
+ // src/github/client.ts
2095
+ function createGhClient(options = {}) {
2096
+ const call = { cwd: options.cwd };
2097
+ const lines = (out) => out.split("\n").filter((line) => line.trim() !== "").map((line) => JSON.parse(line));
2098
+ return {
2099
+ async getJson(path) {
2100
+ const out = await ghCall({ argv: ["gh", "api", path] }, null, call);
2101
+ return out === null ? null : JSON.parse(out);
2102
+ },
2103
+ async list(path, key) {
2104
+ const jq = key === void 0 ? ".[]" : `.${key}[]`;
2105
+ const out = await ghCall({ argv: ["gh", "api", "--paginate", path, "--jq", jq] }, null, call);
2106
+ return out === null ? null : lines(out);
2107
+ },
2108
+ async getRaw(path) {
2109
+ return ghCall(
2110
+ { argv: ["gh", "api", "-H", "Accept: application/vnd.github.raw", path] },
2111
+ null,
2112
+ call
2113
+ );
2114
+ },
2115
+ async send(method, path, body) {
2116
+ const out = await ghCall(
2117
+ { argv: ["gh", "api", "-X", method, path, "--input", "-"], stdin: JSON.stringify(body) },
2118
+ null,
2119
+ call
2120
+ );
2121
+ if (out === null) return null;
2122
+ return out.trim() === "" ? {} : JSON.parse(out);
2123
+ },
2124
+ async addLabels(repo, issue, labels) {
2125
+ await addLabels(repo, issue, [...labels], call);
2126
+ },
2127
+ async removeLabel(repo, issue, label) {
2128
+ await removeLabel(repo, issue, label, call);
2129
+ }
2130
+ };
2131
+ }
2132
+ function clientOf(target) {
2133
+ return target.client ?? createGhClient({ cwd: target.cwd });
2134
+ }
2135
+
2094
2136
  // src/github/check-run.ts
2095
2137
  function checkRunBody(evaluation, now) {
2096
2138
  const output = { title: evaluation.title, summary: evaluation.summary };
@@ -2102,89 +2144,75 @@ function checkRunBody(evaluation, now) {
2102
2144
  output
2103
2145
  };
2104
2146
  }
2105
- async function openRun(target, headSha) {
2106
- const out = await ghCall(
2107
- {
2108
- argv: [
2109
- "gh",
2110
- "api",
2111
- `repos/${target.repo}/commits/${headSha}/check-runs?check_name=${PR_POLICY_CHECK_NAME}&filter=latest`,
2112
- "--jq",
2113
- ".check_runs"
2114
- ]
2115
- },
2116
- null,
2117
- { cwd: target.cwd }
2147
+ async function openRun(target, headSha, name) {
2148
+ const out = await clientOf(target).getJson(
2149
+ `repos/${target.repo}/commits/${headSha}/check-runs?check_name=${encodeURIComponent(name)}&filter=latest`
2118
2150
  );
2119
- if (out === null) throw new Error(`could not list ${PR_POLICY_CHECK_NAME} check-runs`);
2120
- const runs = JSON.parse(out);
2151
+ if (out === null) throw new Error(`could not list ${name} check-runs`);
2152
+ const runs = out.check_runs;
2121
2153
  return runs.find((run) => run.status !== "completed")?.id ?? null;
2122
2154
  }
2123
- async function postCheckRun(target, headSha, evaluation) {
2155
+ async function postCheckRun(target, headSha, evaluation, options = {}) {
2156
+ const name = options.name ?? PR_POLICY_CHECK_NAME;
2124
2157
  const body = checkRunBody(evaluation, /* @__PURE__ */ new Date());
2125
- const existing = await openRun(target, headSha);
2126
- const argv = existing === null ? ["gh", "api", "-X", "POST", `repos/${target.repo}/check-runs`, "--input", "-"] : ["gh", "api", "-X", "PATCH", `repos/${target.repo}/check-runs/${existing}`, "--input", "-"];
2127
- const payload = existing === null ? { name: PR_POLICY_CHECK_NAME, head_sha: headSha, ...body } : body;
2128
- const out = await ghCall({ argv, stdin: JSON.stringify(payload) }, null, { cwd: target.cwd });
2129
- if (out === null) throw new Error(`could not post the ${PR_POLICY_CHECK_NAME} check-run`);
2158
+ const existing = await openRun(target, headSha, name);
2159
+ const client = clientOf(target);
2160
+ const out = existing === null ? await client.send("POST", `repos/${target.repo}/check-runs`, {
2161
+ name,
2162
+ head_sha: headSha,
2163
+ ...body
2164
+ }) : await client.send("PATCH", `repos/${target.repo}/check-runs/${existing}`, body);
2165
+ if (out === null) throw new Error(`could not post the ${name} check-run`);
2130
2166
  }
2131
2167
  var STATUS_DESCRIPTION_MAX = 140;
2132
- function statusBody(evaluation, runUrl) {
2168
+ function statusBody(evaluation, runUrl, name = PR_POLICY_CHECK_NAME) {
2133
2169
  return {
2134
2170
  state: evaluation.outcome,
2135
- context: PR_POLICY_CHECK_NAME,
2171
+ context: name,
2136
2172
  description: evaluation.title.slice(0, STATUS_DESCRIPTION_MAX),
2137
2173
  ...runUrl ? { target_url: runUrl } : {}
2138
2174
  };
2139
2175
  }
2140
- async function postCommitStatus(target, headSha, evaluation) {
2176
+ async function postCommitStatus(target, headSha, evaluation, name) {
2141
2177
  const { GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_RUN_ID } = process.env;
2142
2178
  const runUrl = GITHUB_SERVER_URL && GITHUB_REPOSITORY && GITHUB_RUN_ID ? `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}` : void 0;
2143
- const out = await ghCall(
2144
- {
2145
- argv: ["gh", "api", "-X", "POST", `repos/${target.repo}/statuses/${headSha}`, "--input", "-"],
2146
- stdin: JSON.stringify(statusBody(evaluation, runUrl))
2147
- },
2148
- null,
2149
- { cwd: target.cwd }
2179
+ const out = await clientOf(target).send(
2180
+ "POST",
2181
+ `repos/${target.repo}/statuses/${headSha}`,
2182
+ statusBody(evaluation, runUrl, name)
2150
2183
  );
2151
2184
  if (out === null) {
2152
2185
  console.warn(
2153
- `::warning::could not set the ${PR_POLICY_CHECK_NAME} commit status on ${headSha} \u2014 does the caller workflow grant \`statuses: write\`? (rmartz/pr-policy#24)`
2186
+ `::warning::could not set the ${name} commit status on ${headSha} \u2014 does the caller workflow grant \`statuses: write\`? (rmartz/pr-policy#24)`
2154
2187
  );
2155
2188
  }
2156
2189
  }
2157
- async function postVerdict(target, headSha, evaluation) {
2158
- await postCheckRun(target, headSha, evaluation);
2159
- await postCommitStatus(target, headSha, evaluation);
2190
+ async function postVerdict(target, headSha, evaluation, options = {}) {
2191
+ const name = options.name ?? PR_POLICY_CHECK_NAME;
2192
+ await postCheckRun(target, headSha, evaluation, { name });
2193
+ await postCommitStatus(target, headSha, evaluation, name);
2160
2194
  }
2161
2195
 
2162
2196
  // src/github/head-push.ts
2163
- async function lines(target, endpoint, jq) {
2164
- const out = await ghCall({ argv: ["gh", "api", "--paginate", endpoint, "--jq", jq] }, null, {
2165
- cwd: target.cwd
2166
- });
2197
+ async function list(target, endpoint, key) {
2198
+ const out = await clientOf(target).list(endpoint, key);
2167
2199
  if (out === null) throw new Error(`could not read ${endpoint}`);
2168
- return out.split("\n").filter((line) => line.trim() !== "");
2200
+ return out;
2169
2201
  }
2170
2202
  function times(stamps) {
2171
2203
  return stamps.map((stamp) => Date.parse(stamp)).filter((ms) => !Number.isNaN(ms));
2172
2204
  }
2173
2205
  async function gatherHeadPushedAt(target, headSha) {
2206
+ const events = await list(target, `repos/${target.repo}/issues/${target.pr}/events`);
2174
2207
  const forcePushes = times(
2175
- await lines(
2176
- target,
2177
- `repos/${target.repo}/issues/${target.pr}/events`,
2178
- '.[] | select(.event == "head_ref_force_pushed") | .created_at'
2179
- )
2208
+ events.filter((event) => event.event === "head_ref_force_pushed").map((e) => e.created_at)
2180
2209
  );
2181
- const suites = times(
2182
- await lines(
2183
- target,
2184
- `repos/${target.repo}/commits/${headSha}/check-suites`,
2185
- ".check_suites[].created_at"
2186
- )
2210
+ const checkSuites = await list(
2211
+ target,
2212
+ `repos/${target.repo}/commits/${headSha}/check-suites`,
2213
+ "check_suites"
2187
2214
  );
2215
+ const suites = times(checkSuites.map((suite) => suite.created_at));
2188
2216
  const candidates = [...forcePushes];
2189
2217
  if (suites.length > 0) candidates.push(Math.min(...suites));
2190
2218
  if (candidates.length === 0) return void 0;
@@ -2193,39 +2221,21 @@ async function gatherHeadPushedAt(target, headSha) {
2193
2221
 
2194
2222
  // src/github/sign-offs.ts
2195
2223
  async function listLabelEvents(target) {
2196
- const out = await ghCall(
2197
- {
2198
- argv: [
2199
- "gh",
2200
- "api",
2201
- "--paginate",
2202
- `repos/${target.repo}/issues/${target.pr}/events`,
2203
- "--jq",
2204
- '.[] | select(.event == "labeled") | {label: .label.name, login: .actor.login, type: .actor.type, at: .created_at}'
2205
- ]
2206
- },
2207
- null,
2208
- { cwd: target.cwd }
2209
- );
2224
+ const out = await clientOf(target).list(`repos/${target.repo}/issues/${target.pr}/events`);
2210
2225
  if (out === null) throw new Error(`could not list label events of ${target.repo}#${target.pr}`);
2211
- return out.split("\n").filter((line) => line.trim() !== "").map((line) => JSON.parse(line));
2226
+ return out.filter((event) => event.event === "labeled").map((event) => ({
2227
+ label: event.label?.name ?? "",
2228
+ login: event.actor?.login ?? null,
2229
+ type: event.actor?.type ?? null,
2230
+ at: event.created_at
2231
+ }));
2212
2232
  }
2213
2233
  async function lookupPermission(target, login) {
2214
- const out = await ghCall(
2215
- {
2216
- argv: [
2217
- "gh",
2218
- "api",
2219
- `repos/${target.repo}/collaborators/${encodeURIComponent(login)}/permission`,
2220
- "--jq",
2221
- "{permission, role_name}"
2222
- ]
2223
- },
2224
- null,
2225
- { cwd: target.cwd }
2234
+ const out = await clientOf(target).getJson(
2235
+ `repos/${target.repo}/collaborators/${encodeURIComponent(login)}/permission`
2226
2236
  );
2227
2237
  if (out === null) return "none";
2228
- const { permission, role_name: roleName } = JSON.parse(out);
2238
+ const { permission, role_name: roleName } = out;
2229
2239
  if (isRepoPermission(roleName)) return roleName;
2230
2240
  return isRepoPermission(permission) ? permission : "none";
2231
2241
  }
@@ -2249,100 +2259,57 @@ async function gatherSignOffs(target, labels) {
2249
2259
  // src/github/sign-off-status.ts
2250
2260
  async function gatherSignOffStatus(target, sha) {
2251
2261
  const endpoint = `repos/${target.repo}/commits/${sha}/statuses`;
2252
- const out = await ghCall(
2253
- {
2254
- argv: [
2255
- "gh",
2256
- "api",
2257
- "--paginate",
2258
- endpoint,
2259
- "--jq",
2260
- ".[] | {context, state, description, login: .creator.login, type: .creator.type}"
2261
- ]
2262
- },
2263
- null,
2264
- { cwd: target.cwd }
2265
- );
2262
+ const out = await clientOf(target).list(endpoint);
2266
2263
  if (out === null) throw new Error(`could not read ${endpoint}`);
2267
- const latest = out.split("\n").filter((line) => line.trim() !== "").map((line) => JSON.parse(line)).find((status2) => status2.context === SIGN_OFF_STATUS_CONTEXT);
2264
+ const latest = out.find(
2265
+ (status2) => status2.context === SIGN_OFF_STATUS_CONTEXT
2266
+ );
2268
2267
  if (latest === void 0) return void 0;
2269
2268
  const status = { state: latest.state, description: latest.description ?? "" };
2270
- if (latest.login === null) return status;
2271
- const type = latest.type ?? "unknown actor";
2272
- const permission = type === "User" ? await lookupPermission(target, latest.login) : "none";
2273
- return { ...status, creator: { login: latest.login, type, permission } };
2269
+ if (latest.creator === null) return status;
2270
+ const { login, type } = latest.creator;
2271
+ const permission = type === "User" ? await lookupPermission(target, login) : "none";
2272
+ return { ...status, creator: { login, type, permission } };
2274
2273
  }
2275
2274
 
2276
2275
  // src/github/pull-request.ts
2277
- async function ghJson(target, argv) {
2278
- const out = await ghCall({ argv }, null, { cwd: target.cwd });
2279
- if (out === null) throw new Error(`gh call failed: ${argv.join(" ")}`);
2280
- return JSON.parse(out);
2276
+ async function getJson(target, path) {
2277
+ const out = await clientOf(target).getJson(path);
2278
+ if (out === null) throw new Error(`GitHub call failed: GET ${path}`);
2279
+ return out;
2281
2280
  }
2282
2281
  async function blob(target, path, ref) {
2283
- const out = await ghCall(
2284
- {
2285
- argv: [
2286
- "gh",
2287
- "api",
2288
- "-H",
2289
- "Accept: application/vnd.github.raw",
2290
- `repos/${target.repo}/contents/${path}?ref=${encodeURIComponent(ref)}`
2291
- ]
2292
- },
2293
- null,
2294
- { cwd: target.cwd }
2282
+ const out = await clientOf(target).getRaw(
2283
+ `repos/${target.repo}/contents/${path}?ref=${encodeURIComponent(ref)}`
2295
2284
  );
2296
2285
  if (out === null) throw new Error(`could not read ${path} at ${ref}`);
2297
2286
  return out;
2298
2287
  }
2299
2288
  async function listFiles(target) {
2300
- const out = await ghCall(
2301
- {
2302
- argv: [
2303
- "gh",
2304
- "api",
2305
- "--paginate",
2306
- `repos/${target.repo}/pulls/${target.pr}/files`,
2307
- "--jq",
2308
- ".[] | {filename, status, previous_filename}"
2309
- ]
2310
- },
2311
- null,
2312
- { cwd: target.cwd }
2313
- );
2289
+ const out = await clientOf(target).list(`repos/${target.repo}/pulls/${target.pr}/files`);
2314
2290
  if (out === null) throw new Error(`could not list files of ${target.repo}#${target.pr}`);
2315
- return out.split("\n").filter((line) => line.trim() !== "").map((line) => JSON.parse(line));
2291
+ return out;
2316
2292
  }
2317
2293
  async function gatherBase(target, view) {
2318
2294
  const branch = view.base.ref;
2319
2295
  const defaultBranch = view.base.repo.default_branch;
2320
2296
  if (branch === defaultBranch) return { branch, defaultBranch, headOf: [] };
2321
2297
  const head = encodeURIComponent(`${target.repo.split("/")[0] ?? ""}:${branch}`);
2322
- const out = await ghCall(
2323
- {
2324
- argv: [
2325
- "gh",
2326
- "api",
2327
- "--paginate",
2328
- `repos/${target.repo}/pulls?state=open&head=${head}&per_page=100`,
2329
- "--jq",
2330
- ".[] | {number, labels: [.labels[].name]}"
2331
- ]
2332
- },
2333
- null,
2334
- { cwd: target.cwd }
2298
+ const out = await clientOf(target).list(
2299
+ `repos/${target.repo}/pulls?state=open&head=${head}&per_page=100`
2335
2300
  );
2336
2301
  if (out === null) throw new Error(`could not list the open PRs heading ${branch}`);
2337
- const headOf = out.split("\n").filter((line) => line.trim() !== "").map((line) => JSON.parse(line));
2302
+ const headOf = out.map(
2303
+ (pull) => ({
2304
+ number: pull.number,
2305
+ labels: pull.labels.map((label) => label.name)
2306
+ })
2307
+ );
2338
2308
  return { branch, defaultBranch, headOf };
2339
2309
  }
2340
- async function gatherFacts(target) {
2341
- const view = await ghJson(target, [
2342
- "gh",
2343
- "api",
2344
- `repos/${target.repo}/pulls/${target.pr}`
2345
- ]);
2310
+ async function gatherFacts(pullRequest) {
2311
+ const target = { ...pullRequest, client: clientOf(pullRequest) };
2312
+ const view = await getJson(target, `repos/${target.repo}/pulls/${target.pr}`);
2346
2313
  const headSha = view.head.sha;
2347
2314
  const files = await listFiles(target);
2348
2315
  const touches = (predicate) => files.filter((file) => predicate(file.filename) || predicate(file.previous_filename ?? ""));
@@ -2351,11 +2318,10 @@ async function gatherFacts(target) {
2351
2318
  let workflowChanges = [];
2352
2319
  let manifestChanges = [];
2353
2320
  if (workflowFiles.length > 0 || manifestFiles.length > 0) {
2354
- const comparison = await ghJson(target, [
2355
- "gh",
2356
- "api",
2321
+ const comparison = await getJson(
2322
+ target,
2357
2323
  `repos/${target.repo}/compare/${view.base.ref}...${headSha}`
2358
- ]);
2324
+ );
2359
2325
  const mergeBase = comparison.merge_base_commit.sha;
2360
2326
  const read = async (file) => ({
2361
2327
  path: file.filename,
@@ -2391,29 +2357,17 @@ async function gatherFacts(target) {
2391
2357
  }
2392
2358
  async function openPullRequestsAtHead(target, sha) {
2393
2359
  const endpoint = `repos/${target.repo}/commits/${sha}/pulls`;
2394
- const out = await ghCall(
2395
- {
2396
- argv: [
2397
- "gh",
2398
- "api",
2399
- "--paginate",
2400
- endpoint,
2401
- "--jq",
2402
- '.[] | select(.state == "open") | {number, head: .head.sha}'
2403
- ]
2404
- },
2405
- null,
2406
- { cwd: target.cwd }
2407
- );
2360
+ const out = await clientOf(target).list(endpoint);
2408
2361
  if (out === null) throw new Error(`could not read ${endpoint}`);
2409
- return out.split("\n").filter((line) => line.trim() !== "").map((line) => JSON.parse(line)).filter((pull) => pull.head === sha).map((pull) => pull.number);
2362
+ return out.filter((pull) => pull.state === "open" && pull.head.sha === sha).map((pull) => pull.number);
2410
2363
  }
2411
2364
  async function applyLabelEdits(target, evaluation) {
2365
+ const client = clientOf(target);
2412
2366
  if (evaluation.labelsToAdd.length > 0) {
2413
- await addLabels(target.repo, target.pr, evaluation.labelsToAdd, { cwd: target.cwd });
2367
+ await client.addLabels(target.repo, target.pr, evaluation.labelsToAdd);
2414
2368
  }
2415
2369
  for (const label of evaluation.labelsToRemove) {
2416
- await removeLabel(target.repo, target.pr, label, { cwd: target.cwd });
2370
+ await client.removeLabel(target.repo, target.pr, label);
2417
2371
  }
2418
2372
  }
2419
2373
 
@@ -2461,6 +2415,7 @@ export {
2461
2415
  COMMIT_TYPES,
2462
2416
  FUNCTIONAL_TYPES,
2463
2417
  parseTitle,
2418
+ isFunctionalType,
2464
2419
  TITLE_CHECK,
2465
2420
  decideTitle,
2466
2421
  titleCheck,
@@ -2474,6 +2429,8 @@ export {
2474
2429
  evaluatePolicy,
2475
2430
  parseFacts,
2476
2431
  resolveRepoTarget,
2432
+ createGhClient,
2433
+ clientOf,
2477
2434
  checkRunBody,
2478
2435
  postCheckRun,
2479
2436
  statusBody,
package/dist/index.d.ts CHANGED
@@ -559,17 +559,48 @@ declare function evaluatePolicy(pr: PullRequestFacts, checks?: readonly PolicyCh
559
559
  */
560
560
  declare function parseFacts(raw: string): PullRequestFacts;
561
561
 
562
- interface PullRequestTarget {
562
+ interface GitHubClient {
563
+ /** GET one JSON resource (`repos/o/r/...`), or `null` on failure. */
564
+ getJson(path: string): Promise<unknown>;
565
+ /**
566
+ * GET every page of a list resource, items concatenated, or `null` on
567
+ * failure. Most list endpoints return an array; for one that wraps its items
568
+ * in an object (`{ check_suites: [...] }`), pass that key.
569
+ */
570
+ list(path: string, key?: string): Promise<unknown[] | null>;
571
+ /** GET a file's raw text from the contents API, or `null` on failure. */
572
+ getRaw(path: string): Promise<string | null>;
573
+ /** POST or PATCH a JSON body, returning the response JSON, or `null` on failure. */
574
+ send(method: 'POST' | 'PATCH', path: string, body: unknown): Promise<unknown>;
575
+ /** Add labels to an issue or PR. Soft-fails, like the vendored helper. */
576
+ addLabels(repo: string, issue: number, labels: readonly string[]): Promise<void>;
577
+ /** Remove one label from an issue or PR. Soft-fails, like the vendored helper. */
578
+ removeLabel(repo: string, issue: number, label: string): Promise<void>;
579
+ }
580
+ /** The `gh` client: the default for the CLI and the action. */
581
+ declare function createGhClient(options?: {
582
+ cwd?: string;
583
+ }): GitHubClient;
584
+ /** Where a GitHub call goes: an explicit client, or `gh` in a working directory. */
585
+ interface ClientTarget {
586
+ /** The working directory for the default `gh` client. */
587
+ cwd?: string;
588
+ /** How to reach GitHub; defaults to the `gh` client in `cwd`. */
589
+ client?: GitHubClient;
590
+ }
591
+ /** The target's client, or the default `gh` client in its working directory. */
592
+ declare function clientOf(target: ClientTarget): GitHubClient;
593
+
594
+ interface PullRequestTarget extends ClientTarget {
563
595
  repo: string;
564
596
  pr: number;
565
- cwd?: string;
566
597
  }
567
598
  /**
568
599
  * Gather everything the checks judge. Workflow files and dependency manifests
569
600
  * are read at the **merge base**, not the base tip, so a change merged into the
570
601
  * base after this PR branched is not attributed to it.
571
602
  */
572
- declare function gatherFacts(target: PullRequestTarget): Promise<{
603
+ declare function gatherFacts(pullRequest: PullRequestTarget): Promise<{
573
604
  facts: PullRequestFacts;
574
605
  headSha: string;
575
606
  }>;
@@ -579,20 +610,90 @@ declare function gatherFacts(target: PullRequestTarget): Promise<{
579
610
  * status. A PR whose head has since moved isn't returned: its newer head gets
580
611
  * its own status. A failed lookup throws.
581
612
  */
582
- declare function openPullRequestsAtHead(target: {
613
+ declare function openPullRequestsAtHead(target: ClientTarget & {
583
614
  repo: string;
584
- cwd?: string;
585
615
  }, sha: string): Promise<number[]>;
586
616
  /** Apply the label edits the checks planned (labels this package owns). */
587
617
  declare function applyLabelEdits(target: PullRequestTarget, evaluation: PolicyEvaluation): Promise<void>;
588
618
 
619
+ /**
620
+ * Where to post the verdict. `name` is the check-run name and status context,
621
+ * `pr-policy` unless a caller shadows under a distinct one (`pr-policy (app)`)
622
+ * while another poster still owns the real name. Two creators posting one
623
+ * context would overwrite each other.
624
+ */
625
+ interface VerdictOptions {
626
+ name?: string;
627
+ }
589
628
  /** The request body for this evaluation's check-run state. */
590
629
  declare function checkRunBody(evaluation: PolicyEvaluation, now: Date): Record<string, unknown>;
591
630
  /** Post (or complete) the one `pr-policy` check-run on the head commit. */
592
- declare function postCheckRun(target: PullRequestTarget, headSha: string, evaluation: PolicyEvaluation): Promise<void>;
631
+ declare function postCheckRun(target: PullRequestTarget, headSha: string, evaluation: PolicyEvaluation, options?: VerdictOptions): Promise<void>;
593
632
  /** The request body for the `pr-policy` commit status mirroring this evaluation. */
594
- declare function statusBody(evaluation: PolicyEvaluation, runUrl: string | undefined): Record<string, unknown>;
633
+ declare function statusBody(evaluation: PolicyEvaluation, runUrl: string | undefined, name?: string): Record<string, unknown>;
595
634
  /** Post the verdict: the `pr-policy` check-run, then the matching commit status. */
596
- declare function postVerdict(target: PullRequestTarget, headSha: string, evaluation: PolicyEvaluation): Promise<void>;
635
+ declare function postVerdict(target: PullRequestTarget, headSha: string, evaluation: PolicyEvaluation, options?: VerdictOptions): Promise<void>;
636
+
637
+ /**
638
+ * One informational commit status per policy check (`pr-policy / title`), so a
639
+ * PR's status list shows which check failed, which waits on a human and which
640
+ * passed, without opening the check-run. Moved here from rmartz/pr-policy-action
641
+ * so every wrapper (the Action, a hosted App) posts the same statuses.
642
+ *
643
+ * These are informational: the `pr-policy` verdict status is the gate, and it is
644
+ * posted by `postVerdict` whatever happens here.
645
+ */
646
+
647
+ /** One check's status. */
648
+ interface CheckStatus {
649
+ check: string;
650
+ state: 'success' | 'failure' | 'pending';
651
+ description: string;
652
+ }
653
+ /**
654
+ * Each check's status: red on any `block`, pending on any `hold`, else green.
655
+ * The description leads with the finding that decided the state. A check that
656
+ * didn't run (left out by `selectChecks`) gets no status.
657
+ */
658
+ declare function checkStatuses(checks: readonly Pick<PolicyCheck, 'name'>[], findings: readonly Finding[]): CheckStatus[];
659
+ interface CheckStatusOptions {
660
+ /** The status names are `<context> / <check>`; default `pr-policy`. */
661
+ context?: string;
662
+ /** Where each status links, e.g. the Actions run. */
663
+ targetUrl?: string;
664
+ }
665
+ /**
666
+ * Post each check's status on `sha`. Returns false, having stopped at the first
667
+ * failure, when one can't be posted (most often a token without
668
+ * `statuses: write`); the caller decides whether to warn.
669
+ */
670
+ declare function postCheckStatuses(target: ClientTarget & {
671
+ repo: string;
672
+ }, sha: string, statuses: readonly CheckStatus[], options?: CheckStatusOptions): Promise<boolean>;
673
+
674
+ /**
675
+ * The `ci` title for this PR, or `undefined` to leave the title alone. Only a
676
+ * Dependabot PR with a sensitive bump is retitled, and never one already typed
677
+ * `ci` or a release type: demoting `fix`/`feat`/`perf`/`revert` would cancel a
678
+ * release. Scope, `!` and subject are kept.
679
+ */
680
+ declare function ciRetitle(facts: Pick<PullRequestFacts, 'author' | 'title' | 'manifestChanges'>): string | undefined;
681
+
682
+ /**
683
+ * A token-authenticated `GitHubClient` over `fetch`, for a hosted caller with no
684
+ * `gh` binary (a GitHub App's webhook server). It makes the same REST calls the
685
+ * `gh` client does; it has no retry or GraphQL fallback, so a failed call
686
+ * returns `null` (or soft-fails for labels) and the caller's next event retries.
687
+ */
688
+
689
+ interface FetchClientOptions {
690
+ /** An installation (or other) token, sent as a bearer token. */
691
+ token: string;
692
+ /** The REST API base, default `https://api.github.com`. */
693
+ apiUrl?: string;
694
+ /** Injectable for tests; defaults to the global `fetch`. */
695
+ fetch?: typeof fetch;
696
+ }
697
+ declare function createFetchClient(options: FetchClientOptions): GitHubClient;
597
698
 
598
- export { AMBIGUOUS_INDICATORS, type AmbiguousIndicator, BLOCKED_LABEL, BLOCKING_LABELS, BREAKING_CHANGE_LABEL, CHECKS, CI_APPROVAL_NEEDED_LABEL, CI_CHANGE_APPROVED_LABEL, CI_CHANGE_CHECK, CI_CHANGE_VERDICTS, CI_SENSITIVE_PACKAGES, COMMIT_TYPES, type CheckResult, type CheckRunReport, type CiChangeVerdict, type Claim, type Classification, type CommitStatus, type CommitType, DEPENDABOT_CHECK, DEPENDABOT_LOGIN, DNM_LABEL, DO_NOT_MERGE_LABEL, ESCALATION_NEEDED_LABEL, FUNCTIONAL_TYPES, type FileChange, type Finding, GITHUB_ACTIONS_BOT, HOTFIX_LABEL, type Indicator, type IndicatorClass, type IndicatorKind, LOOSENING_INDICATORS, type LooseningIndicator, MERGE_BLOCK_CHECK, POLICY_OUTCOMES, PR_POLICY_CHECK_NAME, type ParsedTitle, type PolicyCheck, type PolicyEvaluation, type PolicyOptions, type PolicyOutcome, type PullRequestAuthor, type PullRequestFacts, type PullRequestTarget, RELEASE_PLEASE_PENDING_LABEL, SIGN_OFF_REQUIREMENTS, SIGN_OFF_STATUS_CONTEXT, SIGN_OFF_STATUS_VERSIONS, type SignOffClassification, type SignOffRequirement, type SignOffStatusReading, TITLE_CHECK, UAT_LABELS, UAT_LABEL_CHECK, WAIVER_STATES, type WaiverState, type WorkflowFileChange, applyLabelEdits, buildReport, checkRunBody, ciChangeCheck, classifyWorkflowChanges, classifyWorkflowFile, decideCiChange, decideDependabot, decideMergeBlock, decideTitle, decideUatLabel, dependabotCheck, evaluatePolicy, gatherFacts, isManifestPath, isWorkflowPath, mergeBlockCheck, openPullRequestsAtHead, parseClaims, parseFacts, parseSignOffDescription, parseSignOffStatusCreators, parseTitle, postCheckRun, postVerdict, readSignOffStatus, selectChecks, sensitiveBumps, statusBody, titleCheck, uatLabelCheck };
699
+ export { AMBIGUOUS_INDICATORS, type AmbiguousIndicator, BLOCKED_LABEL, BLOCKING_LABELS, BREAKING_CHANGE_LABEL, CHECKS, CI_APPROVAL_NEEDED_LABEL, CI_CHANGE_APPROVED_LABEL, CI_CHANGE_CHECK, CI_CHANGE_VERDICTS, CI_SENSITIVE_PACKAGES, COMMIT_TYPES, type CheckResult, type CheckRunReport, type CheckStatus, type CheckStatusOptions, type CiChangeVerdict, type Claim, type Classification, type ClientTarget, type CommitStatus, type CommitType, DEPENDABOT_CHECK, DEPENDABOT_LOGIN, DNM_LABEL, DO_NOT_MERGE_LABEL, ESCALATION_NEEDED_LABEL, FUNCTIONAL_TYPES, type FetchClientOptions, type FileChange, type Finding, GITHUB_ACTIONS_BOT, type GitHubClient, HOTFIX_LABEL, type Indicator, type IndicatorClass, type IndicatorKind, LOOSENING_INDICATORS, type LooseningIndicator, MERGE_BLOCK_CHECK, POLICY_OUTCOMES, PR_POLICY_CHECK_NAME, type ParsedTitle, type PolicyCheck, type PolicyEvaluation, type PolicyOptions, type PolicyOutcome, type PullRequestAuthor, type PullRequestFacts, type PullRequestTarget, RELEASE_PLEASE_PENDING_LABEL, SIGN_OFF_REQUIREMENTS, SIGN_OFF_STATUS_CONTEXT, SIGN_OFF_STATUS_VERSIONS, type SignOffClassification, type SignOffRequirement, type SignOffStatusReading, TITLE_CHECK, UAT_LABELS, UAT_LABEL_CHECK, type VerdictOptions, WAIVER_STATES, type WaiverState, type WorkflowFileChange, applyLabelEdits, buildReport, checkRunBody, checkStatuses, ciChangeCheck, ciRetitle, classifyWorkflowChanges, classifyWorkflowFile, clientOf, createFetchClient, createGhClient, decideCiChange, decideDependabot, decideMergeBlock, decideTitle, decideUatLabel, dependabotCheck, evaluatePolicy, gatherFacts, isManifestPath, isWorkflowPath, mergeBlockCheck, openPullRequestsAtHead, parseClaims, parseFacts, parseSignOffDescription, parseSignOffStatusCreators, parseTitle, postCheckRun, postCheckStatuses, postVerdict, readSignOffStatus, selectChecks, sensitiveBumps, statusBody, titleCheck, uatLabelCheck };
package/dist/index.js CHANGED
@@ -36,6 +36,8 @@ import {
36
36
  ciChangeCheck,
37
37
  classifyWorkflowChanges,
38
38
  classifyWorkflowFile,
39
+ clientOf,
40
+ createGhClient,
39
41
  decideCiChange,
40
42
  decideDependabot,
41
43
  decideMergeBlock,
@@ -44,6 +46,7 @@ import {
44
46
  dependabotCheck,
45
47
  evaluatePolicy,
46
48
  gatherFacts,
49
+ isFunctionalType,
47
50
  isManifestPath,
48
51
  isWorkflowPath,
49
52
  mergeBlockCheck,
@@ -61,7 +64,129 @@ import {
61
64
  statusBody,
62
65
  titleCheck,
63
66
  uatLabelCheck
64
- } from "./chunk-UI7QG6XT.js";
67
+ } from "./chunk-JJ5AKEQ3.js";
68
+
69
+ // src/github/check-statuses.ts
70
+ var MAX_DESCRIPTION = 140;
71
+ var STATES = { block: "failure", hold: "pending" };
72
+ function checkStatuses(checks, findings) {
73
+ return checks.map(({ name }) => {
74
+ const own = findings.filter((finding) => finding.check === name);
75
+ const deciding = own.find((finding) => finding.effect === "block") ?? own.find((finding) => finding.effect === "hold");
76
+ const state = deciding?.effect === "block" || deciding?.effect === "hold" ? STATES[deciding.effect] : "success";
77
+ const lead = deciding ?? own.find((finding) => finding.headline);
78
+ const gating = own.filter((finding) => finding.effect !== "info").length;
79
+ let description = lead?.message ?? "Passed";
80
+ if (gating > 1) description += ` (+${gating - 1} more)`;
81
+ if (description.length > MAX_DESCRIPTION) {
82
+ description = `${description.slice(0, MAX_DESCRIPTION - 1)}\u2026`;
83
+ }
84
+ return { check: name, state, description };
85
+ });
86
+ }
87
+ async function postCheckStatuses(target, sha, statuses, options = {}) {
88
+ const client = clientOf(target);
89
+ const context = options.context ?? "pr-policy";
90
+ for (const { check, state, description } of statuses) {
91
+ const out = await client.send("POST", `repos/${target.repo}/statuses/${sha}`, {
92
+ state,
93
+ context: `${context} / ${check}`,
94
+ description,
95
+ ...options.targetUrl ? { target_url: options.targetUrl } : {}
96
+ });
97
+ if (out === null) return false;
98
+ }
99
+ return true;
100
+ }
101
+
102
+ // src/checks/title/ci-retitle.ts
103
+ function ciRetitle(facts) {
104
+ if (facts.author?.login !== DEPENDABOT_LOGIN) return void 0;
105
+ const title = parseTitle(facts.title);
106
+ if (title === null || title.type === "ci" || isFunctionalType(title.type)) {
107
+ return void 0;
108
+ }
109
+ if (sensitiveBumps(facts.manifestChanges).length === 0) return void 0;
110
+ return `ci${facts.title.slice(title.type.length)}`;
111
+ }
112
+
113
+ // src/github/fetch-client.ts
114
+ var JSON_ACCEPT = "application/vnd.github+json";
115
+ var RAW_ACCEPT = "application/vnd.github.raw";
116
+ function nextPageUrl(link) {
117
+ if (link === null) return void 0;
118
+ for (const part of link.split(",")) {
119
+ const match = part.match(/<([^>]+)>\s*;\s*rel="next"/);
120
+ if (match?.[1] !== void 0) return match[1];
121
+ }
122
+ return void 0;
123
+ }
124
+ function createFetchClient(options) {
125
+ const apiUrl = (options.apiUrl ?? "https://api.github.com").replace(/\/$/, "");
126
+ const doFetch = options.fetch ?? fetch;
127
+ const request = async (url, init = {}) => {
128
+ try {
129
+ const headers = {
130
+ accept: init.accept ?? JSON_ACCEPT,
131
+ authorization: `Bearer ${options.token}`,
132
+ "x-github-api-version": "2022-11-28"
133
+ };
134
+ if (init.body !== void 0) headers["content-type"] = "application/json";
135
+ const response = await doFetch(url, {
136
+ method: init.method ?? "GET",
137
+ headers,
138
+ body: init.body === void 0 ? void 0 : JSON.stringify(init.body)
139
+ });
140
+ return response.ok ? response : null;
141
+ } catch {
142
+ return null;
143
+ }
144
+ };
145
+ const urlOf = (path) => `${apiUrl}/${path}`;
146
+ const json = async (response) => {
147
+ if (response === null) return null;
148
+ const text = await response.text();
149
+ return text.trim() === "" ? {} : JSON.parse(text);
150
+ };
151
+ return {
152
+ async getJson(path) {
153
+ return json(await request(urlOf(path)));
154
+ },
155
+ async list(path, key) {
156
+ const items = [];
157
+ let url = urlOf(path);
158
+ while (url !== void 0) {
159
+ const response = await request(url);
160
+ if (response === null) return null;
161
+ const page = await json(response);
162
+ const pageItems = key === void 0 ? page : page?.[key];
163
+ if (!Array.isArray(pageItems)) return null;
164
+ items.push(...pageItems);
165
+ url = nextPageUrl(response.headers.get("link"));
166
+ }
167
+ return items;
168
+ },
169
+ async getRaw(path) {
170
+ const response = await request(urlOf(path), { accept: RAW_ACCEPT });
171
+ return response === null ? null : response.text();
172
+ },
173
+ async send(method, path, body) {
174
+ return json(await request(urlOf(path), { method, body }));
175
+ },
176
+ async addLabels(repo, issue, labels) {
177
+ if (labels.length === 0) return;
178
+ await request(urlOf(`repos/${repo}/issues/${issue}/labels`), {
179
+ method: "POST",
180
+ body: { labels }
181
+ });
182
+ },
183
+ async removeLabel(repo, issue, label) {
184
+ await request(urlOf(`repos/${repo}/issues/${issue}/labels/${encodeURIComponent(label)}`), {
185
+ method: "DELETE"
186
+ });
187
+ }
188
+ };
189
+ }
65
190
  export {
66
191
  AMBIGUOUS_INDICATORS,
67
192
  BLOCKED_LABEL,
@@ -97,9 +222,14 @@ export {
97
222
  applyLabelEdits,
98
223
  buildReport,
99
224
  checkRunBody,
225
+ checkStatuses,
100
226
  ciChangeCheck,
227
+ ciRetitle,
101
228
  classifyWorkflowChanges,
102
229
  classifyWorkflowFile,
230
+ clientOf,
231
+ createFetchClient,
232
+ createGhClient,
103
233
  decideCiChange,
104
234
  decideDependabot,
105
235
  decideMergeBlock,
@@ -118,6 +248,7 @@ export {
118
248
  parseSignOffStatusCreators,
119
249
  parseTitle,
120
250
  postCheckRun,
251
+ postCheckStatuses,
121
252
  postVerdict,
122
253
  readSignOffStatus,
123
254
  selectChecks,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rmartz/pr-policy",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "description": "Read-only PR content classifiers — CI-change classification, title-type rules, and more — reported as one blocking pr-policy check-run. Distributed as a pinned Action kept current by Dependabot.",
5
5
  "keywords": [
6
6
  "pr-policy",