@flyingrobots/footprint 0.0.0-stage → 0.6.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/src/symbols.ts ADDED
@@ -0,0 +1,551 @@
1
+ // Symbol-level overlap between open pull requests (flyingrobots/footprint#33).
2
+ //
3
+ // For a file two pull requests both change, the question is whether they change the same
4
+ // *symbols*. graft's `struct diff` cannot answer it: it lists signature-level changes only, and a
5
+ // body edit inside a function reads as "unchanged" (checked on this repository at
6
+ // 65d6a405..3fa62c37, where `src/cli.ts` had body edits inside `footprint` and graft reported
7
+ // `=5 unchanged`). Its lists are a subset of what changed, so two of them being disjoint proves
8
+ // nothing.
9
+ //
10
+ // So the attribution is footprint's own, over facts graft and git each state:
11
+ //
12
+ // - each side's changed lines, from `git diff -U0 <merge-base> <head> -- :(top,literal)<file>`,
13
+ // with textconv, external diff drivers and relative output off, so the patch describes the same
14
+ // raw content `git cat-file blob` hands graft;
15
+ // - the spans of the file's **top-level** symbols, from `graft read outline --json`'s jump table,
16
+ // at the merge base for removed lines and at the head for added ones.
17
+ //
18
+ // A changed line belongs to every symbol whose span holds it. Reading both ends is what keeps a
19
+ // rename honest: graft's diff reads `alpha` -> `gamma` as a removal plus an addition, and here the
20
+ // removed line names `alpha` at the base and the added line names `gamma` at the head, so the side
21
+ // touches both names and overlaps anything that touches either.
22
+ //
23
+ // Whenever a fact is missing the answer is `undetermined`, with a code and a reason, never
24
+ // `symbol-disjoint`: an absent signal must not read as a clean one. That includes a comparison
25
+ // that cannot be tied to exact commits: a pull request's merge base is taken against the base
26
+ // commit `gh` reported (`baseRefOid`), never a local branch tip, and a head that moved while its
27
+ // files were listed, or a listed file the side's own diff does not change, is undetermined
28
+ // (flyingrobots/footprint#56).
29
+ //
30
+ // One-shot graft subcommands only, each under a timeout, and only as many as the outline budget
31
+ // allows; `graft read outline` reads a working-tree path, so each revision's content is written to
32
+ // a private temporary directory, outlined there, and the directory removed at the end.
33
+
34
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
35
+ import { tmpdir } from "node:os";
36
+ import { basename, join } from "node:path";
37
+ import { $ } from "bun";
38
+ import { extensionOf, parsableByGraft } from "./languages.ts";
39
+ import type { ConflictEdge, PullRequest, SharedWith } from "./overlap.ts";
40
+ import { MAX_CONTENT_BYTES, type Remote, type RemoteCompare } from "./remote.ts";
41
+
42
+ export type Level = "symbol-disjoint" | "symbol-overlapping" | "undetermined";
43
+
44
+ /** What one side changed in one file: the symbols its changed lines fall in, and how many fell in none. */
45
+ export interface Touched {
46
+ readonly symbols: readonly string[];
47
+ /**
48
+ * Changed lines outside every top-level symbol (comments, imports, top-level code), counted as
49
+ * `git diff --numstat` counts: a modified line is one removed and one added. A whitespace-only
50
+ * line outside every symbol is not counted; one inside a symbol's span is attributed to it.
51
+ */
52
+ readonly outside: number;
53
+ }
54
+
55
+ export interface Failure {
56
+ readonly code: string;
57
+ readonly reason: string;
58
+ }
59
+
60
+ /** `remote` is true when the side was read over the GitHub API rather than from local git. */
61
+ export type SideResult = ({ readonly ok: true; readonly touched: Touched; readonly remote?: boolean }) | ({ readonly ok: false } & Failure);
62
+
63
+ /** One shared file at the symbol level. `a` and `b` are the edge's two sides, in its order. */
64
+ export interface FileSymbols {
65
+ readonly path: string;
66
+ readonly level: Level;
67
+ readonly a?: Touched;
68
+ readonly b?: Touched;
69
+ /** The symbols both sides change; present when `symbol-overlapping`. */
70
+ readonly shared?: readonly string[];
71
+ /** The sides read over the GitHub API (flyingrobots/footprint#55), because their commits are not in the local clone; absent when every side was read from local git. */
72
+ readonly github?: readonly ("a" | "b")[];
73
+ readonly code?: string;
74
+ readonly reason?: string;
75
+ }
76
+
77
+ /** An edge at the symbol level: overlapping if any shared file is, disjoint only if every one is. */
78
+ export interface SymbolLevel {
79
+ readonly level: Level;
80
+ readonly files: readonly FileSymbols[];
81
+ }
82
+
83
+ export interface SymbolAnalysis {
84
+ /** graft outline processes actually started this run; cache hits are free. */
85
+ readonly outlinesRun: number;
86
+ readonly outlineBudget: number;
87
+ readonly outlineTimeoutMs: number;
88
+ /** `gh api` calls actually started this run (flyingrobots/footprint#55); cache hits are free. */
89
+ readonly remoteCalls: number;
90
+ readonly remoteBudget: number;
91
+ readonly remoteTimeoutMs: number;
92
+ }
93
+
94
+ export interface Symbols {
95
+ /** Keyed `"<a>-<b>"`, the edge's own numbers, lower first. */
96
+ readonly edges: ReadonlyMap<string, SymbolLevel>;
97
+ /** Keyed by the other pull request's number; side `a` is this change. */
98
+ readonly overlapping: ReadonlyMap<number, SymbolLevel>;
99
+ readonly analysis: SymbolAnalysis;
100
+ }
101
+
102
+ export interface Span {
103
+ readonly symbol: string;
104
+ readonly start: number;
105
+ readonly end: number;
106
+ }
107
+
108
+ /** Turn graft content into spans, or say why not. */
109
+ export type Outliner = (content: string, path: string) => Promise<readonly Span[] | Failure>;
110
+
111
+ /** At most this many graft outline calls per run. Each is a process; graft is slow on big files. */
112
+ export const OUTLINE_BUDGET = 24;
113
+ /** Each outline call is killed after this long and its file degrades to undetermined. */
114
+ export const OUTLINE_TIMEOUT_MS = 20_000;
115
+
116
+ export function edgeKey(a: number, b: number): string {
117
+ return a < b ? `${a}-${b}` : `${b}-${a}`;
118
+ }
119
+
120
+ function isFailure(x: unknown): x is Failure {
121
+ return typeof x === "object" && x !== null && typeof (x as Failure).code === "string" && !Array.isArray(x);
122
+ }
123
+
124
+ /** The changed lines of one side of a diff, and which of them are whitespace only. */
125
+ export interface ChangedLines {
126
+ readonly binary: boolean;
127
+ /** How many hunks the diff has. A side listed as changing the file whose diff has none changes no line of it. */
128
+ readonly hunks: number;
129
+ readonly old: number[];
130
+ readonly new: number[];
131
+ /** The whitespace-only lines among `old` and `new`: attributed to a symbol whose span holds them, otherwise not counted. */
132
+ readonly blank: { readonly old: number[]; readonly new: number[] };
133
+ }
134
+
135
+ /**
136
+ * The changed lines of a unified diff, old side and new side, by line number, every line kept.
137
+ * The whitespace-only ones are also listed apart: inside a symbol's span such a line is an edit to
138
+ * that symbol (a template literal's indentation is content), and outside every span it is a blank
139
+ * separator, which `attribute` does not count, so an added function and the blank line before it
140
+ * do not read as an edit outside every symbol (flyingrobots/footprint#56). Pure.
141
+ */
142
+ export function changedLines(diff: string): ChangedLines {
143
+ const old: number[] = [], neu: number[] = [];
144
+ const blankOld: number[] = [], blankNew: number[] = [];
145
+ let binary = false;
146
+ let hunks = 0;
147
+ let o = 0, n = 0, inHunk = false;
148
+ for (const line of diff.split("\n")) {
149
+ const h = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
150
+ if (h !== null) {
151
+ o = Number(h[1]); n = Number(h[2]); inHunk = true; hunks += 1;
152
+ continue;
153
+ }
154
+ if (/^Binary files .* differ$/.test(line) || line.startsWith("GIT binary patch")) binary = true;
155
+ if (line.startsWith("diff --git")) { inHunk = false; continue; }
156
+ if (!inHunk) continue;
157
+ if (line.startsWith("\\")) continue;
158
+ const body = line.slice(1);
159
+ const blank = body.trim() === "";
160
+ if (line.startsWith("-")) { old.push(o); if (blank) blankOld.push(o); o += 1; }
161
+ else if (line.startsWith("+")) { neu.push(n); if (blank) blankNew.push(n); n += 1; }
162
+ else if (line.startsWith(" ")) { o += 1; n += 1; }
163
+ }
164
+ return { binary, hunks, old, new: neu, blank: { old: blankOld, new: blankNew } };
165
+ }
166
+
167
+ /**
168
+ * Which symbols' spans hold these lines, sorted, and how many lines no span holds. A line in
169
+ * `blank` (whitespace only) counts for a span that holds it and is not counted outside. Pure.
170
+ */
171
+ export function attribute(lines: readonly number[], spans: readonly Span[], blank: readonly number[] = []): Touched {
172
+ const names = new Set<string>();
173
+ const blanks = new Set(blank);
174
+ let outside = 0;
175
+ for (const line of lines) {
176
+ const holding = spans.filter((s) => s.start <= line && line <= s.end);
177
+ if (holding.length === 0 && !blanks.has(line)) outside += 1;
178
+ for (const s of holding) names.add(s.symbol);
179
+ }
180
+ return { symbols: [...names].sort(), outside };
181
+ }
182
+
183
+ /** `graft read outline --json` (`graft.cli.read_outline` 3.x) as spans, or why not. Pure. */
184
+ export function parseOutline(text: string): readonly Span[] | Failure {
185
+ let v: unknown;
186
+ try {
187
+ v = JSON.parse(text);
188
+ } catch {
189
+ return { code: "graft.outline_unreadable", reason: "graft read outline --json returned output that is not JSON" };
190
+ }
191
+ // Valid JSON of the wrong shape (`null`, a number, an entry that is not an object) is unreadable,
192
+ // never a throw: a throw here would cost every other edge its symbol level (flyingrobots/footprint#56).
193
+ const isObject = (x: unknown): x is Record<string, unknown> => typeof x === "object" && x !== null && !Array.isArray(x);
194
+ if (!isObject(v)) return { code: "graft.outline_unreadable", reason: "graft read outline --json returned JSON that is not an object" };
195
+ const o = v as { _schema?: { id?: unknown; version?: unknown }; jumpTable?: unknown; partial?: unknown; projection?: unknown; reason?: unknown; error?: unknown };
196
+ const schema = isObject(o._schema) ? (o._schema as { id?: unknown; version?: unknown }) : undefined;
197
+ const version = typeof schema?.version === "string" ? schema.version : "";
198
+ if (schema?.id !== "graft.cli.read_outline" || !version.startsWith("3.")) {
199
+ return { code: "graft.outline_unreadable", reason: `graft read outline answered ${String(schema?.id)}@${version || "?"}, not graft.cli.read_outline 3.x` };
200
+ }
201
+ if (o.projection === "refused") return { code: "graft.outline_refused", reason: `graft refused to outline the file: ${String(o.reason ?? "no reason given")}` };
202
+ if (o.partial === true) return { code: "graft.outline_partial", reason: `graft's outline of the file is partial${typeof o.reason === "string" ? ` (${o.reason})` : ""}, so a line outside it may still be in a symbol` };
203
+ if (typeof o.error === "string") return { code: "graft.outline_failed", reason: `graft read outline: ${o.error}` };
204
+ if (!Array.isArray(o.jumpTable)) return { code: "graft.outline_unreadable", reason: "graft read outline carried no jump table" };
205
+ const spans: Span[] = [];
206
+ for (const e of o.jumpTable as unknown[]) {
207
+ if (!isObject(e) || typeof e.symbol !== "string" || typeof e.start !== "number" || typeof e.end !== "number") {
208
+ return { code: "graft.outline_unreadable", reason: "graft read outline carried a jump-table entry without a symbol and a line span" };
209
+ }
210
+ spans.push({ symbol: e.symbol, start: e.start, end: e.end });
211
+ }
212
+ return spans;
213
+ }
214
+
215
+ /** Two sides of one shared file, classified. Overlap is decided first: it is certain whatever else is unknown. Pure. */
216
+ export function classifyFile(path: string, a: SideResult, b: SideResult): FileSymbols {
217
+ if (!a.ok) return { path, level: "undetermined", code: a.code, reason: a.reason };
218
+ if (!b.ok) return { path, level: "undetermined", code: b.code, reason: b.reason };
219
+ const inB = new Set(b.touched.symbols);
220
+ const shared = a.touched.symbols.filter((s) => inB.has(s));
221
+ const sides = [...(a.remote === true ? ["a" as const] : []), ...(b.remote === true ? ["b" as const] : [])];
222
+ const github = sides.length === 0 ? {} : { github: sides };
223
+ if (shared.length > 0) return { path, level: "symbol-overlapping", a: a.touched, b: b.touched, shared, ...github };
224
+ if (a.touched.outside > 0 && b.touched.outside > 0) {
225
+ return {
226
+ path,
227
+ level: "undetermined",
228
+ a: a.touched,
229
+ b: b.touched,
230
+ code: "symbols.outside",
231
+ reason: `both sides change lines outside every top-level symbol graft found (${a.touched.outside} and ${b.touched.outside}: comments, imports or top-level code), which no symbol can tell apart`,
232
+ ...github,
233
+ };
234
+ }
235
+ return { path, level: "symbol-disjoint", a: a.touched, b: b.touched, ...github };
236
+ }
237
+
238
+ /** The edge's level from its files': any overlap overlaps; disjoint only when every file is. Pure. */
239
+ export function edgeLevel(files: readonly FileSymbols[]): SymbolLevel {
240
+ const level: Level = files.some((f) => f.level === "symbol-overlapping")
241
+ ? "symbol-overlapping"
242
+ : files.length > 0 && files.every((f) => f.level === "symbol-disjoint") ? "symbol-disjoint" : "undetermined";
243
+ return { level, files };
244
+ }
245
+
246
+ /** Every shared file undetermined for one reason: what an edge carries when no analysis ran. */
247
+ export function undeterminedLevel(files: readonly string[], code: string, reason: string): SymbolLevel {
248
+ return { level: "undetermined", files: files.map((path) => ({ path, level: "undetermined", code, reason })) };
249
+ }
250
+
251
+ /**
252
+ * The real outliner: write the content under a private temporary directory with the file's own
253
+ * basename (graft picks the grammar by extension) and run `graft read outline` there. One deadline,
254
+ * `timeoutMs` from the start, bounds the process and the reading of both its pipes: a child that
255
+ * exits while a grandchild still holds a pipe open is stopped at the same deadline
256
+ * (flyingrobots/footprint#56). `dispose` removes the directory; the caller calls it once at the end
257
+ * of a run, and a removal that fails is returned as a failure rather than thrown, so it cannot cost
258
+ * the run the result already computed.
259
+ */
260
+ export function graftOutliner(graft: string, opts: { timeoutMs?: number } = {}): Outliner & { dispose(): Failure | null; timeoutMs: number } {
261
+ const timeoutMs = opts.timeoutMs ?? OUTLINE_TIMEOUT_MS;
262
+ let root: string | null = null;
263
+ let n = 0;
264
+ const outline = async (content: string, path: string): Promise<readonly Span[] | Failure> => {
265
+ root ??= mkdtempSync(join(tmpdir(), "footprint-outline-"));
266
+ n += 1;
267
+ const dir = join(root, String(n));
268
+ mkdirSync(dir);
269
+ const name = basename(path);
270
+ writeFileSync(join(dir, name), content);
271
+ let proc: ReturnType<typeof Bun.spawn>;
272
+ try {
273
+ proc = Bun.spawn([graft, "--cwd", dir, "read", "outline", name, "--json"], { cwd: dir, stdout: "pipe", stderr: "pipe", stdin: "ignore", timeout: timeoutMs, killSignal: "SIGKILL" });
274
+ } catch (e) {
275
+ return { code: "graft.outline_failed", reason: `graft read outline could not start: ${e instanceof Error ? e.message : String(e)}` };
276
+ }
277
+ // Read both streams while waiting, so a large outline cannot fill the pipe and stall. The exit
278
+ // and both reads race one deadline; past it the reads are cancelled, since a grandchild may
279
+ // hold a pipe open long after the child itself has gone.
280
+ const outReader = (proc.stdout as ReadableStream<Uint8Array>).getReader();
281
+ const errReader = (proc.stderr as ReadableStream<Uint8Array>).getReader();
282
+ const timedOut: Failure = { code: "graft.outline_timeout", reason: `graft read outline ${path} did not answer within ${timeoutMs} ms and was stopped` };
283
+ let timer: ReturnType<typeof setTimeout> | undefined;
284
+ const deadline = new Promise<"timeout">((resolve) => { timer = setTimeout(() => resolve("timeout"), timeoutMs); });
285
+ const done = Promise.all([proc.exited, drain(outReader), drain(errReader)]);
286
+ const settled = await Promise.race([done, deadline]);
287
+ clearTimeout(timer);
288
+ if (settled === "timeout") {
289
+ proc.kill("SIGKILL");
290
+ outReader.cancel().catch(() => {}); errReader.cancel().catch(() => {});
291
+ done.catch(() => {});
292
+ return timedOut;
293
+ }
294
+ const [code, out, err] = settled;
295
+ if (proc.signalCode !== null && proc.signalCode !== undefined) return timedOut;
296
+ if (code !== 0) return { code: "graft.outline_failed", reason: `graft read outline ${path} exited ${code}: ${err.trim().split("\n")[0] || "(no message)"}` };
297
+ return parseOutline(out);
298
+ };
299
+ return Object.assign(outline, {
300
+ timeoutMs,
301
+ dispose(): Failure | null {
302
+ if (root === null) return null;
303
+ const dir = root;
304
+ root = null;
305
+ try {
306
+ rmSync(dir, { recursive: true, force: true });
307
+ return null;
308
+ } catch (e) {
309
+ return { code: "symbols.cleanup_failed", reason: `the outline directory ${dir} could not be removed: ${e instanceof Error ? e.message : String(e)}` };
310
+ }
311
+ },
312
+ });
313
+ }
314
+
315
+ /** A stream read to its end as text; cancelling the reader ends it early. */
316
+ async function drain(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<string> {
317
+ const decoder = new TextDecoder();
318
+ let text = "";
319
+ for (;;) {
320
+ const { done, value } = await reader.read();
321
+ if (done) return text + decoder.decode();
322
+ text += decoder.decode(value, { stream: true });
323
+ }
324
+ }
325
+
326
+ /** One side of a comparison: a revision range, or why it has none. */
327
+ type Side = { readonly ok: true; readonly base: string; readonly head: string; readonly label: string; readonly compare?: RemoteCompare } | ({ readonly ok: false } & Failure);
328
+
329
+ export interface AnalyseInput {
330
+ readonly repo: string;
331
+ readonly prs: readonly PullRequest[];
332
+ /** The file-level edges, from `computeOverlap` without symbols. */
333
+ readonly conflicts: readonly ConflictEdge[];
334
+ /** The file-level overlaps with this change. */
335
+ readonly overlapping: readonly SharedWith[];
336
+ /** This change's own range: its merge base and head, or why it has none. Null when there is no such comparison. */
337
+ readonly range: { readonly base: string; readonly head: string } | Failure | null;
338
+ /** Null when graft could not be resolved. */
339
+ readonly outliner: Outliner | null;
340
+ readonly outlineBudget?: number;
341
+ /**
342
+ * The read-only GitHub API fallback (flyingrobots/footprint#55) for a pull request whose head or
343
+ * base commit is not in the local clone. Null or absent: such a side stays undetermined.
344
+ */
345
+ readonly remote?: Remote | null;
346
+ }
347
+
348
+ async function git(repo: string, ...args: string[]): Promise<{ ok: boolean; text: string; err: string }> {
349
+ const r = await $`git -C ${repo} ${args}`.quiet().nothrow();
350
+ return { ok: r.exitCode === 0, text: r.text(), err: r.stderr.toString().trim() };
351
+ }
352
+
353
+ /**
354
+ * The symbol level of every file-level edge and every overlap with this change. Bounded: only the
355
+ * shared files of pairs that share a file are analysed, outlines are cached by blob and path, and past the
356
+ * outline budget a file is undetermined with code `budget.spent`. The overlaps with this change are
357
+ * analysed first, since they are what the report is about, then the edges in number order.
358
+ */
359
+ export async function analyseSymbols(input: AnalyseInput): Promise<Symbols> {
360
+ const budget = input.outlineBudget ?? OUTLINE_BUDGET;
361
+ const remote = input.remote ?? null;
362
+ const timeoutMs = (input.outliner as { timeoutMs?: number } | null)?.timeoutMs ?? OUTLINE_TIMEOUT_MS;
363
+ let outlinesRun = 0;
364
+ const outlines = new Map<string, Promise<readonly Span[] | Failure>>();
365
+ const sides = new Map<string, Promise<Side>>();
366
+ const touched = new Map<string, Promise<SideResult>>();
367
+ const byNumber = new Map(input.prs.map((p) => [p.number, p]));
368
+
369
+ const prSide = (n: number): Promise<Side> => {
370
+ const key = `#${n}`;
371
+ let s = sides.get(key);
372
+ if (s === undefined) {
373
+ s = resolvePullSide(input.repo, byNumber.get(n), remote);
374
+ sides.set(key, s);
375
+ }
376
+ return s;
377
+ };
378
+ const rangeSide: Side | null = input.range === null
379
+ ? null
380
+ : isFailure(input.range) ? { ok: false, ...input.range } : { ok: true, base: input.range.base, head: input.range.head, label: "this change" };
381
+
382
+ /** The outline of a file at a commit the clone lacks, read over the API by commit id; cached by commit and path. */
383
+ const outlineRemote = (rev: string, path: string): Promise<readonly Span[] | Failure> => {
384
+ const key = `gh\0${rev}\0${path}`;
385
+ let p = outlines.get(key);
386
+ if (p === undefined) {
387
+ p = (async () => {
388
+ const content = await remote!.content(rev, path);
389
+ if (isFailure(content)) return content;
390
+ if (Buffer.byteLength(content) > MAX_CONTENT_BYTES) return { code: "gh.content_too_large", reason: `${path} at ${rev.slice(0, 12)} is larger than ${MAX_CONTENT_BYTES} bytes, which footprint does not read` };
391
+ if (outlinesRun >= budget) return { code: "budget.spent", reason: `the run's budget of ${budget} graft outline call${budget === 1 ? "" : "s"} was spent before this file was reached` };
392
+ outlinesRun += 1;
393
+ return input.outliner!(content, path);
394
+ })();
395
+ outlines.set(key, p);
396
+ }
397
+ return p;
398
+ };
399
+
400
+ const outlineAt = async (rev: string, path: string, viaRemote = false): Promise<readonly Span[] | Failure> => {
401
+ if (viaRemote) return outlineRemote(rev, path);
402
+ const blob = await git(input.repo, "rev-parse", "--verify", "--quiet", `${rev}:${path}`);
403
+ if (!blob.ok) return { code: "git.show_failed", reason: `${path} does not exist at ${rev.slice(0, 12)}` };
404
+ const id = blob.text.trim();
405
+ // Keyed by blob *and* path: graft picks the grammar (and may refuse) by the path, so one blob at
406
+ // two paths can have two outlines (flyingrobots/footprint#56).
407
+ const key = `${id}\0${path}`;
408
+ let p = outlines.get(key);
409
+ if (p === undefined) {
410
+ if (outlinesRun >= budget) return { code: "budget.spent", reason: `the run's budget of ${budget} graft outline call${budget === 1 ? "" : "s"} was spent before this file was reached` };
411
+ outlinesRun += 1;
412
+ p = (async () => {
413
+ const shown = await git(input.repo, "cat-file", "blob", id);
414
+ if (!shown.ok) return { code: "git.show_failed", reason: `git cat-file blob ${id} failed: ${shown.err}` };
415
+ return input.outliner!(shown.text, path);
416
+ })();
417
+ outlines.set(key, p);
418
+ }
419
+ return p;
420
+ };
421
+
422
+ const sideTouched = (side: Side, path: string): Promise<SideResult> => {
423
+ if (!side.ok) return Promise.resolve(side);
424
+ const key = `${side.base}..${side.head}:${path}`;
425
+ let t = touched.get(key);
426
+ if (t === undefined) {
427
+ t = touchedBy(side, path);
428
+ touched.set(key, t);
429
+ }
430
+ return t;
431
+ };
432
+
433
+ const touchedBy = async (side: Side & { ok: true }, path: string): Promise<SideResult> => {
434
+ // Raw content, root-relative and literal (flyingrobots/footprint#56): textconv would hand the
435
+ // diff a different text than `cat-file blob` hands graft, and a plain pathspec is relative to
436
+ // the working directory and treats `[`, `*` and `?` as a glob.
437
+ if (side.compare !== undefined) return touchedRemote(side, path);
438
+ const diff = await git(input.repo, "diff", "-U0", "--no-color", "--no-ext-diff", "--no-textconv", "--no-relative", "--no-renames", side.base, side.head, "--", `:(top,literal)${path}`);
439
+ if (!diff.ok) return { ok: false, code: "git.diff_failed", reason: `git diff ${side.base.slice(0, 12)} ${side.head.slice(0, 12)} -- ${path} failed: ${diff.err.split("\n")[0] || "(no message)"}` };
440
+ return attributeLines(side, path, changedLines(diff.text));
441
+ };
442
+
443
+ /** A side read over the API: its patch is the compare's, for exactly merge base..head. */
444
+ const touchedRemote = (side: Side & { ok: true }, path: string): Promise<SideResult> => {
445
+ const patch = side.compare!.patches.get(path);
446
+ if (patch === undefined) return Promise.resolve({ ok: false, code: "gh.compare_incomplete", reason: `the GitHub compare for ${side.label} did not list ${path} (its file list is capped), so its changed lines are not known` });
447
+ if (isFailure(patch)) return Promise.resolve({ ok: false, ...patch });
448
+ return attributeLines(side, path, changedLines(patch));
449
+ };
450
+
451
+ const attributeLines = async (side: Side & { ok: true }, path: string, lines: ChangedLines): Promise<SideResult> => {
452
+ const viaRemote = side.compare !== undefined;
453
+ const from = viaRemote ? `the GitHub compare ${side.base.slice(0, 12)}...${side.head.slice(0, 12)}` : `git diff ${side.base.slice(0, 12)} ${side.head.slice(0, 12)}`;
454
+ if (lines.binary) return { ok: false, code: "git.binary", reason: `${path} is binary in ${side.label}'s change, so it has no symbols` };
455
+ // The file was listed as changed by this side, yet its own diff changes no line of it: the list
456
+ // and the commits disagree (a head that moved, a base that is not the pull request's), so the
457
+ // side is not an empty one, it is unknown.
458
+ if (lines.hunks === 0) return { ok: false, code: "symbols.file_unchanged", reason: `${path} is listed as changed by ${side.label}, but ${from} changes no line of it, so the file list and the commits do not describe one comparison` };
459
+ // Old lines from the merge base's outline, new lines from the head's; a side with no lines on
460
+ // one end does not need (or spend budget on) that end's outline.
461
+ const ends: Array<[string, readonly number[], readonly number[]]> = [[side.base, lines.old, lines.blank.old], [side.head, lines.new, lines.blank.new]];
462
+ const names = new Set<string>();
463
+ let outside = 0;
464
+ for (const [rev, ls, blank] of ends) {
465
+ if (ls.length === 0) continue;
466
+ const spans = await outlineAt(rev, path, viaRemote);
467
+ if (isFailure(spans)) return { ok: false, ...spans };
468
+ const t = attribute(ls, spans, blank);
469
+ t.symbols.forEach((s) => names.add(s));
470
+ outside += t.outside;
471
+ }
472
+ return { ok: true, touched: { symbols: [...names].sort(), outside }, ...(viaRemote ? { remote: true } : {}) };
473
+ };
474
+
475
+ const fileLevel = async (path: string, a: () => Promise<Side>, b: () => Promise<Side>): Promise<FileSymbols> => {
476
+ if (!parsableByGraft(path)) {
477
+ const ext = extensionOf(path);
478
+ return { path, level: "undetermined", code: "language.unsupported", reason: `graft has no grammar for ${ext === "" ? "files without an extension" : `${ext} files`}, so the file has no symbols to compare` };
479
+ }
480
+ if (input.outliner === null) return { path, level: "undetermined", code: "graft.not_resolved", reason: "graft could not be resolved through the package dependency, PATH or FOOTPRINT_GRAFT, so the file is compared by name only" };
481
+ // Sequential, and the second side is not resolved once the first fails: resolving a side may
482
+ // cost a `gh api` call, and a pair already undetermined spends none (flyingrobots/footprint#56, #55).
483
+ const sa = await a();
484
+ if (!sa.ok) return classifyFile(path, sa, sa);
485
+ const sb = await b();
486
+ if (!sb.ok) return classifyFile(path, sb, sb);
487
+ const ta = await sideTouched(sa, path);
488
+ if (!ta.ok) return classifyFile(path, ta, ta);
489
+ const tb = await sideTouched(sb, path);
490
+ return classifyFile(path, ta, tb);
491
+ };
492
+
493
+ const overlapping = new Map<number, SymbolLevel>();
494
+ for (const o of input.overlapping) {
495
+ if (rangeSide === null) {
496
+ overlapping.set(o.number, undeterminedLevel(o.sharedFiles, "symbols.not_analysed", "symbol-level analysis was not run"));
497
+ continue;
498
+ }
499
+ const files: FileSymbols[] = [];
500
+ for (const path of o.sharedFiles) files.push(await fileLevel(path, async () => rangeSide, () => prSide(o.number)));
501
+ overlapping.set(o.number, edgeLevel(files));
502
+ }
503
+
504
+ const edges = new Map<string, SymbolLevel>();
505
+ for (const e of input.conflicts) {
506
+ const files: FileSymbols[] = [];
507
+ for (const path of e.sharedFiles) files.push(await fileLevel(path, () => prSide(e.a), () => prSide(e.b)));
508
+ edges.set(edgeKey(e.a, e.b), edgeLevel(files));
509
+ }
510
+
511
+ return { edges, overlapping, analysis: { outlinesRun, outlineBudget: budget, outlineTimeoutMs: timeoutMs, remoteCalls: remote?.stats().calls ?? 0, remoteBudget: remote?.stats().budget ?? 0, remoteTimeoutMs: remote?.stats().timeoutMs ?? 0 } };
512
+ }
513
+
514
+ /**
515
+ * A pull request as a revision range: its head commit, from the merge base with the base commit
516
+ * `gh` reported (`baseRefOid`). Never a local branch tip: a fork's `origin/main` can already hold
517
+ * the head, which would make the merge base the head itself and the diff empty
518
+ * (flyingrobots/footprint#56).
519
+ */
520
+ async function resolvePullSide(repo: string, p: PullRequest | undefined, remote: Remote | null): Promise<Side> {
521
+ if (p === undefined || p.headCommit === undefined) {
522
+ return { ok: false, code: "gh.head_unknown", reason: `gh did not report the head commit of ${p === undefined ? "the pull request" : `#${p.number}`}` };
523
+ }
524
+ if (p.headMoved === true) {
525
+ return { ok: false, code: "gh.head_moved", reason: `the head commit of #${p.number} changed, or could not be read again, while gh listed its files, so the files and the commit are not one snapshot` };
526
+ }
527
+ const head = p.headCommit;
528
+ const base = p.baseCommit;
529
+ // A commit the clone lacks is read over the GitHub API when there is a way to, never fetched:
530
+ // `git fetch` writes to `.git`. The API answer is pinned to the same commit ids, so the rule is
531
+ // the same: no exact comparison, no level (flyingrobots/footprint#55).
532
+ const viaGitHub = async (local: Failure): Promise<Side> => {
533
+ if (remote === null || base === undefined) return { ok: false, ...local };
534
+ const c = await remote.compare(base, head);
535
+ if ("code" in c) return { ok: false, code: c.code, reason: `${c.reason}; locally: ${local.reason}` };
536
+ return { ok: true, base: c.mergeBase, head, label: `#${p.number}`, compare: c };
537
+ };
538
+ if (!(await git(repo, "cat-file", "-e", `${head}^{commit}`)).ok) {
539
+ return viaGitHub({ code: "git.head_missing", reason: `the head commit ${head.slice(0, 12)} of #${p.number} is not in the local repository; git fetch origin pull/${p.number}/head makes it available` });
540
+ }
541
+ if (base === undefined) {
542
+ return { ok: false, code: "gh.base_unknown", reason: `gh did not report the base commit (baseRefOid) of #${p.number}, and a local branch tip is not a substitute for it` };
543
+ }
544
+ if (!(await git(repo, "cat-file", "-e", `${base}^{commit}`)).ok) {
545
+ return viaGitHub({ code: "git.base_missing", reason: `the base commit ${base.slice(0, 12)} of #${p.number}${p.baseBranch === undefined ? "" : ` (${p.baseBranch})`} is not in the local repository; git fetch origin makes it available` });
546
+ }
547
+ const mb = await git(repo, "merge-base", base, head);
548
+ const sha = mb.text.trim();
549
+ if (mb.ok && sha !== "") return { ok: true, base: sha, head, label: `#${p.number}` };
550
+ return { ok: false, code: "git.merge_base", reason: `git merge-base ${base.slice(0, 12)} ${head.slice(0, 12)} found no common commit for #${p.number}` };
551
+ }