@rmartz/pr-policy 1.6.0 → 1.7.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 CHANGED
@@ -12,17 +12,17 @@ new required-status name.
12
12
 
13
13
  ## Checks
14
14
 
15
- | Check | Blocks when |
16
- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17
- | **Blocking labels** ([docs](docs/checks/merge-block.md)) | The PR carries `do not merge`, `dnm`, `blocked`, or `escalation needed` (shows as pending). |
18
- | **CI-change classification** ([docs](docs/checks/ci-change.md)) | pr-lifecycle's `pr-lifecycle/sign-off` status asks for a CI sign-off (or, before a repo cuts over, a `.github/workflows/**` change loosens CI), and no human has applied `CI change approved` (shows as pending). |
19
- | **Base branch** ([docs](docs/checks/base-branch.md)) | The PR targets a branch other than the default and it isn't a non-epic PR on an open epic's branch. A stacked PR waits for its base PR (shows as pending); a base no open PR heads blocks. |
20
- | **Title-type rules** ([docs](docs/checks/title.md)) | The squash title isn't a valid Conventional Commit, puts `!` on a non-functional type, disagrees with the `breaking change` label, types a linter/formatter bump as a non-release, non-`ci` type, or changes paths its type rules out (`docs`, `test`, `refactor`, `ci`). |
21
- | **UAT sign-off** ([docs](docs/checks/uat.md)) | pr-lifecycle's sign-off status says the head needs UAT (or, before a repo cuts over, the PR isn't docs, tests, CI, dependency-only, or repo metadata), or the status can't be trusted, and no trusted user has applied `no UAT needed`, or `UAT passed` (or `tested`) since the last push (shows as pending). |
22
- | **UAT label presence** ([docs](docs/checks/uat-label.md)), opt-in | `require-uat-label` is on and the PR carries none of `no UAT needed`, `UAT pending`, `UAT ready`, `UAT passed` (shows as pending). |
23
- | **Dependabot claim verification** ([docs](docs/checks/dependabot.md)) | A Dependabot PR touches a non-dependency path, changes a dependency its description doesn't claim, pins a version other than the claimed one, or edits anything Dependabot never edits (a `package.json` script, a workflow step). |
24
- | Domain labels (backlog) | Never blocks. Additive path-glob → domain-label map. |
25
- | Milestone inheritance (backlog) | Never blocks. Issue → PR milestone. |
15
+ | Check | Blocks when |
16
+ | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17
+ | **Blocking labels** ([docs](docs/checks/merge-block.md)) | The PR carries `do not merge`, `dnm`, `blocked`, or `escalation needed` (shows as pending). |
18
+ | **CI-change classification** ([docs](docs/checks/ci-change.md)) | pr-lifecycle's `pr-lifecycle/sign-off` status asks for a CI sign-off (or, before a repo cuts over, a `.github/workflows/**` change loosens CI), and no human has applied `CI change approved` (shows as pending). |
19
+ | **Base branch** ([docs](docs/checks/base-branch.md)) | The PR targets a branch other than the default and it isn't a non-epic PR on an open epic's branch. A stacked PR waits for its base PR (shows as pending); a base no open PR heads blocks. |
20
+ | **Title-type rules** ([docs](docs/checks/title.md)) | The squash title isn't a valid Conventional Commit, puts `!` on a non-functional type, disagrees with the `breaking change` label, types a linter/formatter bump as a non-release, non-`ci` type, or changes paths its type rules out (`docs`, `test`, `refactor`, `ci`). |
21
+ | **UAT sign-off** ([docs](docs/checks/uat.md)) | pr-lifecycle's sign-off status says the head needs UAT (or, before a repo cuts over, the PR isn't docs, tests, CI, repo tooling, dependency-only, or repo metadata), or the status can't be trusted, and no trusted user has applied `no UAT needed`, or `UAT passed` (or `tested`) since the last push (shows as pending). |
22
+ | **UAT label presence** ([docs](docs/checks/uat-label.md)), opt-in | `require-uat-label` is on and the PR carries none of `no UAT needed`, `UAT pending`, `UAT ready`, `UAT passed` (shows as pending). |
23
+ | **Dependabot claim verification** ([docs](docs/checks/dependabot.md)) | A Dependabot PR touches a non-dependency path, changes a dependency its description doesn't claim, pins a version other than the claimed one, or edits anything Dependabot never edits (a `package.json` script, a workflow step). |
24
+ | Domain labels (backlog) | Never blocks. Additive path-glob → domain-label map. |
25
+ | Milestone inheritance (backlog) | Never blocks. Issue → PR milestone. |
26
26
 
27
27
  The design, and why this is separate from `merge-safety` and `pr-lifecycle`, is
28
28
  in [docs/decisions.md](docs/decisions.md).
@@ -8,7 +8,7 @@ import {
8
8
  postVerdict,
9
9
  resolveRepoTarget,
10
10
  selectChecks
11
- } from "../chunk-UI7QG6XT.js";
11
+ } from "../chunk-SWWJ3U3V.js";
12
12
 
13
13
  // src/bin/pr-policy.ts
14
14
  import { readFile } from "fs/promises";
@@ -1633,7 +1633,14 @@ var baseBranchCheck = {
1633
1633
  };
1634
1634
 
1635
1635
  // src/checks/uat/trivial.ts
1636
- var TRIVIAL_CATEGORIES = ["docs", "tests", "ci", "dependencies", "metadata"];
1636
+ var TRIVIAL_CATEGORIES = [
1637
+ "docs",
1638
+ "tests",
1639
+ "ci",
1640
+ "tooling",
1641
+ "dependencies",
1642
+ "metadata"
1643
+ ];
1637
1644
  function categoryOf(kind) {
1638
1645
  switch (kind) {
1639
1646
  case "docs":
@@ -1641,12 +1648,13 @@ function categoryOf(kind) {
1641
1648
  case "ci":
1642
1649
  case "metadata":
1643
1650
  return kind;
1651
+ case "tooling-config":
1652
+ case "repo-script":
1653
+ return "tooling";
1644
1654
  case "lockfile":
1645
1655
  case "tooling-manifest":
1646
1656
  case "runtime-manifest":
1647
1657
  return "dependencies";
1648
- case "tooling-config":
1649
- case "repo-script":
1650
1658
  case void 0:
1651
1659
  return void 0;
1652
1660
  }
@@ -1796,10 +1804,10 @@ function buildReport(findings) {
1796
1804
  outcome = "pending";
1797
1805
  title = `Waiting on ${plural(holds.length, "human sign-off")}`;
1798
1806
  }
1799
- const lines2 = findings.map(
1807
+ const lines = findings.map(
1800
1808
  (finding) => `- ${ICONS[finding.effect]} **${finding.check}**: ${finding.message}`
1801
1809
  );
1802
- const summary = lines2.length > 0 ? lines2.join("\n") : "No policy findings.";
1810
+ const summary = lines.length > 0 ? lines.join("\n") : "No policy findings.";
1803
1811
  return { outcome, title, summary, findings };
1804
1812
  }
1805
1813
 
@@ -2091,6 +2099,48 @@ async function removeLabel(repo, issue, label, call = {}) {
2091
2099
  return out !== null ? out.trim() : null;
2092
2100
  }
2093
2101
 
2102
+ // src/github/client.ts
2103
+ function createGhClient(options = {}) {
2104
+ const call = { cwd: options.cwd };
2105
+ const lines = (out) => out.split("\n").filter((line) => line.trim() !== "").map((line) => JSON.parse(line));
2106
+ return {
2107
+ async getJson(path) {
2108
+ const out = await ghCall({ argv: ["gh", "api", path] }, null, call);
2109
+ return out === null ? null : JSON.parse(out);
2110
+ },
2111
+ async list(path, key) {
2112
+ const jq = key === void 0 ? ".[]" : `.${key}[]`;
2113
+ const out = await ghCall({ argv: ["gh", "api", "--paginate", path, "--jq", jq] }, null, call);
2114
+ return out === null ? null : lines(out);
2115
+ },
2116
+ async getRaw(path) {
2117
+ return ghCall(
2118
+ { argv: ["gh", "api", "-H", "Accept: application/vnd.github.raw", path] },
2119
+ null,
2120
+ call
2121
+ );
2122
+ },
2123
+ async send(method, path, body) {
2124
+ const out = await ghCall(
2125
+ { argv: ["gh", "api", "-X", method, path, "--input", "-"], stdin: JSON.stringify(body) },
2126
+ null,
2127
+ call
2128
+ );
2129
+ if (out === null) return null;
2130
+ return out.trim() === "" ? {} : JSON.parse(out);
2131
+ },
2132
+ async addLabels(repo, issue, labels) {
2133
+ await addLabels(repo, issue, [...labels], call);
2134
+ },
2135
+ async removeLabel(repo, issue, label) {
2136
+ await removeLabel(repo, issue, label, call);
2137
+ }
2138
+ };
2139
+ }
2140
+ function clientOf(target) {
2141
+ return target.client ?? createGhClient({ cwd: target.cwd });
2142
+ }
2143
+
2094
2144
  // src/github/check-run.ts
2095
2145
  function checkRunBody(evaluation, now) {
2096
2146
  const output = { title: evaluation.title, summary: evaluation.summary };
@@ -2102,89 +2152,75 @@ function checkRunBody(evaluation, now) {
2102
2152
  output
2103
2153
  };
2104
2154
  }
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 }
2155
+ async function openRun(target, headSha, name) {
2156
+ const out = await clientOf(target).getJson(
2157
+ `repos/${target.repo}/commits/${headSha}/check-runs?check_name=${encodeURIComponent(name)}&filter=latest`
2118
2158
  );
2119
- if (out === null) throw new Error(`could not list ${PR_POLICY_CHECK_NAME} check-runs`);
2120
- const runs = JSON.parse(out);
2159
+ if (out === null) throw new Error(`could not list ${name} check-runs`);
2160
+ const runs = out.check_runs;
2121
2161
  return runs.find((run) => run.status !== "completed")?.id ?? null;
2122
2162
  }
2123
- async function postCheckRun(target, headSha, evaluation) {
2163
+ async function postCheckRun(target, headSha, evaluation, options = {}) {
2164
+ const name = options.name ?? PR_POLICY_CHECK_NAME;
2124
2165
  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`);
2166
+ const existing = await openRun(target, headSha, name);
2167
+ const client = clientOf(target);
2168
+ const out = existing === null ? await client.send("POST", `repos/${target.repo}/check-runs`, {
2169
+ name,
2170
+ head_sha: headSha,
2171
+ ...body
2172
+ }) : await client.send("PATCH", `repos/${target.repo}/check-runs/${existing}`, body);
2173
+ if (out === null) throw new Error(`could not post the ${name} check-run`);
2130
2174
  }
2131
2175
  var STATUS_DESCRIPTION_MAX = 140;
2132
- function statusBody(evaluation, runUrl) {
2176
+ function statusBody(evaluation, runUrl, name = PR_POLICY_CHECK_NAME) {
2133
2177
  return {
2134
2178
  state: evaluation.outcome,
2135
- context: PR_POLICY_CHECK_NAME,
2179
+ context: name,
2136
2180
  description: evaluation.title.slice(0, STATUS_DESCRIPTION_MAX),
2137
2181
  ...runUrl ? { target_url: runUrl } : {}
2138
2182
  };
2139
2183
  }
2140
- async function postCommitStatus(target, headSha, evaluation) {
2184
+ async function postCommitStatus(target, headSha, evaluation, name) {
2141
2185
  const { GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_RUN_ID } = process.env;
2142
2186
  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 }
2187
+ const out = await clientOf(target).send(
2188
+ "POST",
2189
+ `repos/${target.repo}/statuses/${headSha}`,
2190
+ statusBody(evaluation, runUrl, name)
2150
2191
  );
2151
2192
  if (out === null) {
2152
2193
  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)`
2194
+ `::warning::could not set the ${name} commit status on ${headSha} \u2014 does the caller workflow grant \`statuses: write\`? (rmartz/pr-policy#24)`
2154
2195
  );
2155
2196
  }
2156
2197
  }
2157
- async function postVerdict(target, headSha, evaluation) {
2158
- await postCheckRun(target, headSha, evaluation);
2159
- await postCommitStatus(target, headSha, evaluation);
2198
+ async function postVerdict(target, headSha, evaluation, options = {}) {
2199
+ const name = options.name ?? PR_POLICY_CHECK_NAME;
2200
+ await postCheckRun(target, headSha, evaluation, { name });
2201
+ await postCommitStatus(target, headSha, evaluation, name);
2160
2202
  }
2161
2203
 
2162
2204
  // 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
- });
2205
+ async function list(target, endpoint, key) {
2206
+ const out = await clientOf(target).list(endpoint, key);
2167
2207
  if (out === null) throw new Error(`could not read ${endpoint}`);
2168
- return out.split("\n").filter((line) => line.trim() !== "");
2208
+ return out;
2169
2209
  }
2170
2210
  function times(stamps) {
2171
2211
  return stamps.map((stamp) => Date.parse(stamp)).filter((ms) => !Number.isNaN(ms));
2172
2212
  }
2173
2213
  async function gatherHeadPushedAt(target, headSha) {
2214
+ const events = await list(target, `repos/${target.repo}/issues/${target.pr}/events`);
2174
2215
  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
- )
2216
+ events.filter((event) => event.event === "head_ref_force_pushed").map((e) => e.created_at)
2180
2217
  );
2181
- const suites = times(
2182
- await lines(
2183
- target,
2184
- `repos/${target.repo}/commits/${headSha}/check-suites`,
2185
- ".check_suites[].created_at"
2186
- )
2218
+ const checkSuites = await list(
2219
+ target,
2220
+ `repos/${target.repo}/commits/${headSha}/check-suites`,
2221
+ "check_suites"
2187
2222
  );
2223
+ const suites = times(checkSuites.map((suite) => suite.created_at));
2188
2224
  const candidates = [...forcePushes];
2189
2225
  if (suites.length > 0) candidates.push(Math.min(...suites));
2190
2226
  if (candidates.length === 0) return void 0;
@@ -2193,39 +2229,21 @@ async function gatherHeadPushedAt(target, headSha) {
2193
2229
 
2194
2230
  // src/github/sign-offs.ts
2195
2231
  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
- );
2232
+ const out = await clientOf(target).list(`repos/${target.repo}/issues/${target.pr}/events`);
2210
2233
  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));
2234
+ return out.filter((event) => event.event === "labeled").map((event) => ({
2235
+ label: event.label?.name ?? "",
2236
+ login: event.actor?.login ?? null,
2237
+ type: event.actor?.type ?? null,
2238
+ at: event.created_at
2239
+ }));
2212
2240
  }
2213
2241
  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 }
2242
+ const out = await clientOf(target).getJson(
2243
+ `repos/${target.repo}/collaborators/${encodeURIComponent(login)}/permission`
2226
2244
  );
2227
2245
  if (out === null) return "none";
2228
- const { permission, role_name: roleName } = JSON.parse(out);
2246
+ const { permission, role_name: roleName } = out;
2229
2247
  if (isRepoPermission(roleName)) return roleName;
2230
2248
  return isRepoPermission(permission) ? permission : "none";
2231
2249
  }
@@ -2249,100 +2267,57 @@ async function gatherSignOffs(target, labels) {
2249
2267
  // src/github/sign-off-status.ts
2250
2268
  async function gatherSignOffStatus(target, sha) {
2251
2269
  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
- );
2270
+ const out = await clientOf(target).list(endpoint);
2266
2271
  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);
2272
+ const latest = out.find(
2273
+ (status2) => status2.context === SIGN_OFF_STATUS_CONTEXT
2274
+ );
2268
2275
  if (latest === void 0) return void 0;
2269
2276
  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 } };
2277
+ if (latest.creator === null) return status;
2278
+ const { login, type } = latest.creator;
2279
+ const permission = type === "User" ? await lookupPermission(target, login) : "none";
2280
+ return { ...status, creator: { login, type, permission } };
2274
2281
  }
2275
2282
 
2276
2283
  // 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);
2284
+ async function getJson(target, path) {
2285
+ const out = await clientOf(target).getJson(path);
2286
+ if (out === null) throw new Error(`GitHub call failed: GET ${path}`);
2287
+ return out;
2281
2288
  }
2282
2289
  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 }
2290
+ const out = await clientOf(target).getRaw(
2291
+ `repos/${target.repo}/contents/${path}?ref=${encodeURIComponent(ref)}`
2295
2292
  );
2296
2293
  if (out === null) throw new Error(`could not read ${path} at ${ref}`);
2297
2294
  return out;
2298
2295
  }
2299
2296
  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
- );
2297
+ const out = await clientOf(target).list(`repos/${target.repo}/pulls/${target.pr}/files`);
2314
2298
  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));
2299
+ return out;
2316
2300
  }
2317
2301
  async function gatherBase(target, view) {
2318
2302
  const branch = view.base.ref;
2319
2303
  const defaultBranch = view.base.repo.default_branch;
2320
2304
  if (branch === defaultBranch) return { branch, defaultBranch, headOf: [] };
2321
2305
  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 }
2306
+ const out = await clientOf(target).list(
2307
+ `repos/${target.repo}/pulls?state=open&head=${head}&per_page=100`
2335
2308
  );
2336
2309
  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));
2310
+ const headOf = out.map(
2311
+ (pull) => ({
2312
+ number: pull.number,
2313
+ labels: pull.labels.map((label) => label.name)
2314
+ })
2315
+ );
2338
2316
  return { branch, defaultBranch, headOf };
2339
2317
  }
2340
- async function gatherFacts(target) {
2341
- const view = await ghJson(target, [
2342
- "gh",
2343
- "api",
2344
- `repos/${target.repo}/pulls/${target.pr}`
2345
- ]);
2318
+ async function gatherFacts(pullRequest) {
2319
+ const target = { ...pullRequest, client: clientOf(pullRequest) };
2320
+ const view = await getJson(target, `repos/${target.repo}/pulls/${target.pr}`);
2346
2321
  const headSha = view.head.sha;
2347
2322
  const files = await listFiles(target);
2348
2323
  const touches = (predicate) => files.filter((file) => predicate(file.filename) || predicate(file.previous_filename ?? ""));
@@ -2351,11 +2326,10 @@ async function gatherFacts(target) {
2351
2326
  let workflowChanges = [];
2352
2327
  let manifestChanges = [];
2353
2328
  if (workflowFiles.length > 0 || manifestFiles.length > 0) {
2354
- const comparison = await ghJson(target, [
2355
- "gh",
2356
- "api",
2329
+ const comparison = await getJson(
2330
+ target,
2357
2331
  `repos/${target.repo}/compare/${view.base.ref}...${headSha}`
2358
- ]);
2332
+ );
2359
2333
  const mergeBase = comparison.merge_base_commit.sha;
2360
2334
  const read = async (file) => ({
2361
2335
  path: file.filename,
@@ -2391,29 +2365,17 @@ async function gatherFacts(target) {
2391
2365
  }
2392
2366
  async function openPullRequestsAtHead(target, sha) {
2393
2367
  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
- );
2368
+ const out = await clientOf(target).list(endpoint);
2408
2369
  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);
2370
+ return out.filter((pull) => pull.state === "open" && pull.head.sha === sha).map((pull) => pull.number);
2410
2371
  }
2411
2372
  async function applyLabelEdits(target, evaluation) {
2373
+ const client = clientOf(target);
2412
2374
  if (evaluation.labelsToAdd.length > 0) {
2413
- await addLabels(target.repo, target.pr, evaluation.labelsToAdd, { cwd: target.cwd });
2375
+ await client.addLabels(target.repo, target.pr, evaluation.labelsToAdd);
2414
2376
  }
2415
2377
  for (const label of evaluation.labelsToRemove) {
2416
- await removeLabel(target.repo, target.pr, label, { cwd: target.cwd });
2378
+ await client.removeLabel(target.repo, target.pr, label);
2417
2379
  }
2418
2380
  }
2419
2381
 
@@ -2461,6 +2423,7 @@ export {
2461
2423
  COMMIT_TYPES,
2462
2424
  FUNCTIONAL_TYPES,
2463
2425
  parseTitle,
2426
+ isFunctionalType,
2464
2427
  TITLE_CHECK,
2465
2428
  decideTitle,
2466
2429
  titleCheck,
@@ -2474,6 +2437,8 @@ export {
2474
2437
  evaluatePolicy,
2475
2438
  parseFacts,
2476
2439
  resolveRepoTarget,
2440
+ createGhClient,
2441
+ clientOf,
2477
2442
  checkRunBody,
2478
2443
  postCheckRun,
2479
2444
  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-SWWJ3U3V.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.1",
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",