@flyingrobots/footprint 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.ts ADDED
@@ -0,0 +1,331 @@
1
+ #!/usr/bin/env bun
2
+ // footprint speaks the Parley output protocol (flyingrobots/parley, spec v0.2): JSON Lines on
3
+ // stdout and stderr, a receipt per run, `--human` for the Markdown comment.
4
+ import { $ } from "bun";
5
+ import { defineTool, main, type Run } from "@flyingrobots/parley-emit";
6
+ import pkg from "../package.json" with { type: "json" };
7
+ import { compose, parseNumstat } from "./footprint.ts";
8
+ import { blastRadius, gutCheck, render, renderLanding, renderOverlap } from "./render.ts";
9
+ import { resolveGraft, structuralReview } from "./graft.ts";
10
+ import { landingPlan, readLandingDocs, LANDING_DOCUMENTS } from "./landing.ts";
11
+ import { computeOverlap, underReview, unavailableOverlap, type Overlap, type RangeHead } from "./overlap.ts";
12
+ import { isFailure, listOpenPullRequests, resolveGh } from "./pulls.ts";
13
+ import { analyseSymbols, graftOutliner, type Symbols } from "./symbols.ts";
14
+ import { ghRemote } from "./remote.ts";
15
+ import { COMPOSITION_SCHEMA, COMPOSITION_TYPE, compositionRecord, LANDING_SCHEMA, LANDING_TYPE, landingRecord, OVERLAP_SCHEMA, OVERLAP_TYPE, overlapRecord } from "./report.ts";
16
+ import { BLAST_RADIUS_SCHEMA, BLAST_RADIUS_TYPE, attachCallSites, exportSurface, rangeBase, rangeEnds, exportsRecord, surfaceCallSiteRows, surfaceSymbols } from "./exports.ts";
17
+ import { unsupportedLanguages } from "./languages.ts";
18
+ import { BLAST_LIMITS, COMPOSITION_BUDGET, LANDING_BUDGET, MIN_REPORT_CHARS, OVERLAP_BUDGET, REPORT_LIMIT, blastBudget } from "./bound.ts";
19
+ import { parseArgs } from "./args.ts";
20
+ import { impactIndex, parseImpact, unmatchedEntries, type ImpactIndex } from "./impact.ts";
21
+ import { COMMENT_SCHEMA, COMMENT_TYPE, commentCommand, commentProse } from "./comment.ts";
22
+ import { readFileSync } from "node:fs";
23
+ import { resolve as resolvePath } from "node:path";
24
+
25
+ let markdown = "";
26
+ let landingMarkdown = "";
27
+ let blastMarkdown = "";
28
+ let overlapMarkdown = "";
29
+
30
+ const tool = defineTool({
31
+ name: "footprint",
32
+ version: pkg.version,
33
+ commands: {
34
+ footprint: {
35
+ intent: "Report what a change touches: its composition by file kind, the gut-check flags, which exported symbols moved and where they are called from, how it lands -- what the diff puts before a reviewer, and the after-merge steps read from the repository's own RELEASE.md and AGENTS.md -- and which open pull requests it overlaps",
36
+ // The network is read-only and optional: `gh` for the open pull requests, nothing else.
37
+ // The working tree itself is read for the call sites of the changed symbols (#10).
38
+ effects: { reads: ["<cwd>/.git", "<cwd>"], writes: [], network: true, idempotent: true },
39
+ // No secret reaches footprint: `gh` holds its own credential and footprint never reads it.
40
+ secrets: [],
41
+ emits: [{ ...COMPOSITION_TYPE, schema: COMPOSITION_SCHEMA }, { ...LANDING_TYPE, schema: LANDING_SCHEMA }, { ...BLAST_RADIUS_TYPE, schema: BLAST_RADIUS_SCHEMA }, { ...OVERLAP_TYPE, schema: OVERLAP_SCHEMA }],
42
+ },
43
+ // flyingrobots/footprint#59: the one Footprint comment of a pull request, found and updated in
44
+ // place or created, with a Changelog row per run. Named first on the command line:
45
+ // `footprint comment <pr> --report <file> --change <text> --reason <text> [--remarks <text>]`.
46
+ comment: {
47
+ intent: "Post a footprint --human report as the pull request's one Footprint comment: find the comment whose first line is <!-- footprint:report --> (or adopt the most recent unmarked '## Footprint' comment by the current gh user), carry its Changelog rows over verbatim, append one row (UTC timestamp, the head's short SHA, --change, --reason, --remarks), and update it in place or create it; never edits another user's comment; at most 65536 characters",
48
+ effects: { reads: ["<--report>"], writes: ["github:<pr> issue comment (one, created or edited in place)"], network: true, idempotent: false },
49
+ secrets: [],
50
+ emits: [{ ...COMMENT_TYPE, schema: COMMENT_SCHEMA }],
51
+ },
52
+ },
53
+ retention: { count: 50 },
54
+ human: (line) => {
55
+ if (line.event !== "result") return null;
56
+ const id = (line._schema as { id?: string } | undefined)?.id;
57
+ if (id === LANDING_TYPE.id) return landingMarkdown;
58
+ if (id === BLAST_RADIUS_TYPE.id) return blastMarkdown;
59
+ if (id === OVERLAP_TYPE.id) return overlapMarkdown;
60
+ if (id === COMMENT_TYPE.id) return commentProse(line);
61
+ return markdown;
62
+ },
63
+ });
64
+
65
+ async function defaultBase(): Promise<string | null> {
66
+ for (const ref of ["origin/main", "origin/master", "main", "master"]) {
67
+ if (await $`git rev-parse --verify --quiet ${ref}`.quiet().nothrow().then((r) => r.exitCode === 0)) return ref;
68
+ }
69
+ return null;
70
+ }
71
+
72
+ const USAGE = "footprint [<range>] [--max-chars <n>] [--impact <file.jsonl>]";
73
+
74
+ async function footprint(run: Run, args: string[]): Promise<void> {
75
+ const parsed = parseArgs(args, ["--max-chars", "--impact"]);
76
+ if (!parsed.ok || parsed.positionals.length > 1) {
77
+ run.error({ code: "args.invalid", problem: parsed.ok ? `expected at most one range, got ${JSON.stringify(parsed.positionals)}` : parsed.problem, remedy: `usage: ${USAGE}` });
78
+ return;
79
+ }
80
+ // The bound on the --human report (flyingrobots/footprint#59): GitHub's 65536 unless a caller
81
+ // needs room beside it, as `footprint comment` does for the Changelog.
82
+ const maxCharsText = parsed.flags["--max-chars"];
83
+ const maxChars = maxCharsText === undefined ? REPORT_LIMIT : /^[0-9]+$/.test(maxCharsText) ? Number(maxCharsText) : NaN;
84
+ if (!(maxChars >= MIN_REPORT_CHARS && maxChars <= REPORT_LIMIT)) {
85
+ run.error({ code: "args.invalid", problem: `--max-chars must be a whole number from ${MIN_REPORT_CHARS} to ${REPORT_LIMIT}, got ${JSON.stringify(maxCharsText)}`, remedy: `usage: ${USAGE}` });
86
+ return;
87
+ }
88
+ // The posting agent's reading of the call sites, rendered in --human only (flyingrobots/footprint#59).
89
+ let impact: ImpactIndex | undefined;
90
+ const impactPath = parsed.flags["--impact"];
91
+ if (impactPath !== undefined) {
92
+ const at = resolvePath(run.cwd, impactPath);
93
+ let text: string;
94
+ try {
95
+ text = readFileSync(at, "utf8");
96
+ } catch (e) {
97
+ run.error({ code: "impact.invalid", problem: `the impact file ${at} could not be read: ${e instanceof Error ? e.message : String(e)}`, remedy: "write one JSON object per line, {symbol, system, file?, impact, dataFlow}; an empty file is allowed", remedy_target: at });
98
+ return;
99
+ }
100
+ const entries = parseImpact(text);
101
+ if (!entries.ok) {
102
+ run.error({ code: "impact.invalid", problem: `${at} line ${entries.line}: ${entries.problem}`, remedy: "write one JSON object per line, {symbol, system, file?, impact, dataFlow}", remedy_target: `${at}:${entries.line}` });
103
+ return;
104
+ }
105
+ impact = impactIndex(entries.entries);
106
+ run.step(`impact columns from ${entries.entries.length} entr${entries.entries.length === 1 ? "y" : "ies"}`, "--impact was given: the posting agent's reading of the call sites, rendered in the --human call-site tables only and labelled as the agent's; no result line carries it");
107
+ }
108
+ const given = parsed.positionals[0];
109
+ const spec = given ?? (await defaultBase());
110
+ if (spec === null) {
111
+ run.error({ code: "base.not_found", problem: "No default branch found: none of origin/main, origin/master, main or master exists", remedy: "pass a base explicitly", remedy_target: "<base>" });
112
+ return;
113
+ }
114
+ // Three dots: compare against the merge base, so unrelated default-branch commits are excluded.
115
+ const range = spec.includes("..") ? spec : `${spec}...HEAD`;
116
+ run.step(`compare ${range}`, given === undefined ? `no base was given; ${spec} is the first of origin/main, origin/master, main, master that exists` : given.includes("..") ? "the range was given on the command line" : "the base was given on the command line; three dots compare against the merge base");
117
+
118
+ // Both ends pinned to commit ids before anything is read (flyingrobots/footprint#56): the run
119
+ // takes minutes of gh calls, and a branch that advances meanwhile must not be read once for the
120
+ // changed files and again for the symbols. Every section compares the pinned range; `range`, as
121
+ // written, is what the report shows. A range git cannot resolve stays as written, so the diff
122
+ // below fails with git's own message.
123
+ const ends = rangeEnds(range);
124
+ const commitOf = async (ref: string) => (await $`git rev-parse --verify --quiet ${`${ref}^{commit}`}`.quiet().nothrow()).text().trim() || null;
125
+ const baseId = await commitOf(ends.base);
126
+ const headId = await commitOf(ends.head);
127
+ const pinned = baseId !== null && headId !== null ? `${baseId}${ends.threeDot ? "..." : ".."}${headId}` : range;
128
+
129
+ const diff = await $`git diff --numstat ${pinned}`.quiet().nothrow();
130
+ if (diff.exitCode !== 0) {
131
+ run.error({ code: "git.diff_failed", problem: `git diff --numstat ${range} exited ${diff.exitCode}: ${diff.stderr.toString().trim() || "(no message)"}`, remedy: "pass a range git can resolve", remedy_target: range });
132
+ return;
133
+ }
134
+ const changes = parseNumstat(diff.text());
135
+ const head = headId ?? ends.head;
136
+ const baseRef = await rangeBase(run.cwd, pinned);
137
+
138
+ const graft = await resolveGraft(process.env.FOOTPRINT_GRAFT);
139
+ run.step(graft === null ? "structural analysis unavailable" : `structural analysis via ${graft}`, graft === null ? "graft could not be resolved through the package or PATH; the report states the limitation rather than omitting the section" : "graft resolved through the package dependency, PATH or FOOTPRINT_GRAFT");
140
+ const review = graft === null || changes.length === 0 || !baseRef.ok ? null : await structuralReview(graft, run.cwd, baseRef.ref, head);
141
+ if (graft !== null && changes.length > 0 && review === null) {
142
+ run.warning({ code: "graft.review_failed", problem: baseRef.ok ? "graft struct review failed or returned output footprint could not read; structural analysis unavailable for this run" : `${baseRef.detail}; structural analysis unavailable for this run`, remedy: "run graft struct review --json by hand to see why", remedy_target: graft });
143
+ }
144
+
145
+ const composition = compose(changes);
146
+ const gut = gutCheck(composition);
147
+ markdown = changes.length === 0 ? `No changes in \`${range}\`.` : render(composition, changes, range, review, COMPOSITION_BUDGET);
148
+ run.result(compositionRecord(range, composition, gut, review), COMPOSITION_TYPE, { files: changes, markdown });
149
+
150
+ // The landing plan is a second result in the same run: what the diff puts in front of a reviewer
151
+ // before the merge, and the steps to take after, read from the repository rather than invented.
152
+ const landing = landingPlan(changes.map((c) => c.path), readLandingDocs(run.cwd));
153
+ run.step(
154
+ `landing plan: ${landing.after_merge.statement}`,
155
+ `after-merge steps are read from ${LANDING_DOCUMENTS.join(" and ")} under the working directory, never invented; ` +
156
+ `the before-merge guard rule is path patterns over the changed files, and found ${landing.before_merge.guards.length}`,
157
+ { read: landing.after_merge.read, guards: landing.before_merge.guards },
158
+ );
159
+ landingMarkdown = renderLanding(landing, LANDING_BUDGET);
160
+ run.result(landingRecord(range, landing), LANDING_TYPE, { markdown: landingMarkdown });
161
+
162
+ // The export surface, the third result in the same run (flyingrobots/footprint#9), and the call
163
+ // sites of every symbol it names (flyingrobots/footprint#10).
164
+ const graftSurface = await exportSurface(graft, run.cwd, pinned);
165
+ const surface = await attachCallSites(graftSurface, run.cwd);
166
+ if (surface.available) {
167
+ const scan = surface.surface.callSiteScan;
168
+ const symbols = surfaceSymbols(surface.surface).length;
169
+ run.step(
170
+ scan.available
171
+ ? `call sites of ${symbols} symbol${symbols === 1 ? "" : "s"}: ${scan.filesScanned} file${scan.filesScanned === 1 ? "" : "s"} scanned`
172
+ : `call sites unavailable (${scan.reason.code})`,
173
+ scan.available
174
+ ? "every whole-word occurrence of each symbol's name in the tracked, non-binary files of the working tree, by git ls-files; no graft contract answers with a call site's line, so this is footprint's own scan and it counts declarations, comments and strings"
175
+ : scan.reason.detail,
176
+ scan.available ? { files_scanned: scan.filesScanned, files_skipped: { ...scan.skipped } } : undefined,
177
+ );
178
+ if (!scan.available) {
179
+ run.warning({ code: "callsites.scan_failed", problem: `the call sites of the changed symbols could not be found (${scan.reason.code}): ${scan.reason.detail}`, remedy: "run footprint from inside a git repository", remedy_target: run.cwd });
180
+ }
181
+ }
182
+ if (!surface.available && surface.reason.code !== "graft.not_resolved") {
183
+ run.warning({ code: "graft.exports_failed", problem: `the export-surface diff is unavailable (${surface.reason.code}): ${surface.reason.detail}`, remedy: "run graft struct exports <base> <head> --json by hand to see why", remedy_target: graft ?? range });
184
+ }
185
+ // Changed files in languages graft's grammars cannot parse at all -- independent of whether
186
+ // graft ran or what it returned (flyingrobots/footprint#12).
187
+ const unanalysed = unsupportedLanguages(changes.map((c) => c.path));
188
+ // The report is posted as one GitHub comment, which holds at most REPORT_LIMIT characters
189
+ // (flyingrobots/footprint#51): the blast radius gets what composition and landing left.
190
+ blastMarkdown = blastRadius(surface, unanalysed, blastBudget(markdown.length, landingMarkdown.length, maxChars), BLAST_LIMITS, impact);
191
+ if (impact !== undefined) {
192
+ const rows = surface.available && surface.surface.callSiteScan.available ? surfaceCallSiteRows(surface.surface) : [];
193
+ const unmatched = unmatchedEntries(impact, rows);
194
+ if (unmatched.length > 0) {
195
+ run.warning({
196
+ code: "impact.unmatched",
197
+ problem: `${unmatched.length} impact entr${unmatched.length === 1 ? "y matches" : "ies match"} no call-site row of this range: ${unmatched.slice(0, 20).map((e) => `${e.symbol} in ${e.system}${e.file === undefined ? "" : ` at ${e.file}`}`).join("; ")}${unmatched.length > 20 ? `; and ${unmatched.length - 20} more` : ""}`,
198
+ remedy: "check each entry's symbol, system and file against the call-site tables of this head; an entry for an earlier head is stale",
199
+ });
200
+ }
201
+ }
202
+ run.result(exportsRecord(range, surface, unanalysed), BLAST_RADIUS_TYPE, { markdown: blastMarkdown });
203
+
204
+ // Cross-pull-request overlap: the fourth result in the same run, after the blast radius.
205
+ const overlap = await crossPullRequest(run, changes.map((c) => c.path), { ref: ends.head, commit: headId }, baseRef, graft);
206
+ overlapMarkdown = renderOverlap(overlap, OVERLAP_BUDGET);
207
+ run.result(overlapRecord(range, overlap), OVERLAP_TYPE, { markdown: overlapMarkdown });
208
+ }
209
+
210
+ /**
211
+ * The open pull requests that share a file with this change, and an order they could land in.
212
+ * `gh` absent, unauthenticated or rate-limited is a stated limitation and the run still succeeds:
213
+ * an omitted section would read as "nothing overlaps", which is a different claim.
214
+ */
215
+ async function crossPullRequest(
216
+ run: Run,
217
+ changed: readonly string[],
218
+ headRef: { readonly ref: string; readonly commit: string | null },
219
+ baseRef: { ok: true; ref: string } | { ok: false; detail: string },
220
+ graft: string | null,
221
+ ): Promise<Overlap> {
222
+ const gh = resolveGh();
223
+ if (gh === null) {
224
+ run.step("cross-pull-request overlap unavailable", "gh is not on PATH; the result states the limitation rather than omitting the section");
225
+ return unavailableOverlap("gh.not_found", "gh is not installed or not on PATH");
226
+ }
227
+ const pulls = await listOpenPullRequests(gh, run.cwd);
228
+ if (isFailure(pulls)) {
229
+ run.step("cross-pull-request overlap unavailable", `gh resolved but could not list the open pull requests (${pulls.code}); the result states the limitation rather than omitting the section`);
230
+ run.warning({ code: pulls.code, problem: `gh could not list the open pull requests: ${pulls.reason}`, remedy: "run gh pr list by hand to see why; the composition result is unaffected", remedy_target: gh });
231
+ return unavailableOverlap(pulls.code, pulls.reason);
232
+ }
233
+ const self = underReview(pulls.pullRequests, await rangeHead(headRef.ref, headRef.commit));
234
+ const fileLevel = computeOverlap(changed, pulls.pullRequests, { self, limit: pulls.limit });
235
+ // The symbol level of every shared file (flyingrobots/footprint#33), bounded: only the shared
236
+ // files of pairs that share one, an outline budget per run and a timeout per graft call.
237
+ const outliner = graft === null ? null : graftOutliner(graft);
238
+ let symbols: Symbols | undefined;
239
+ try {
240
+ symbols = await analyseSymbols({
241
+ repo: run.cwd,
242
+ prs: pulls.pullRequests,
243
+ conflicts: fileLevel.conflicts,
244
+ overlapping: fileLevel.overlapping,
245
+ range: baseRef.ok ? { base: baseRef.ref, head: headRef.commit ?? headRef.ref } : { code: "git.merge_base", reason: `${baseRef.detail}, so this change has no merge base to compare symbols from` },
246
+ outliner,
247
+ remote: ghRemote(gh, run.cwd),
248
+ });
249
+ } catch (e) {
250
+ // The symbol level is enrichment: a fault in it leaves every edge undetermined (file-level),
251
+ // stated as a warning, rather than costing the run its overlap section.
252
+ run.warning({ code: "symbols.analysis_failed", problem: `the symbol-level comparison of the shared files failed, so every edge is file-level: ${e instanceof Error ? e.message : String(e)}`, remedy: "report it with the range; the file-level overlap is unaffected" });
253
+ } finally {
254
+ // A directory that will not go away is a warning: the levels are already computed, and a
255
+ // throw here would cost the run its overlap section (flyingrobots/footprint#56).
256
+ const cleanup = outliner?.dispose() ?? null;
257
+ if (cleanup !== null) run.warning({ code: cleanup.code, problem: cleanup.reason, remedy: "remove the directory by hand; the overlap result is unaffected" });
258
+ }
259
+ const overlap = computeOverlap(changed, pulls.pullRequests, { self, limit: pulls.limit, symbols });
260
+ const counted = (lv: string) => overlap.conflicts.filter((c) => c.symbolLevel.level === lv).length;
261
+ if (symbols !== undefined) run.step(
262
+ `symbol level of ${overlap.conflicts.length} edge${overlap.conflicts.length === 1 ? "" : "s"}: ${counted("symbol-disjoint")} disjoint, ${counted("symbol-overlapping")} overlapping, ${counted("undetermined")} undetermined`,
263
+ `each side's changed lines from git diff -U0 against its merge base, attributed to the top-level symbols of graft read outline at the merge base and the head; ${symbols.analysis.outlinesRun} of at most ${symbols.analysis.outlineBudget} outline calls, each stopped after ${symbols.analysis.outlineTimeoutMs} ms; a pull request whose commits are not in the clone is read over read-only gh api calls by commit id, never fetched (${symbols.analysis.remoteCalls} of at most ${symbols.analysis.remoteBudget}, each stopped after ${symbols.analysis.remoteTimeoutMs} ms); a symbol-disjoint edge does not separate waves`,
264
+ );
265
+ if (self !== null) run.step(`#${self} is the pull request under review`, "its head commit is the range's head commit (or, failing a commit match, its same-repository head branch is the range's head branch), so it is excluded from the overlap rather than listed against itself");
266
+ run.step(`cross-pull-request overlap over ${overlap.openPullRequests} open pull request${overlap.openPullRequests === 1 ? "" : "s"}`, "gh listed the open pull requests and gh pr diff --name-only their files; waves are greedy first-fit over the conflict graph, a proposal rather than a minimum");
267
+ if (overlap.undetermined.length > 0) {
268
+ run.warning({ code: "gh.diff_failed", problem: `gh pr diff --name-only would not report the changed files of ${overlap.undetermined.map((u) => `#${u.number}`).join(", ")}; those pull requests are reported as undetermined rather than assumed disjoint`, remedy: "run gh pr diff --name-only by hand to see why", remedy_target: gh });
269
+ }
270
+ if (overlap.truncated) {
271
+ run.warning({ code: "gh.list_truncated", problem: `gh returned ${overlap.openPullRequests} open pull requests, the limit asked for; there may be more that were not considered`, measured: overlap.openPullRequests, limit: overlap.limit, remedy: "narrow the question, or raise the limit in src/pulls.ts" });
272
+ }
273
+ return overlap;
274
+ }
275
+
276
+ /**
277
+ * The range's head as the pull-request match needs it: the commit id pinned at the start of the
278
+ * run, and the branch name when the head is a branch (HEAD resolves to the checked-out branch;
279
+ * `origin/x` is branch `x`; a commit id or a tag has no branch name).
280
+ */
281
+ async function rangeHead(ref: string, commit: string | null): Promise<RangeHead> {
282
+ const text = async (...cmd: string[]) => (await $`${cmd}`.quiet().nothrow()).text().trim() || null;
283
+ let branch: string | null = null;
284
+ const exists = async (full: string) => (await $`git show-ref --verify --quiet ${full}`.quiet().nothrow()).exitCode === 0;
285
+ if (ref === "HEAD") branch = await text("git", "symbolic-ref", "--short", "--quiet", "HEAD");
286
+ else if (await exists(`refs/heads/${ref}`)) branch = ref;
287
+ else if (ref.startsWith("origin/") && (await exists(`refs/remotes/${ref}`))) branch = ref.slice("origin/".length);
288
+ return { commit, branch };
289
+ }
290
+
291
+ /**
292
+ * The resolved interpretation (spec §5), which is also the inv preimage: the range after the
293
+ * default base is applied, both ends as commit ids, and the graft setting. The commit ids are the
294
+ * content addresses of the subject matter, so inv moves when the compared trees move; without
295
+ * them a footprint run would declare no inputs and its inv would cover the arguments alone.
296
+ */
297
+ async function resolved(args: string[], command: string): Promise<Record<string, unknown>> {
298
+ // Never throws: an argument the handler will refuse is still recorded, so the refusal is an
299
+ // error line with exit 2 rather than a startup failure.
300
+ const parsed = parseArgs(args, command === "comment" ? ["--report", "--change", "--reason", "--remarks"] : ["--max-chars", "--impact"]);
301
+ const flags = parsed.ok ? parsed.flags : {};
302
+ if (command === "comment") {
303
+ return { command, pull_request: parsed.ok ? parsed.positionals[0] ?? null : null, report: flags["--report"] ?? null, change: flags["--change"] ?? null, reason: flags["--reason"] ?? null, remarks: flags["--remarks"] ?? null };
304
+ }
305
+ const given = (parsed.ok ? parsed.positionals[0] : args.find((a) => !a.startsWith("-"))) ?? null;
306
+ const spec = given ?? (await defaultBase());
307
+ const range = spec === null ? null : spec.includes("..") ? spec : `${spec}...HEAD`;
308
+ const ends = range === null ? [null, null] : range.split(/\.{2,3}/);
309
+ const rev = async (ref: string | null) => (ref === null ? null : (await $`git rev-parse --verify --quiet ${ref}`.quiet().nothrow()).text().trim() || null);
310
+ return {
311
+ command: "footprint", base: given, default_base: given === null ? spec : null, range, base_commit: await rev(ends[0] ?? null), head_commit: await rev(ends[1] || "HEAD"), graft: process.env.FOOTPRINT_GRAFT ?? null,
312
+ // Only when given, so a run without them resolves exactly as it did before they existed.
313
+ ...(flags["--max-chars"] === undefined ? {} : { max_chars: flags["--max-chars"] }),
314
+ ...(flags["--impact"] === undefined ? {} : { impact: flags["--impact"] }),
315
+ };
316
+ }
317
+
318
+ /** The files a run reads besides the repository: the report a comment posts, the impact entries a report renders. */
319
+ function inputs(args: string[], command: string): { path: string }[] {
320
+ const parsed = parseArgs(args, command === "comment" ? ["--report", "--change", "--reason", "--remarks"] : ["--max-chars", "--impact"]);
321
+ if (!parsed.ok) return [];
322
+ const path = command === "comment" ? parsed.flags["--report"] : parsed.flags["--impact"];
323
+ return path === undefined ? [] : [{ path }];
324
+ }
325
+
326
+ // `footprint` is the default command: `footprint <range>` names none, so it is named here unless
327
+ // the first positional argument is `comment` (flyingrobots/footprint#59).
328
+ const argv = process.argv.slice(2);
329
+ const named = argv.find((a) => !a.startsWith("-")) === "comment" ? "comment" : "footprint";
330
+ const status = await main(tool, ["footprint", ...(named === "comment" ? argv : ["footprint", ...argv])], (run, args) => (named === "comment" ? commentCommand(run, args) : footprint(run, args)), { resolved, inputs });
331
+ process.exit(status);
package/src/comment.ts ADDED
@@ -0,0 +1,291 @@
1
+ // One Footprint comment per pull request (flyingrobots/footprint#59).
2
+ //
3
+ // `footprint comment <pr> --report <file> --change <text> --reason <text> [--remarks <text>]`
4
+ // finds the pull request's Footprint comment and updates it in place, or creates it, and appends
5
+ // one row to the Changelog at its foot. The comment is identified by a hidden marker on its first
6
+ // line. A comment someone else wrote is never edited. Every `gh` call is one of five, made through
7
+ // `gh api` and `gh pr view`:
8
+ //
9
+ // gh api user --jq .login
10
+ // gh pr view <pr> --json headRefOid --jq .headRefOid
11
+ // gh api repos/{owner}/{repo}/issues/<pr>/comments --paginate --jq <one JSON object per comment>
12
+ // gh api --method POST repos/{owner}/{repo}/issues/<pr>/comments --input - --jq <id and url>
13
+ // gh api --method PATCH repos/{owner}/{repo}/issues/comments/<id> --input - --jq <id and url>
14
+ //
15
+ // The Changelog's shape and the size bound are pure functions below; the run is `commentCommand`.
16
+ import { readFileSync } from "node:fs";
17
+ import { resolve } from "node:path";
18
+ import type { Run } from "@flyingrobots/parley-emit";
19
+ import { COMMENT_REPORT_LIMIT, REPORT_LIMIT } from "./bound.ts";
20
+ import { parseArgs } from "./args.ts";
21
+ import { cellText } from "./cell.ts";
22
+ import { classifyFailure, resolveGh } from "./pulls.ts";
23
+
24
+ export const COMMENT_SCHEMA = JSON.parse(readFileSync(new URL("../schemas/footprint.comment.schema.json", import.meta.url), "utf8")) as Record<string, unknown>;
25
+ export const COMMENT_TYPE = { id: "footprint.comment", version: "1.0.0" } as const;
26
+
27
+ /** The first line of the Footprint comment, and the only thing that identifies it. */
28
+ export const MARKER = "<!-- footprint:report -->";
29
+ /** The owner's summary line, byte for byte. */
30
+ export const CHANGELOG_OPEN = "<details><summary>Changelog</summary>";
31
+ /** The owner's header lines, byte for byte. */
32
+ export const CHANGELOG_HEADER: readonly string[] = ["| Timestamp | SHA | Change | Reason | Remarks |", "| --------- | --- | ------ | ------ | ------- |"];
33
+ const CHANGELOG_CLOSE = "</details>";
34
+ /** How a comment posted before the marker existed is recognised: the report's own first heading. */
35
+ const LEGACY_HEADING = "## Footprint";
36
+ const ADOPTED = "Adopted an earlier Footprint comment that carried no marker.";
37
+ export { cellText };
38
+
39
+ export interface ChangelogRow {
40
+ readonly timestamp: string;
41
+ readonly sha: string;
42
+ readonly change: string;
43
+ readonly reason: string;
44
+ readonly remarks: string;
45
+ }
46
+
47
+ export function rowLine(r: ChangelogRow): string {
48
+ return `| ${[r.timestamp, r.sha, r.change, r.reason, r.remarks].map(cellText).join(" | ")} |`;
49
+ }
50
+
51
+ /** The rows a comment's Changelog already carries, verbatim, and how many it says were dropped. */
52
+ export interface Changelog {
53
+ readonly rows: readonly string[];
54
+ readonly dropped: number;
55
+ }
56
+
57
+ const DROPPED = /(\d+) older Changelog rows? dropped/;
58
+
59
+ function droppedNotice(n: number): string {
60
+ return `<sub>${n} older Changelog row${n === 1 ? "" : "s"} dropped to keep this comment within GitHub's ${REPORT_LIMIT}-character limit.</sub>`;
61
+ }
62
+
63
+ /** The Changelog at the foot of a comment body; none is no rows. */
64
+ export function parseChangelog(body: string): Changelog {
65
+ const lines = body.split(/\r?\n/);
66
+ const at = lines.lastIndexOf(CHANGELOG_OPEN);
67
+ if (at < 0) return { rows: [], dropped: 0 };
68
+ const rows: string[] = [];
69
+ let dropped = 0;
70
+ for (const line of lines.slice(at + 1)) {
71
+ if (line === CHANGELOG_CLOSE) break;
72
+ if (line.startsWith("|") && !CHANGELOG_HEADER.includes(line)) rows.push(line);
73
+ const m = DROPPED.exec(line);
74
+ if (m !== null) dropped = Number(m[1]);
75
+ }
76
+ return { rows, dropped };
77
+ }
78
+
79
+ export interface Built {
80
+ readonly body: string;
81
+ /** Every row the body carries, the new one last. */
82
+ readonly rows: readonly string[];
83
+ /** Older rows dropped in all, this run's and every earlier run's. */
84
+ readonly dropped: number;
85
+ }
86
+
87
+ function assemble(report: string, rows: readonly string[], dropped: number): string {
88
+ return [
89
+ MARKER,
90
+ report.trimEnd(),
91
+ "",
92
+ // The blank line after the summary is not in the owner's shape, and is needed: without it
93
+ // GitHub renders the table inside <details> as raw text (checked with `gh api markdown`).
94
+ CHANGELOG_OPEN,
95
+ "",
96
+ ...CHANGELOG_HEADER,
97
+ ...rows,
98
+ ...(dropped > 0 ? ["", droppedNotice(dropped)] : []),
99
+ "",
100
+ CHANGELOG_CLOSE,
101
+ ].join("\n");
102
+ }
103
+
104
+ /**
105
+ * The comment: the marker, the report, and the Changelog with `row` appended, at most `limit`
106
+ * characters. When every row does not fit, the oldest are dropped and the count is stated, added
107
+ * to whatever earlier runs dropped. Throws when not even the new row fits beside the report.
108
+ */
109
+ export function buildComment(report: string, changelog: Changelog, row: string, limit: number = REPORT_LIMIT): Built {
110
+ const all = [...changelog.rows, row];
111
+ for (let keep = all.length; keep >= 1; keep--) {
112
+ const rows = all.slice(all.length - keep);
113
+ const dropped = changelog.dropped + (all.length - keep);
114
+ const body = assemble(report, rows, dropped);
115
+ if (body.length <= limit) return { body, rows, dropped };
116
+ }
117
+ throw new Error(`the comment is too long: a ${report.length}-character report leaves no room for one Changelog row under ${limit} characters`);
118
+ }
119
+
120
+ export interface PullComment {
121
+ readonly id: number;
122
+ readonly login: string;
123
+ readonly body: string;
124
+ readonly created_at: string;
125
+ }
126
+
127
+ export type Target =
128
+ | { readonly kind: "marked"; readonly comment: PullComment; readonly others: readonly PullComment[] }
129
+ | { readonly kind: "legacy"; readonly comment: PullComment; readonly others: readonly PullComment[] }
130
+ | { readonly kind: "foreign"; readonly comment: PullComment }
131
+ | { readonly kind: "none" };
132
+
133
+ const isMarked = (c: PullComment) => c.body.split(/\r?\n/, 1)[0]!.trim() === MARKER;
134
+ const isLegacy = (c: PullComment) => c.body.trimStart().startsWith(LEGACY_HEADING);
135
+ const newestFirst = (a: PullComment, b: PullComment) => b.created_at.localeCompare(a.created_at) || b.id - a.id;
136
+
137
+ /**
138
+ * Which comment to write. The most recent marked comment by `login`; failing that, a marked
139
+ * comment by anyone else, which is refused; failing that, the most recent unmarked comment by
140
+ * `login` that opens with the report's heading, which is adopted; failing that, none.
141
+ */
142
+ export function findTarget(comments: readonly PullComment[], login: string): Target {
143
+ const marked = comments.filter(isMarked).sort(newestFirst);
144
+ const mine = marked.filter((c) => c.login === login);
145
+ if (mine.length > 0) return { kind: "marked", comment: mine[0]!, others: mine.slice(1) };
146
+ if (marked.length > 0) return { kind: "foreign", comment: marked[0]! };
147
+ const legacy = comments.filter((c) => c.login === login && isLegacy(c)).sort(newestFirst);
148
+ if (legacy.length > 0) return { kind: "legacy", comment: legacy[0]!, others: legacy.slice(1) };
149
+ return { kind: "none" };
150
+ }
151
+
152
+ /** UTC ISO-8601 to the second. */
153
+ export function timestamp(now: Date = new Date()): string {
154
+ return now.toISOString().replace(/\.\d{3}Z$/, "Z");
155
+ }
156
+
157
+ /** GitHub's own short form of a commit id. */
158
+ const SHORT_SHA = 7;
159
+
160
+ class Refused extends Error {
161
+ constructor(readonly code: string, readonly problem: string, readonly remedy: string, readonly target?: string) {
162
+ super(problem);
163
+ }
164
+ }
165
+
166
+ function gh(bin: string, cwd: string, args: readonly string[], input?: string): string {
167
+ const r = Bun.spawnSync([bin, ...args], { cwd, stdin: input === undefined ? "ignore" : Buffer.from(input), stdout: "pipe", stderr: "pipe" });
168
+ if (r.exitCode !== 0) {
169
+ const f = classifyFailure(r.stderr.toString(), r.exitCode ?? 1);
170
+ const code = f.code === "gh.list_failed" ? "gh.call_failed" : f.code;
171
+ throw new Refused(code, `gh ${args.slice(0, 3).join(" ")} failed: ${f.reason}`, "run the same gh command by hand to see why; nothing was written by this run unless its result line says so", bin);
172
+ }
173
+ return r.stdout.toString();
174
+ }
175
+
176
+ const COMMENTS_JQ = ".[] | {id, login: .user.login, body, created_at} | @json";
177
+ const WRITTEN_JQ = "{id, html_url} | @json";
178
+
179
+ /** The `comment` command. */
180
+ export async function commentCommand(run: Run, args: readonly string[]): Promise<void> {
181
+ try {
182
+ await post(run, args);
183
+ } catch (e) {
184
+ if (!(e instanceof Refused)) throw e;
185
+ run.error({ code: e.code, problem: e.problem, remedy: e.remedy, ...(e.target === undefined ? {} : { remedy_target: e.target }) });
186
+ }
187
+ }
188
+
189
+ const USAGE = "footprint comment <pr> --report <file> --change <text> --reason <text> [--remarks <text>]";
190
+
191
+ async function post(run: Run, argv: readonly string[]): Promise<void> {
192
+ const parsed = parseArgs(argv, ["--report", "--change", "--reason", "--remarks"]);
193
+ if (!parsed.ok) throw new Refused("args.invalid", parsed.problem, `usage: ${USAGE}`);
194
+ const { positionals, flags } = parsed;
195
+ const pr = positionals[0];
196
+ if (positionals.length !== 1 || pr === undefined || !/^[1-9][0-9]*$/.test(pr)) {
197
+ throw new Refused("args.invalid", `expected one pull request number, got ${JSON.stringify(positionals)}`, `usage: ${USAGE}`);
198
+ }
199
+ for (const f of ["--report", "--change", "--reason"]) {
200
+ if (flags[f] === undefined) throw new Refused("args.invalid", `${f} is required`, `usage: ${USAGE}`);
201
+ }
202
+ const reportPath = resolve(run.cwd, flags["--report"]!);
203
+ let report: string;
204
+ try {
205
+ report = readFileSync(reportPath, "utf8");
206
+ } catch (e) {
207
+ throw new Refused("report.unreadable", `the report ${reportPath} could not be read: ${e instanceof Error ? e.message : String(e)}`, "write the report with `footprint <range> --human > <file>` first", reportPath);
208
+ }
209
+ if (report.trim() === "") throw new Refused("report.unreadable", `the report ${reportPath} is empty`, "write the report with `footprint <range> --human > <file>` first", reportPath);
210
+
211
+ const bin = resolveGh();
212
+ if (bin === null) throw new Refused("gh.not_found", "gh is not installed or not on PATH; the comment cannot be read or written without it", "install gh and run gh auth login");
213
+ const login = gh(bin, run.cwd, ["api", "user", "--jq", ".login"]).trim();
214
+ const head = gh(bin, run.cwd, ["pr", "view", pr, "--json", "headRefOid", "--jq", ".headRefOid"]).trim();
215
+ if (!/^[0-9a-f]{40}$/.test(head)) throw new Refused("gh.call_failed", `gh pr view ${pr} answered ${JSON.stringify(head)} for the head commit, not a commit id`, "run gh pr view by hand to see why", bin);
216
+ const comments = gh(bin, run.cwd, ["api", `repos/{owner}/{repo}/issues/${pr}/comments`, "--paginate", "--jq", COMMENTS_JQ])
217
+ .split("\n").filter((l) => l.trim() !== "").map((l) => JSON.parse(l) as PullComment);
218
+
219
+ const target = findTarget(comments, login);
220
+ if (target.kind === "foreign") {
221
+ throw new Refused(
222
+ "comment.other_author",
223
+ `the Footprint comment on #${pr} (${target.comment.id}) was written by ${target.comment.login}, not ${login}; footprint never edits another user's comment, and will not post a second one`,
224
+ `run footprint comment as ${target.comment.login}, or ask them to remove the marker line from their comment`,
225
+ );
226
+ }
227
+ run.step(
228
+ target.kind === "none" ? `no Footprint comment on #${pr}: creating one` : `${target.kind === "legacy" ? "adopting" : "updating"} comment ${target.comment.id} on #${pr}`,
229
+ target.kind === "marked"
230
+ ? `its first line is ${MARKER} and ${login} wrote it`
231
+ : target.kind === "legacy"
232
+ ? `no comment carries ${MARKER}; this is the most recent by ${login} that opens with "${LEGACY_HEADING}"`
233
+ : `no comment carries ${MARKER}, and none by ${login} opens with "${LEGACY_HEADING}"`,
234
+ );
235
+ if ((target.kind === "marked" || target.kind === "legacy") && target.others.length > 0) {
236
+ run.warning({
237
+ code: "comment.duplicates",
238
+ problem: `${target.others.length} more Footprint comment${target.others.length === 1 ? "" : "s"} by ${login} on #${pr} left as they are: ${target.others.map((c) => c.id).join(", ")}`,
239
+ remedy: "delete them by hand if they are no longer wanted; footprint updates only the most recent",
240
+ });
241
+ }
242
+
243
+ const carried = target.kind === "marked" ? parseChangelog(target.comment.body) : { rows: [], dropped: 0 };
244
+ const remarks = [flags["--remarks"] ?? "", target.kind === "legacy" ? ADOPTED : ""].filter((x) => x.trim() !== "").join(" ");
245
+ const row: ChangelogRow = { timestamp: timestamp(), sha: head.slice(0, SHORT_SHA), change: flags["--change"]!, reason: flags["--reason"]!, remarks };
246
+ let built: Built;
247
+ try {
248
+ built = buildComment(report, carried, rowLine(row));
249
+ } catch (e) {
250
+ throw new Refused("comment.too_long", e instanceof Error ? e.message : String(e), `write the report with --max-chars ${COMMENT_REPORT_LIMIT}`, reportPath);
251
+ }
252
+ const dropping = built.dropped - carried.dropped;
253
+ run.step(
254
+ `changelog: ${carried.rows.length} row${carried.rows.length === 1 ? "" : "s"} carried, one appended${dropping > 0 ? `, ${dropping} oldest dropped` : ""}`,
255
+ `rows are append-only and carried verbatim, oldest first; the comment is held to GitHub's ${REPORT_LIMIT} characters, and the newest rows are kept when they do not all fit`,
256
+ );
257
+
258
+ let written: { id: number; html_url: string } | null = null;
259
+ if (!run.dryRun) {
260
+ const payload = JSON.stringify({ body: built.body });
261
+ const answer = target.kind === "none"
262
+ ? gh(bin, run.cwd, ["api", "--method", "POST", `repos/{owner}/{repo}/issues/${pr}/comments`, "--input", "-", "--jq", WRITTEN_JQ], payload)
263
+ : gh(bin, run.cwd, ["api", "--method", "PATCH", `repos/{owner}/{repo}/issues/comments/${target.comment.id}`, "--input", "-", "--jq", WRITTEN_JQ], payload);
264
+ written = JSON.parse(answer.trim()) as { id: number; html_url: string };
265
+ }
266
+ const id = written?.id ?? (target.kind === "none" ? null : target.comment.id);
267
+ run.result(
268
+ {
269
+ event: "result",
270
+ pull_request: Number(pr),
271
+ action: target.kind === "none" ? "created" : "updated",
272
+ adopted: target.kind === "legacy",
273
+ dry_run: run.dryRun,
274
+ comment: { id, url: written?.html_url ?? null },
275
+ head_sha: row.sha,
276
+ row,
277
+ changelog: { rows: built.rows.length, carried: carried.rows.length, dropped: built.dropped },
278
+ chars: built.body.length,
279
+ limit: REPORT_LIMIT,
280
+ },
281
+ COMMENT_TYPE,
282
+ );
283
+ }
284
+
285
+ /** The one line `--human` prints for the result. */
286
+ export function commentProse(line: Record<string, unknown>): string {
287
+ const c = line.comment as { id: number | null; url: string | null };
288
+ const log = line.changelog as { rows: number; dropped: number };
289
+ const verb = line.dry_run === true ? (line.action === "created" ? "Would create" : "Would update") : line.action === "created" ? "Created" : "Updated";
290
+ return `${verb} the Footprint comment on #${String(line.pull_request)}${c.url === null ? "" : `: ${c.url}`}${line.adopted === true ? " (adopted an unmarked one)" : ""} — ${log.rows} Changelog row${log.rows === 1 ? "" : "s"}${log.dropped > 0 ? `, ${log.dropped} older dropped` : ""}.`;
291
+ }