architecture-harness 0.16.0 → 0.18.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.
Files changed (124) hide show
  1. package/package.json +8 -3
  2. package/src/cli/bash-command-guard.mjs +25 -10
  3. package/src/cli/bash-command-guard.test.mjs +30 -0
  4. package/src/cli/bash-edit-guard.mjs +28 -7
  5. package/src/cli/bash-edit-guard.test.mjs +24 -0
  6. package/src/cli/budget-counter.mjs +25 -4
  7. package/src/cli/budget-guard.mjs +73 -4
  8. package/src/cli/budget-guard.test.mjs +111 -0
  9. package/src/cli/budget.mjs +3 -2
  10. package/src/cli/check-registries.test.mjs +181 -0
  11. package/src/cli/check.mjs +130 -9
  12. package/src/cli/cli.test.mjs +215 -2
  13. package/src/cli/context-signal.mjs +92 -0
  14. package/src/cli/context-signal.test.mjs +99 -0
  15. package/src/cli/contract-history.mjs +46 -0
  16. package/src/cli/contract-history.test.mjs +118 -0
  17. package/src/cli/controller-guard.mjs +73 -0
  18. package/src/cli/controller-guard.test.mjs +119 -0
  19. package/src/cli/dispatch-guard.mjs +14 -4
  20. package/src/cli/dispatch-guard.test.mjs +5 -6
  21. package/src/cli/dispatch-reminder.mjs +19 -11
  22. package/src/cli/dispatch-reminder.test.mjs +32 -0
  23. package/src/cli/dispatch.mjs +23 -2
  24. package/src/cli/dispatch.test.mjs +39 -1
  25. package/src/cli/doctor.mjs +2 -1
  26. package/src/cli/explore-guard.mjs +2 -2
  27. package/src/cli/explore-hint.mjs +67 -7
  28. package/src/cli/explore-hint.test.mjs +104 -4
  29. package/src/cli/gh-merge-command.mjs +228 -0
  30. package/src/cli/gh-merge-command.test.mjs +273 -0
  31. package/src/cli/gh-run.mjs +30 -0
  32. package/src/cli/gh-run.test.mjs +22 -0
  33. package/src/cli/git-hooks.test.mjs +28 -0
  34. package/src/cli/git-read.mjs +42 -0
  35. package/src/cli/git-read.test.mjs +94 -0
  36. package/src/cli/handoff-note.mjs +69 -0
  37. package/src/cli/handoff-note.test.mjs +71 -0
  38. package/src/cli/init.mjs +7 -3
  39. package/src/cli/issue-gate.mjs +169 -0
  40. package/src/cli/issue-gate.test.mjs +234 -0
  41. package/src/cli/ledger.mjs +138 -0
  42. package/src/cli/ledger.test.mjs +127 -0
  43. package/src/cli/merge-guard.mjs +193 -0
  44. package/src/cli/merge-guard.test.mjs +328 -0
  45. package/src/cli/plan-check.mjs +151 -0
  46. package/src/cli/plan-check.test.mjs +143 -0
  47. package/src/cli/plan-stop.mjs +101 -0
  48. package/src/cli/plan-stop.test.mjs +136 -0
  49. package/src/cli/plugin-agents.test.mjs +105 -8
  50. package/src/cli/pr-check.mjs +17 -5
  51. package/src/cli/pr-check.test.mjs +85 -4
  52. package/src/cli/prose.mjs +192 -0
  53. package/src/cli/prose.test.mjs +248 -0
  54. package/src/cli/qc.mjs +22 -0
  55. package/src/cli/registry-history.mjs +1 -1
  56. package/src/cli/report-stash.mjs +69 -0
  57. package/src/cli/report-stash.test.mjs +71 -0
  58. package/src/cli/report-stop.mjs +266 -0
  59. package/src/cli/report-stop.test.mjs +471 -0
  60. package/src/cli/shell-command.mjs +81 -6
  61. package/src/cli/shell-command.test.mjs +101 -1
  62. package/src/cli/task-gate.mjs +179 -0
  63. package/src/cli/task-gate.test.mjs +507 -0
  64. package/src/cli/tokens.mjs +239 -0
  65. package/src/cli/tokens.test.mjs +286 -0
  66. package/src/cli/transcript-usage.mjs +135 -0
  67. package/src/cli/transcript-usage.test.mjs +129 -0
  68. package/src/cli/workflow-hooks.test.mjs +72 -0
  69. package/src/cli/workflow-place.mjs +143 -0
  70. package/src/cli/workflow-place.test.mjs +146 -0
  71. package/src/cli/workflow-settings.mjs +77 -0
  72. package/src/cli/workflow-settings.test.mjs +79 -0
  73. package/src/cli/worktree.mjs +1 -1
  74. package/src/cli/worktree.test.mjs +19 -2
  75. package/src/config.mjs +99 -4
  76. package/src/config.test.mjs +38 -3
  77. package/src/descriptions.mjs +5 -1
  78. package/src/eslint/index.mjs +2 -0
  79. package/src/eslint/jsx.mjs +57 -0
  80. package/src/eslint/preset.mjs +32 -6
  81. package/src/eslint/preset.test.mjs +60 -0
  82. package/src/eslint/rules/durable-idempotency-key.mjs +26 -0
  83. package/src/eslint/rules/ime-safe-key.mjs +1 -50
  84. package/src/eslint/rules/mutation-control-pending.mjs +128 -0
  85. package/src/eslint/rules/no-supersession-trail.mjs +8 -4
  86. package/src/eslint/rules/registry-literal.mjs +36 -2
  87. package/src/eslint/rules.test.mjs +153 -0
  88. package/src/gates/call-args.mjs +90 -0
  89. package/src/gates/call-args.test.mjs +21 -0
  90. package/src/gates/config-floor.mjs +41 -20
  91. package/src/gates/config-floor.test.mjs +71 -1
  92. package/src/gates/contract-idempotency.mjs +103 -0
  93. package/src/gates/contract-idempotency.test.mjs +276 -0
  94. package/src/gates/contract-operations.mjs +120 -0
  95. package/src/gates/contract-operations.test.mjs +275 -0
  96. package/src/gates/contract-routes.mjs +82 -0
  97. package/src/gates/contract-routes.test.mjs +210 -0
  98. package/src/gates/registry-literal.mjs +79 -15
  99. package/src/gates/registry-literal.test.mjs +89 -0
  100. package/src/gates/saga-key.mjs +253 -0
  101. package/src/gates/saga-key.test.mjs +322 -0
  102. package/src/gates/scrub.mjs +108 -0
  103. package/src/gates/scrub.test.mjs +29 -0
  104. package/src/gates/tenant-isolation-test.mjs +80 -0
  105. package/src/gates/tenant-isolation-test.test.mjs +129 -0
  106. package/src/gates/tenant-predicate.mjs +644 -91
  107. package/src/gates/tenant-predicate.test.mjs +662 -1
  108. package/src/prose-lines.mjs +49 -0
  109. package/src/prose-lines.test.mjs +63 -0
  110. package/src/registries.mjs +89 -0
  111. package/src/registries.test.mjs +44 -0
  112. package/src/vale-style.test.mjs +158 -0
  113. package/templates/docs/enforcement.md +26 -2
  114. package/templates/github/workflows/ci.yml +18 -1
  115. package/templates/quality-thresholds.json +1 -1
  116. package/templates/vale/.vale.ini +7 -0
  117. package/templates/vale/styles/Qc/AndOr.yml +7 -0
  118. package/templates/vale/styles/Qc/InOrderTo.yml +6 -0
  119. package/templates/vale/styles/Qc/Latin.yml +9 -0
  120. package/templates/vale/styles/Qc/PassiveVoice.yml +21 -0
  121. package/templates/vale/styles/Qc/Please.yml +6 -0
  122. package/templates/vale/styles/Qc/Progress.yml +9 -0
  123. package/templates/vale/styles/Qc/SentenceLength.yml +6 -0
  124. package/templates/vale/styles/Qc/Utilize.yml +10 -0
@@ -0,0 +1,228 @@
1
+ // A fragment that finds each `gh pr merge` in a Bash or PowerShell command line, with the head sha it pins,
2
+ // the PR and repository it names, and the GH_* settings the command makes for gh.
3
+ // It also finds each `gh api` call to a PR's merge endpoint or with a `mergePullRequest` mutation, which merge with no review check.
4
+
5
+ import { readFileSync, statSync } from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { nestedCommand, programName } from "./bash-command-guard.mjs";
9
+ import { commandEnv, commandWords } from "./shell-command.mjs";
10
+ import { nativePath } from "./workflow-place.mjs";
11
+
12
+ const GH_SETTINGS = ["GH_CONFIG_DIR", "GH_HOST", "GH_REPO"];
13
+ const VALUE_FLAGS = new Set(["-b", "--body", "-F", "--body-file", "-t", "--subject", "-A", "--author-email", "--match-head-commit", "--repo"]);
14
+ const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;
15
+ const POWERSHELL_ENV = /^\$env:([A-Za-z_][A-Za-z0-9_]*)(?:=(.*))?$/is;
16
+ const MERGE_ENDPOINT = /^(?:https?:\/\/[^/]+\/(?:api\/v3\/)?)?\/?(?:repos\/[^/]+\/[^/]+\/)?pulls\/\d+\/merge\/?(?:\?.*)?$/;
17
+ const MERGE_MUTATION = /\bmergePullRequest\b/;
18
+ const GRAPHQL_ENDPOINT = /(?:^|\/)graphql\/?(?:\?.*)?$/;
19
+ const FIELD_FLAGS = new Set(["--field"]);
20
+ const PR_URL = /^https?:\/\/[^/]+\/([^/]+\/[^/]+)\/pull\/\d+/;
21
+ const REST_PATH = /^(?:https?:\/\/[^/]+\/(?:api\/v3\/)?)?\/?repos\//;
22
+ /** The short flags of `gh pr merge` and of `gh api` that take a value, and the long flags of `gh api` that do. */
23
+ const MERGE_VALUE_LETTERS = "bFtAR";
24
+ const API_VALUE_LETTERS = "FfHXqtp";
25
+ const API_VALUE_FLAGS = new Set(["--field", "--raw-field", "--header", "--method", "--jq", "--template", "--input", "--hostname", "--cache", "--preview"]);
26
+ const MAX_QUERY_BYTES = 1024 * 1024;
27
+
28
+ /** Only the settings that choose gh's account or host; a token is a credential and is never kept. */
29
+ const kept = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => GH_SETTINGS.includes(name)));
30
+
31
+ /** The settings one segment makes for the segments after it: `export NAME=value`, or PowerShell's `$env:NAME = value`. */
32
+ function settingsMadeBy(segment) {
33
+ const [first, second, third] = segment.words;
34
+ if (first === "export") {
35
+ return kept(Object.fromEntries(segment.words.slice(1).map((word) => ASSIGNMENT.exec(word)).filter(Boolean).map((m) => [m[1], m[2]])));
36
+ }
37
+ const powershell = POWERSHELL_ENV.exec(first ?? "");
38
+ if (!powershell) return {};
39
+ const value = powershell[2] ?? (second === "=" ? third : undefined);
40
+ return value === undefined ? {} : kept({ [powershell[1].toUpperCase()]: value });
41
+ }
42
+
43
+ /** The settings a command makes for gh alone: its `NAME=value` words, before it and after `env` or `sudo`. */
44
+ const prefixOf = (segment) => kept(commandEnv(segment));
45
+
46
+ /** The repository a `-R` or `--repo` flag names, as `-R o/r`, `-Ro/r`, `-R=o/r`, `--repo o/r` or `--repo=o/r`. */
47
+ const REPO_FLAG = /^(?:-R(.+)|-R|--repo(?:=(.*))?)$/s;
48
+
49
+ /** Skips the flags gh reads before its group and between its group and verb, and keeps the repository they name. */
50
+ function leadingFlags(words) {
51
+ let repo = null;
52
+ let i = 0;
53
+ for (; i < words.length && words[i].startsWith("-") && words[i] !== "-"; i++) {
54
+ const match = REPO_FLAG.exec(words[i]);
55
+ if (!match) continue;
56
+ // `-R=o/r` keeps its `=` in the first group; `--repo=` with nothing after it names no repository.
57
+ const attached = match[1]?.replace(/^=/, "") ?? match[2];
58
+ repo = attached === undefined ? (words[++i] ?? null) : attached || null;
59
+ }
60
+ return { repo, rest: words.slice(i) };
61
+ }
62
+
63
+ /**
64
+ * The words after `gh` as a command: its group, its verb, the words after the verb, and the repository a flag before the verb names.
65
+ * `gh pr -R o/r merge 60` and `gh -R o/r pr merge 60` are `pr merge 60`. `rest` holds every word after the group, flags kept.
66
+ */
67
+ function ghCommand(words) {
68
+ const first = leadingFlags(words);
69
+ const [group, ...rest] = first.rest;
70
+ const second = leadingFlags(rest);
71
+ const [verb, ...args] = second.rest;
72
+ return { group, verb, args, rest, repo: second.repo ?? first.repo };
73
+ }
74
+
75
+ function mergeOf(args) {
76
+ const merge = { sha: null, repo: null, selector: null, auto: false };
77
+ for (let i = 0; i < args.length; i++) {
78
+ const arg = args[i];
79
+ // pflag reads `-Rvalue`, `-R=value`, and a cluster of short flags that ends in -R (`-sRvalue`, `-sR value`).
80
+ const cluster = /^-([A-Za-z]*)R(.*)$/s.exec(arg);
81
+ if (cluster && !new RegExp(`[${MERGE_VALUE_LETTERS}]`).test(cluster[1])) {
82
+ const value = cluster[2] === "" ? args[++i] : cluster[2].replace(/^=/, "");
83
+ merge.repo = value ?? null;
84
+ continue;
85
+ }
86
+ const at = arg.startsWith("--") ? arg.indexOf("=") : -1;
87
+ const flag = at === -1 ? arg : arg.slice(0, at);
88
+ if (flag === "--disable-auto") return null;
89
+ if (flag === "--auto") merge.auto = true;
90
+ if (VALUE_FLAGS.has(flag)) {
91
+ const value = at === -1 ? args[++i] : arg.slice(at + 1);
92
+ if (flag === "--match-head-commit") merge.sha = value ?? null;
93
+ if (flag === "--repo") merge.repo = value ?? null;
94
+ } else if (!arg.startsWith("-") && merge.selector === null) {
95
+ merge.selector = arg;
96
+ }
97
+ }
98
+ return merge;
99
+ }
100
+
101
+ /** Every gh call in the command, in order, as `{ words, env }` with the words after `gh`; a nested shell's lines count. */
102
+ function ghCalls(command, parse) {
103
+ const calls = [];
104
+ let env = {};
105
+ for (const segment of parse(command)) {
106
+ env = { ...env, ...settingsMadeBy(segment) };
107
+ const nested = nestedCommand(segment);
108
+ if (nested) {
109
+ calls.push(...ghCalls(nested.command, nested.parse).map((call) => ({ ...call, env: { ...env, ...prefixOf(segment), ...call.env } })));
110
+ continue;
111
+ }
112
+ const [program, ...words] = commandWords(segment);
113
+ if (programName(program) === "gh") calls.push({ words, env: { ...env, ...prefixOf(segment) } });
114
+ }
115
+ return calls;
116
+ }
117
+
118
+ /** Every `gh pr merge` in the command, in order, the lines of a nested `bash -c` or `pwsh -Command` included. */
119
+ export function ghMerges(command, parse) {
120
+ const merges = [];
121
+ for (const { words, env } of ghCalls(command, parse)) {
122
+ const { group, verb, args, repo } = ghCommand(words);
123
+ if (group !== "pr" || verb !== "merge") continue;
124
+ const merge = mergeOf(args);
125
+ if (!merge) continue;
126
+ // The repository comes from a PR URL first, then -R or --repo (the one written last), then GH_REPO. GH_REPO is no setting to keep.
127
+ const { GH_REPO: fromEnv, ...settings } = env;
128
+ merge.repo = PR_URL.exec(merge.selector ?? "")?.[1] ?? merge.repo ?? repo ?? fromEnv ?? null;
129
+ merges.push({ ...merge, env: settings });
130
+ }
131
+ return merges;
132
+ }
133
+
134
+ /** A file path as the command wrote it: `~` and a Git Bash `/c/...` spelling resolve the way the shell would. */
135
+ function fileOf(cwd, spelled) {
136
+ const file = nativePath(spelled.replace(/^~(?=$|[\\/])/, os.homedir()));
137
+ return path.resolve(cwd, file);
138
+ }
139
+
140
+ /**
141
+ * The files a `gh api` call reads its body from: each `-F key=@file`, and `--input file`. `-` is standard input.
142
+ * pflag reads a short flag with its value attached (`-Fkey=@file`, `-F=key=@file`) and a cluster of short flags
143
+ * that ends in `-F` (`-iFkey=@file`, `-iF key=@file`). A letter that takes a value ends a cluster, so it hides an `F` after it.
144
+ */
145
+ function bodyFiles(args) {
146
+ const files = [];
147
+ const add = (field) => {
148
+ if (/^[^=]*=@/.test(field)) files.push(field.slice(field.indexOf("@") + 1));
149
+ };
150
+ for (let i = 0; i < args.length; i++) {
151
+ const arg = args[i];
152
+ const cluster = /^-([A-Za-z]*)F(.*)$/s.exec(arg);
153
+ if (cluster && !/[fFHXqt]/.test(cluster[1])) {
154
+ const value = cluster[2] === "" ? args[++i] : cluster[2].replace(/^=/, "");
155
+ if (value !== undefined) add(value);
156
+ continue;
157
+ }
158
+ const at = arg.startsWith("--") ? arg.indexOf("=") : -1;
159
+ const flag = at === -1 ? arg : arg.slice(0, at);
160
+ if (flag !== "--input" && !FIELD_FLAGS.has(flag)) continue;
161
+ const value = at === -1 ? args[++i] : arg.slice(at + 1);
162
+ if (value === undefined) continue;
163
+ if (flag === "--input") files.push(value);
164
+ else add(value);
165
+ }
166
+ return files;
167
+ }
168
+
169
+ /** The text of a query file, or null when it is standard input, too large, or unreadable. */
170
+ function queryText(cwd, spelled) {
171
+ if (spelled === "-") return null;
172
+ try {
173
+ const file = fileOf(cwd, spelled);
174
+ if (statSync(file).size > MAX_QUERY_BYTES) return null;
175
+ return readFileSync(file, "utf8");
176
+ } catch {
177
+ return null;
178
+ }
179
+ }
180
+
181
+ /** True for a `repos/` path that stays inside `repos/`: no `..` segment, spelled or percent-encoded, and no end at `graphql`. */
182
+ const isRestPath = (endpoint) => REST_PATH.test(endpoint) && !/(?:^|\/)(?:\.|%2e){2}(?:\/|$)/i.test(endpoint) && !GRAPHQL_ENDPOINT.test(endpoint);
183
+
184
+ /** The endpoint of a `gh api` call: its first word that is no flag and no flag's value, or null. */
185
+ function apiEndpoint(args) {
186
+ for (let i = 0; i < args.length; i++) {
187
+ const arg = args[i];
188
+ if (arg.startsWith("--")) {
189
+ if (!arg.includes("=") && API_VALUE_FLAGS.has(arg)) i++;
190
+ } else if (arg.startsWith("-") && arg.length > 1) {
191
+ // A value letter takes the rest of the word, or the next word when it ends the cluster.
192
+ const letter = [...arg.slice(1)].findIndex((char) => API_VALUE_LETTERS.includes(char));
193
+ if (letter !== -1 && letter === arg.length - 2) i++;
194
+ } else {
195
+ return arg;
196
+ }
197
+ }
198
+ return null;
199
+ }
200
+
201
+ /**
202
+ * Each `gh api` call that merges with no review check, as `{ endpoint, unreadable }`. `endpoint` is the PR merge
203
+ * endpoint as written, or the GraphQL URL as written (`graphql` when the call spells none). A call holds a
204
+ * `mergePullRequest` mutation when any argument, or any query file it reads, names it, whatever the URL spelling.
205
+ * A GraphQL call whose query file the guard cannot read fails closed, and `unreadable` names that file.
206
+ * A call whose endpoint is a `repos/` REST path that stays inside it holds no mutation, so its arguments and files are not searched.
207
+ * @param options.cwd the folder a relative query file resolves against
208
+ */
209
+ export function ghApiMerges(command, parse, { cwd = process.cwd() } = {}) {
210
+ return ghCalls(command, parse)
211
+ .map(({ words }) => ghCommand(words))
212
+ .filter(({ group }) => group === "api")
213
+ .flatMap(({ rest: args }) => {
214
+ const found = args.filter((word) => MERGE_ENDPOINT.test(word)).map((endpoint) => ({ endpoint }));
215
+ if (isRestPath(apiEndpoint(args) ?? "")) return found;
216
+ const graphql = args.find((word) => GRAPHQL_ENDPOINT.test(word));
217
+ let mutation = args.some((word) => MERGE_MUTATION.test(word));
218
+ let unreadable;
219
+ for (const file of bodyFiles(args)) {
220
+ const text = queryText(cwd, file);
221
+ if (text === null) unreadable ??= file;
222
+ else if (MERGE_MUTATION.test(text)) mutation = true;
223
+ }
224
+ if (mutation) found.push({ endpoint: graphql ?? "graphql" });
225
+ else if (graphql !== undefined && unreadable !== undefined) found.push({ endpoint: graphql, unreadable });
226
+ return found;
227
+ });
228
+ }
@@ -0,0 +1,273 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { ghApiMerges, ghMerges } from "./gh-merge-command.mjs";
7
+ import { powershellSegments } from "./powershell-command.mjs";
8
+ import { segmentsOf } from "./shell-command.mjs";
9
+
10
+ test("a POSIX merge carries its sha, PR, repository, and GH_* prefix, and never a token", () => {
11
+ assert.deepEqual(
12
+ ghMerges("GH_CONFIG_DIR=~/.config/gh-personal GH_TOKEN=x gh pr merge 60 -R o/r --squash --match-head-commit abc1234", segmentsOf),
13
+ [{ sha: "abc1234", repo: "o/r", selector: "60", auto: false, env: { GH_CONFIG_DIR: "~/.config/gh-personal" } }],
14
+ );
15
+ });
16
+
17
+ test("inline flag values, an exported setting, and a merge with no PR named", () => {
18
+ assert.deepEqual(ghMerges("gh pr merge --repo=o/r --match-head-commit=abc1234 61", segmentsOf), [
19
+ { sha: "abc1234", repo: "o/r", selector: "61", auto: false, env: {} },
20
+ ]);
21
+ assert.deepEqual(ghMerges("export GH_HOST=ghe.example.com && gh pr merge --auto -s", segmentsOf), [
22
+ { sha: null, repo: null, selector: null, auto: true, env: { GH_HOST: "ghe.example.com" } },
23
+ ]);
24
+ assert.deepEqual(ghMerges('gh pr merge -b "Closes #1" -t subject 62 --match-head-commit abc1234', segmentsOf)[0].selector, "62");
25
+ });
26
+
27
+ test("a PowerShell merge reads the $env: settings before it", () => {
28
+ assert.deepEqual(ghMerges(String.raw`$env:GH_CONFIG_DIR = "C:\gh"; gh pr merge 63 --match-head-commit abc1234`, powershellSegments), [
29
+ { sha: "abc1234", repo: null, selector: "63", auto: false, env: { GH_CONFIG_DIR: String.raw`C:\gh` } },
30
+ ]);
31
+ assert.deepEqual(ghMerges(String.raw`$env:gh_host="ghe.example.com"; gh.exe pr merge 64`, powershellSegments)[0].env, { GH_HOST: "ghe.example.com" });
32
+ });
33
+
34
+ test("a nested shell's merge is found, and what is no merge is left alone", () => {
35
+ assert.equal(ghMerges(`bash -c "gh pr merge 65"`, segmentsOf).length, 1);
36
+ assert.equal(ghMerges(`pwsh -Command "gh pr merge 66 --match-head-commit abc1234"`, powershellSegments)[0].sha, "abc1234");
37
+ for (const command of ["gh pr view 60", "gh pr merge 60 --disable-auto", "git merge feat/x", "echo gh pr merge"]) {
38
+ assert.deepEqual(ghMerges(command, segmentsOf), [], command);
39
+ }
40
+ });
41
+
42
+ test("a gh api call to a PR's merge endpoint is found, in each spelling, and no other gh api call is", () => {
43
+ const endpoints = (command, parse = segmentsOf) => ghApiMerges(command, parse).map((call) => call.endpoint);
44
+ assert.deepEqual(endpoints("gh api -X PUT repos/o/r/pulls/60/merge -f merge_method=squash"), ["repos/o/r/pulls/60/merge"]);
45
+ assert.deepEqual(endpoints("gh api --method=PUT /repos/{owner}/{repo}/pulls/61/merge"), ["/repos/{owner}/{repo}/pulls/61/merge"]);
46
+ assert.deepEqual(endpoints(`bash -c "gh api repos/o/r/pulls/62/merge -X PUT"`), ["repos/o/r/pulls/62/merge"]);
47
+ assert.deepEqual(endpoints(String.raw`gh.exe api repos/o/r/pulls/63/merge -X PUT`, powershellSegments), ["repos/o/r/pulls/63/merge"]);
48
+ for (const command of [
49
+ "gh api repos/o/r/pulls/60",
50
+ "gh api repos/o/r/pulls/60/comments",
51
+ "gh api repos/o/r/issues/60 -f body=x/pulls/1/merge",
52
+ "gh pr merge 60",
53
+ "echo gh api repos/o/r/pulls/60/merge",
54
+ ]) {
55
+ assert.deepEqual(endpoints(command), [], command);
56
+ }
57
+ });
58
+
59
+ const MUTATION = "mutation { mergePullRequest(input: {pullRequestId: \"X\"}) { clientMutationId } }";
60
+
61
+ test("a mutation word in any argument is found, whatever the spelling of the GraphQL URL", () => {
62
+ for (const url of ["graphql", "/graphql", "https://api.github.com/graphql", "https://ghe.example.com/api/graphql", "graphql/"]) {
63
+ assert.deepEqual(ghApiMerges(`gh api ${url} -f query='${MUTATION}'`, segmentsOf).map((call) => call.endpoint), [url], url);
64
+ }
65
+ assert.equal(ghApiMerges(`gh api -X POST graphql -F query='${MUTATION}'`, segmentsOf).length, 1);
66
+ assert.equal(ghApiMerges(`gh api graphql -f query='${MUTATION}'`, powershellSegments).length, 1);
67
+ assert.equal(ghApiMerges(`gh api graphql -f query='query { viewer { login } }'`, segmentsOf).length, 0);
68
+ assert.equal(ghApiMerges("gh api https://api.github.com/graphql -f query='query { viewer { login } }'", segmentsOf).length, 0);
69
+ });
70
+
71
+ test("a query file the call reads is searched for the mutation, and a file the guard cannot read fails closed", (t) => {
72
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-gh-api-"));
73
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
74
+ writeFileSync(path.join(dir, "merge.graphql"), MUTATION);
75
+ writeFileSync(path.join(dir, "viewer.graphql"), "query { viewer { login } }");
76
+ writeFileSync(path.join(dir, "body.json"), JSON.stringify({ query: MUTATION }));
77
+ const found = (command) => ghApiMerges(command, segmentsOf, { cwd: dir });
78
+ assert.equal(found("gh api https://api.github.com/graphql -F query=@merge.graphql").length, 1);
79
+ assert.equal(found("gh api graphql --field=query=@merge.graphql").length, 1);
80
+ assert.equal(found("gh api graphql --input body.json").length, 1);
81
+ assert.equal(found(`gh api graphql -F query=@${path.join(dir, "merge.graphql").replaceAll("\\", "/")}`).length, 1);
82
+ assert.equal(found("gh api graphql -Fquery=@merge.graphql").length, 1, "an attached short flag carries its value");
83
+ assert.equal(found("gh api graphql -F=query=@merge.graphql").length, 1);
84
+ assert.equal(found("gh api graphql -fquery=@merge.graphql").length, 0, "-f reads no file");
85
+ assert.equal(found("gh api graphql -Fquery=@missing.graphql")[0].unreadable, "missing.graphql");
86
+ assert.equal(found("gh api graphql -iFquery=@merge.graphql").length, 1, "a cluster of short flags ends in -F");
87
+ assert.equal(found("gh api graphql -i -F query=@merge.graphql").length, 1);
88
+ assert.equal(found("gh api graphql -iF query=@merge.graphql").length, 1, "a cluster that ends in -F takes the next argument");
89
+ assert.equal(found("gh api graphql -fFquery=@merge.graphql").length, 0, "-f takes the rest of the word as its value");
90
+ assert.equal(found("gh api graphql -iFquery=@viewer.graphql").length, 0);
91
+ assert.equal(found("gh api graphql --field=query=@missing.graphql")[0].unreadable, "missing.graphql");
92
+ assert.equal(found("gh api graphql -Fquery=@-")[0].unreadable, "-");
93
+ assert.equal(found("gh api graphql -iFquery=@missing.graphql")[0].unreadable, "missing.graphql");
94
+ assert.equal(found("gh api graphql -Fquery=@viewer.graphql").length, 0);
95
+ assert.equal(found("gh api graphql -F query=@viewer.graphql").length, 0);
96
+ assert.equal(found("gh api graphql -f query=@merge.graphql").length, 0, "-f sends the text as written and reads no file");
97
+ const [unreadable] = found("gh api graphql -F query=@missing.graphql");
98
+ assert.equal(unreadable.endpoint, "graphql");
99
+ assert.equal(unreadable.unreadable, "missing.graphql");
100
+ assert.equal(found("gh api graphql -F query=@-")[0].unreadable, "-");
101
+ assert.equal(found("gh api graphql --input -")[0].unreadable, "-");
102
+ // A call to another endpoint never fails closed on a file it cannot read.
103
+ assert.equal(found("gh api repos/o/r/issues/1/comments -F body=@notes.txt").length, 0);
104
+ assert.equal(found("gh api repos/o/r/issues/1/comments -F body=@-").length, 0);
105
+ });
106
+
107
+ test("the repository of a merge comes from a PR URL, GH_REPO, an attached -R, or a cluster that ends in -R", () => {
108
+ const repoOf = (command, parse = segmentsOf) => ghMerges(command, parse)[0].repo;
109
+ assert.equal(repoOf("gh pr merge https://github.com/o/r/pull/5 --match-head-commit abc1234"), "o/r");
110
+ assert.equal(repoOf("gh pr merge https://ghe.example.com/o/r/pull/5/files"), "o/r");
111
+ assert.equal(repoOf("GH_REPO=o/r gh pr merge 5"), "o/r");
112
+ assert.equal(repoOf("export GH_REPO=o/r && gh pr merge 5"), "o/r");
113
+ assert.equal(repoOf(String.raw`$env:GH_REPO = "o/r"; gh pr merge 5`, powershellSegments), "o/r");
114
+ assert.equal(repoOf("gh pr merge 5 -Ro/r"), "o/r");
115
+ assert.equal(repoOf("gh pr merge 5 -R=o/r"), "o/r");
116
+ assert.equal(repoOf("gh pr merge 5 -sRo/r"), "o/r");
117
+ assert.equal(repoOf("gh pr merge 5 -sR o/r"), "o/r");
118
+ assert.equal(repoOf("gh pr merge 5 --repo=o/r"), "o/r");
119
+ assert.equal(repoOf("GH_REPO=x/y gh pr merge 5 -R o/r"), "o/r", "an explicit -R beats GH_REPO");
120
+ assert.equal(repoOf("gh pr merge https://github.com/o/r/pull/5 -R x/y"), "o/r", "a PR URL beats -R");
121
+ assert.equal(repoOf("gh pr merge 5"), null);
122
+ assert.equal(repoOf("gh pr merge 5 -bRo/r"), null, "-b takes the rest of the word as its value");
123
+ assert.deepEqual(ghMerges("GH_REPO=o/r gh pr merge 5", segmentsOf)[0].env, {}, "GH_REPO is not kept as a setting");
124
+ });
125
+
126
+ test("a mutation search skips a call whose endpoint is a repos/ REST path", (t) => {
127
+ const dir = mkdtempSync(path.join(os.tmpdir(), "qc-gh-api-rest-"));
128
+ t.after(() => rmSync(dir, { recursive: true, force: true }));
129
+ writeFileSync(path.join(dir, "review.md"), "The bypass is the mergePullRequest mutation.");
130
+ const found = (command) => ghApiMerges(command, segmentsOf, { cwd: dir });
131
+ assert.equal(found("gh api repos/o/r/issues/64/comments -F body=@review.md").length, 0);
132
+ assert.equal(found("gh api repos/o/r/issues/64/comments -f body='see mergePullRequest'").length, 0);
133
+ assert.equal(found("gh api https://api.github.com/repos/o/r/issues/64/comments -F body=@review.md").length, 0);
134
+ assert.equal(found("gh api -X POST -H 'Accept: x' /repos/o/r/issues/64/comments -iFbody=@review.md").length, 0);
135
+ // The REST merge endpoint stays refused by its own rule.
136
+ assert.equal(found("gh api -X PUT repos/o/r/pulls/64/merge -F body=@review.md").length, 1);
137
+ // A word that only looks like a path, as the value of a flag, is no endpoint.
138
+ assert.equal(found("gh api -H repos/x graphql -f query='mutation { mergePullRequest(input: {}) { clientMutationId } }'").length, 1);
139
+ assert.equal(found("gh api graphql -F query=@review.md -f x=repos/o/r").length, 1);
140
+ assert.equal(found("gh api -q repos/x graphql -F query=@review.md").length, 1);
141
+ // A path that climbs out of repos/ or ends at graphql is searched.
142
+ const mutation = "mutation { mergePullRequest }";
143
+ for (const endpoint of ["repos/../graphql", "/repos/o/r/../../graphql", "repos/o/r/%2e%2e/graphql", "https://api.github.com/repos/../graphql", "repos/o/r/graphql", "repos/o/r/../x"]) {
144
+ assert.equal(found(`gh api ${endpoint} -f query='${mutation}'`).length, 1, endpoint);
145
+ }
146
+ });
147
+
148
+ test("each wrapper spelling is seen as a merge", () => {
149
+ for (const command of [
150
+ `bash -lc 'gh pr merge 60'`,
151
+ `bash -ic "gh pr merge 60"`,
152
+ `bash -lic 'gh pr merge 60'`,
153
+ `sh -c 'gh pr merge 60'`,
154
+ `zsh -lc 'gh pr merge 60'`,
155
+ `env gh pr merge 60`,
156
+ `env -i GH_HOST=x gh pr merge 60`,
157
+ `sudo gh pr merge 60`,
158
+ `sudo -u ci gh pr merge 60`,
159
+ `command gh pr merge 60`,
160
+ `time gh pr merge 60`,
161
+ `nohup gh pr merge 60`,
162
+ `timeout 30 gh pr merge 60`,
163
+ `env bash -lc 'sudo gh pr merge 60'`,
164
+ `eval 'gh pr merge 60'`,
165
+ `eval gh pr merge 60`,
166
+ `eval "cd x; gh pr merge 60"`,
167
+ `if true; then gh pr merge 60; fi`,
168
+ `if gh pr merge 60; then echo ok; fi`,
169
+ "if true\nthen\n gh pr merge 60\nfi",
170
+ `for n in 60; do gh pr merge $n; done`,
171
+ `{ gh pr merge 60; }`,
172
+ `bash -c 'if true; then gh pr merge 60; fi'`,
173
+ `gh pr -R o/r merge 60`,
174
+ `gh pr --repo o/r merge 60`,
175
+ `gh -R o/r pr merge 60`,
176
+ ]) {
177
+ assert.equal(ghMerges(command, segmentsOf).length, 1, command);
178
+ }
179
+ assert.equal(ghMerges(String.raw`pwsh -c "gh pr merge 60"`, powershellSegments).length, 1);
180
+ assert.equal(ghMerges(String.raw`pwsh -NoProfile -ExecutionPolicy Bypass -Command "gh pr merge 60"`, powershellSegments).length, 1);
181
+ assert.equal(ghMerges(String.raw`if ($true) { gh pr merge 60 }`, powershellSegments).length, 1);
182
+ });
183
+
184
+ test("a wrapped gh api merge is seen as one", () => {
185
+ const endpoints = (command) => ghApiMerges(command, segmentsOf).map((call) => call.endpoint);
186
+ for (const command of [
187
+ `bash -lc 'gh api -X PUT repos/o/r/pulls/60/merge'`,
188
+ `env gh api -X PUT repos/o/r/pulls/60/merge`,
189
+ `sudo gh api -X PUT repos/o/r/pulls/60/merge`,
190
+ `eval 'gh api -X PUT repos/o/r/pulls/60/merge'`,
191
+ `if true; then gh api -X PUT repos/o/r/pulls/60/merge; fi`,
192
+ `gh -R o/r api -X PUT repos/o/r/pulls/60/merge`,
193
+ ]) {
194
+ assert.deepEqual(endpoints(command), ["repos/o/r/pulls/60/merge"], command);
195
+ }
196
+ });
197
+
198
+ test("the repo flag before the verb is the merge's repo", () => {
199
+ const repo = (command) => ghMerges(command, segmentsOf)[0].repo;
200
+ assert.equal(repo("gh pr -R o/r merge 60"), "o/r");
201
+ assert.equal(repo("gh pr --repo o/r merge 60"), "o/r");
202
+ assert.equal(repo("gh pr --repo=o/r merge 60"), "o/r");
203
+ assert.equal(repo("gh pr -Ro/r merge 60"), "o/r");
204
+ assert.equal(repo("gh pr -R=o/r merge 60"), "o/r");
205
+ assert.equal(repo("gh -R o/r pr merge 60"), "o/r");
206
+ // The flag written last wins, as it does in gh, and a PR URL wins over both.
207
+ assert.equal(repo("gh pr -R a/b merge 60 -R o/r"), "o/r");
208
+ assert.equal(repo("gh pr -R a/b merge https://github.com/o/r/pull/60"), "o/r");
209
+ assert.equal(repo("GH_REPO=x/y gh pr -R o/r merge 60"), "o/r");
210
+ assert.equal(repo("GH_REPO=o/r gh pr merge 60"), "o/r");
211
+ assert.equal(repo("env GH_REPO=o/r gh pr merge 60"), "o/r");
212
+ assert.equal(repo("bash -lc 'gh pr -R o/r merge 60'"), "o/r");
213
+ assert.equal(ghMerges("gh pr -R o/r merge 60 --match-head-commit abc1234", segmentsOf)[0].sha, "abc1234");
214
+ assert.equal(ghMerges("gh pr -R o/r merge 60", segmentsOf)[0].selector, "60");
215
+ });
216
+
217
+ test("the settings a wrapper or a nested shell's prefix makes reach the merge", () => {
218
+ const env = (command) => ghMerges(command, segmentsOf)[0].env;
219
+ assert.deepEqual(env("env GH_CONFIG_DIR=/c GH_TOKEN=x gh pr merge 60"), { GH_CONFIG_DIR: "/c" });
220
+ assert.deepEqual(env("sudo GH_HOST=h gh pr merge 60"), { GH_HOST: "h" });
221
+ assert.deepEqual(env("GH_CONFIG_DIR=/c bash -lc 'gh pr merge 60'"), { GH_CONFIG_DIR: "/c" });
222
+ assert.deepEqual(env("GH_CONFIG_DIR=/c eval 'gh pr merge 60'"), { GH_CONFIG_DIR: "/c" });
223
+ });
224
+
225
+ test("a wrapped gh that is no merge is not a merge", () => {
226
+ for (const command of [
227
+ "env gh pr view 60",
228
+ "sudo gh pr -R o/r view 60",
229
+ "bash -lc 'gh pr view 60'",
230
+ "eval 'gh pr merge 60 --disable-auto'",
231
+ "if true; then gh pr list; fi",
232
+ "env echo gh pr merge 60",
233
+ "command -v gh",
234
+ "bash -lc 'echo gh pr merge 60'",
235
+ "gh pr -R o/r comment 60",
236
+ "gh -R o/r pr view merge",
237
+ ]) {
238
+ assert.deepEqual(ghMerges(command, segmentsOf), [], command);
239
+ }
240
+ // Known gap: `xargs` runs its arguments as a command, and the parser does not follow it.
241
+ assert.deepEqual(ghMerges("echo 60 | xargs gh pr merge", segmentsOf), []);
242
+ });
243
+
244
+ test("exec, nice, ionice, stdbuf, setsid, doas, builtin, and ! wrap a merge that is still seen", () => {
245
+ for (const command of [
246
+ "exec gh pr merge 5",
247
+ "nice -n 5 gh pr merge 5",
248
+ "ionice -c 3 gh pr merge 5",
249
+ "stdbuf -o0 gh pr merge 5",
250
+ "setsid gh pr merge 5",
251
+ "doas gh pr merge 5",
252
+ "builtin exec gh pr merge 5",
253
+ "bash -c 'exec gh pr merge 5'",
254
+ "! gh pr merge 5",
255
+ "if ! gh pr merge 5; then echo failed; fi",
256
+ "nice -n 5 gh api -X PUT repos/o/r/pulls/5/merge",
257
+ ]) {
258
+ assert.equal(ghMerges(command, segmentsOf).length + ghApiMerges(command, segmentsOf).length, 1, command);
259
+ }
260
+ assert.deepEqual(ghMerges("nice -n 5 gh pr view 5", segmentsOf), []);
261
+ });
262
+
263
+ test("only -R and --repo name the repository before the verb, not a longer flag that starts with them", () => {
264
+ const repo = (command) => ghMerges(command, segmentsOf)[0]?.repo;
265
+ assert.equal(repo("gh pr --repoX o/r merge 60"), undefined);
266
+ assert.equal(repo("gh pr --repoX merge 60"), null);
267
+ assert.equal(repo("gh pr --repository merge 60"), null);
268
+ assert.equal(repo("gh pr --repo o/r merge 60"), "o/r");
269
+ assert.equal(repo("gh pr --repo=o/r merge 60"), "o/r");
270
+ assert.equal(repo("gh pr -R o/r merge 60"), "o/r");
271
+ assert.equal(repo("gh pr -Ro/r merge 60"), "o/r");
272
+ assert.equal(repo("gh pr -R=o/r merge 60"), "o/r");
273
+ });
@@ -0,0 +1,30 @@
1
+ // A fragment that runs one gh call for a workflow hook. The caller passes the GH_* settings the user's
2
+ // own command made, so the hook reads with the account that command used.
3
+
4
+ import { spawnSync } from "node:child_process";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+
8
+ const GH_TIMEOUT_MS = 20_000;
9
+
10
+ /** Expands a leading `~`, `~/`, or `~\` in each value, as a shell does for an assignment. */
11
+ export function expandHome(env) {
12
+ return Object.fromEntries(
13
+ Object.entries(env ?? {}).map(([name, value]) => [
14
+ name,
15
+ typeof value === "string" && (value === "~" || value.startsWith("~/") || value.startsWith("~\\")) ? path.join(os.homedir(), value.slice(1)) : value,
16
+ ]),
17
+ );
18
+ }
19
+
20
+ /** @returns gh's stdout on exit 0, or null when gh fails, times out, or is not installed. */
21
+ export function runGh(args, { cwd = process.cwd(), env = {} } = {}) {
22
+ const result = spawnSync("gh", args, {
23
+ cwd,
24
+ encoding: "utf8",
25
+ windowsHide: true,
26
+ timeout: GH_TIMEOUT_MS,
27
+ env: { ...process.env, ...expandHome(env) },
28
+ });
29
+ return result.status === 0 ? (result.stdout ?? "") : null;
30
+ }
@@ -0,0 +1,22 @@
1
+ import { strict as assert } from "node:assert";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { test } from "node:test";
5
+ import { expandHome, runGh } from "./gh-run.mjs";
6
+
7
+ test("expandHome expands a leading ~ the way the shell would, and leaves every other value", () => {
8
+ assert.deepEqual(expandHome({ GH_CONFIG_DIR: "~/.config/gh-personal", GH_HOST: "ghe.example.com" }), {
9
+ GH_CONFIG_DIR: path.join(os.homedir(), "/.config/gh-personal"),
10
+ GH_HOST: "ghe.example.com",
11
+ });
12
+ assert.deepEqual(expandHome({ A: "~\\.config\\gh", B: "~" }), {
13
+ A: path.join(os.homedir(), "\\.config\\gh"),
14
+ B: os.homedir(),
15
+ });
16
+ assert.deepEqual(expandHome({ A: "~other/x", B: "C:/gh" }), { A: "~other/x", B: "C:/gh" });
17
+ assert.deepEqual(expandHome(undefined), {});
18
+ });
19
+
20
+ test("runGh answers null when gh fails or is missing", () => {
21
+ assert.equal(runGh(["no-such-command-for-qc"]), null);
22
+ });
@@ -5,6 +5,7 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { test } from "node:test";
7
7
  import { fileURLToPath } from "node:url";
8
+ import { defaults, requiredHooks } from "../config.mjs";
8
9
  import { hookDrift } from "./git-hooks.mjs";
9
10
 
10
11
  const TEMPLATES = fileURLToPath(new URL("../../templates/githooks/", import.meta.url));
@@ -83,3 +84,30 @@ test("qc doctor fails on hook drift, and passes the kit's template", async (t) =
83
84
  copyFileSync(path.join(TEMPLATES, "pre-commit"), path.join(r.root, ".githooks", "pre-commit"));
84
85
  assert.equal(await runDoctor({ root: r.root, hooks: { required: REQUIRED } }), 0);
85
86
  });
87
+
88
+ const withConventional = (conventional) => ({ ...defaults, commitMessage: { ...defaults.commitMessage, conventional } });
89
+
90
+ function strictFolder(t, names) {
91
+ const r = repo(t);
92
+ mkdirSync(path.join(r.root, ".githooks"));
93
+ for (const name of names) copyFileSync(path.join(TEMPLATES, name), path.join(r.root, ".githooks", name));
94
+ return r;
95
+ }
96
+
97
+ test("conventional on and no commit-msg hook fails hooks (strict folder)", (t) => {
98
+ const r = strictFolder(t, ["pre-commit", "pre-push"]);
99
+ const { problems } = hookDrift(r.root, requiredHooks(withConventional(true)));
100
+ assert.equal(problems.length, 1);
101
+ assert.equal(problems[0].path, ".githooks/commit-msg");
102
+ assert.match(problems[0].detail, /commit-msg is missing/);
103
+ });
104
+
105
+ test("conventional on and the template commit-msg hook passes", (t) => {
106
+ const r = strictFolder(t, ["pre-commit", "pre-push", "commit-msg"]);
107
+ assert.deepEqual(hookDrift(r.root, requiredHooks(withConventional(true))).problems, []);
108
+ });
109
+
110
+ test("conventional false and no commit-msg hook passes", (t) => {
111
+ const r = strictFolder(t, ["pre-commit", "pre-push"]);
112
+ assert.deepEqual(hookDrift(r.root, requiredHooks(withConventional(false))).problems, []);
113
+ });
@@ -0,0 +1,42 @@
1
+ // A fragment of the git reads the workflow checks share. Each read returns null or an empty list when git
2
+ // fails, so a check that cannot read the repository decides on what it has.
3
+
4
+ import { spawnSync } from "node:child_process";
5
+
6
+ export { keyOf as pathKey } from "./worktree.mjs";
7
+
8
+ const GIT_TIMEOUT_MS = 10_000;
9
+
10
+ /** @returns git's trimmed stdout, or null on a non-zero exit or after `timeoutMs`. */
11
+ export function gitOutWithin(timeoutMs, cwd, ...args) {
12
+ const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true, timeout: timeoutMs });
13
+ return result.status === 0 ? (result.stdout ?? "").trim() : null;
14
+ }
15
+
16
+ /** @returns git's trimmed stdout, or null on a non-zero exit or a timeout. */
17
+ export const gitOut = (cwd, ...args) => gitOutWithin(GIT_TIMEOUT_MS, cwd, ...args);
18
+
19
+ /** @returns the full sha that `ref` names as a commit, or null when the repository holds none. */
20
+ export const commitOf = (cwd, ref) => gitOut(cwd, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`);
21
+
22
+ /** @returns the branch checked out at `dir`, or null on a detached head. */
23
+ export const branchAt = (dir) => gitOut(dir, "branch", "--show-current") || null;
24
+
25
+ /** @returns the local branches whose head is `sha`, in ref order. */
26
+ export const branchesAt = (cwd, sha) =>
27
+ (gitOut(cwd, "for-each-ref", "--points-at", sha, "--format=%(refname:short)", "refs/heads") ?? "").split(/\r?\n/).filter(Boolean);
28
+
29
+ /** @returns each linked worktree of the repository at `root`, with its branch and head; the primary checkout is left out. */
30
+ export function linkedWorktrees(root) {
31
+ const out = gitOut(root, "worktree", "list", "--porcelain");
32
+ if (out === null) return [];
33
+ return out
34
+ .split(/\r?\n[ \t]*\r?\n/)
35
+ .map((block) => {
36
+ const lines = block.split(/\r?\n/);
37
+ const field = (name) => lines.find((line) => line.startsWith(`${name} `))?.slice(name.length + 1) ?? null;
38
+ return { path: field("worktree"), branch: field("branch")?.replace(/^refs\/heads\//, "") ?? null, head: field("HEAD") };
39
+ })
40
+ .filter((entry) => entry.path)
41
+ .slice(1);
42
+ }