@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/pulls.ts ADDED
@@ -0,0 +1,124 @@
1
+ // The open pull requests, from `gh`. This is the only impure half of the overlap feature: it
2
+ // shells out, and everything it returns is a plain `{number, title, isDraft, files}` record for
3
+ // `src/overlap.ts` to compute over.
4
+ //
5
+ // Three `gh` calls per run plus one per pull request, all read-only:
6
+ //
7
+ // gh pr list --state open --json number,title,isDraft,headRefOid,headRefName,isCrossRepository,baseRefName,baseRefOid --limit <n>
8
+ // gh pr diff <number> --name-only
9
+ // gh pr list ... (the same listing again)
10
+ //
11
+ // The second listing binds each file list to a head commit (flyingrobots/footprint#56): `gh pr
12
+ // diff` answers for whatever the head is when it runs, so a pull request whose head commit differs
13
+ // between the two listings, or is missing from the second, is marked `headMoved` and its symbol
14
+ // level is undetermined rather than computed from a commit its file list may not describe.
15
+ //
16
+ // `gh` missing, unauthenticated or rate-limited is a stated limitation, never an omitted section:
17
+ // an absent signal that reads as a clean signal is worse than no signal.
18
+
19
+ import { $ } from "bun";
20
+ import { LIST_LIMIT, type PullRequest } from "./overlap.ts";
21
+
22
+ export interface PullsFailure {
23
+ readonly code: string;
24
+ readonly reason: string;
25
+ }
26
+
27
+ export interface Pulls {
28
+ readonly pullRequests: readonly PullRequest[];
29
+ readonly limit: number;
30
+ }
31
+
32
+ export type PullsResult = Pulls | PullsFailure;
33
+
34
+ export function isFailure(r: PullsResult): r is PullsFailure {
35
+ return (r as PullsFailure).code !== undefined;
36
+ }
37
+
38
+ /** `gh` on PATH, or null. Nothing is installed and nothing is prompted for. */
39
+ export function resolveGh(): string | null {
40
+ return Bun.which("gh");
41
+ }
42
+
43
+ /**
44
+ * Why `gh` could not answer, from what it said. The codes are stable; the reason is gh's own
45
+ * message, because a paraphrase of an authentication failure helps nobody.
46
+ */
47
+ export function classifyFailure(stderr: string, exitCode: number): PullsFailure {
48
+ const said = stderr.trim().split("\n").filter((l) => l !== "").join("; ") || `(no message, exit ${exitCode})`;
49
+ if (/rate limit/i.test(said)) return { code: "gh.rate_limited", reason: said };
50
+ if (/auth login|not logged in|requires authentication|authentication failed|bad credentials|HTTP 401/i.test(said)) {
51
+ return { code: "gh.unauthenticated", reason: said };
52
+ }
53
+ if (/no git remotes|not a git repository|known GitHub host|could not determine/i.test(said)) {
54
+ return { code: "gh.no_remote", reason: said };
55
+ }
56
+ return { code: "gh.list_failed", reason: said };
57
+ }
58
+
59
+ interface Listed {
60
+ number?: unknown;
61
+ title?: unknown;
62
+ isDraft?: unknown;
63
+ headRefOid?: unknown;
64
+ headRefName?: unknown;
65
+ isCrossRepository?: unknown;
66
+ baseRefName?: unknown;
67
+ baseRefOid?: unknown;
68
+ }
69
+
70
+ const FIELDS = "number,title,isDraft,headRefOid,headRefName,isCrossRepository,baseRefName,baseRefOid";
71
+
72
+ async function list(gh: string, cwd: string, limit: number): Promise<Listed[] | PullsFailure> {
73
+ const listed = await $`${gh} pr list --state open --json ${FIELDS} --limit ${limit}`.cwd(cwd).quiet().nothrow();
74
+ if (listed.exitCode !== 0) return classifyFailure(listed.stderr.toString(), listed.exitCode);
75
+ try {
76
+ const parsed = JSON.parse(listed.text()) as unknown;
77
+ if (!Array.isArray(parsed)) throw new TypeError("gh pr list did not return an array");
78
+ return parsed as Listed[];
79
+ } catch (e) {
80
+ return { code: "gh.list_unreadable", reason: `gh pr list --json returned output footprint could not read: ${e instanceof Error ? e.message : String(e)}` };
81
+ }
82
+ }
83
+
84
+ /**
85
+ * List the open pull requests and their changed files. A file list that `gh` would not give is
86
+ * `null`, which the computation reports as undetermined rather than treating as disjoint.
87
+ */
88
+ export async function listOpenPullRequests(gh: string, cwd: string, limit: number = LIST_LIMIT): Promise<PullsResult> {
89
+ const rows = await list(gh, cwd, limit);
90
+ if (!Array.isArray(rows)) return rows;
91
+
92
+ const listedFirst: PullRequest[] = [];
93
+ for (const row of rows) {
94
+ if (typeof row.number !== "number") continue;
95
+ listedFirst.push({
96
+ number: row.number,
97
+ title: typeof row.title === "string" ? row.title : "",
98
+ isDraft: row.isDraft === true,
99
+ files: await changedFiles(gh, cwd, row.number),
100
+ ...(typeof row.headRefOid === "string" ? { headCommit: row.headRefOid } : {}),
101
+ ...(typeof row.headRefName === "string" ? { headBranch: row.headRefName } : {}),
102
+ ...(typeof row.isCrossRepository === "boolean" ? { crossRepository: row.isCrossRepository } : {}),
103
+ ...(typeof row.baseRefName === "string" ? { baseBranch: row.baseRefName } : {}),
104
+ ...(typeof row.baseRefOid === "string" ? { baseCommit: row.baseRefOid } : {}),
105
+ });
106
+ }
107
+
108
+ // Listed again, after the files: a head that is not the same commit both times did not
109
+ // necessarily produce the file list. A second listing that fails confirms nothing, so every head
110
+ // counts as moved; the file-level overlap is unaffected.
111
+ const again = await list(gh, cwd, limit);
112
+ const heads = new Map<number, unknown>(Array.isArray(again) ? again.map((r) => [r.number as number, r.headRefOid]) : []);
113
+ const pullRequests = listedFirst.map((p) =>
114
+ p.headCommit !== undefined && heads.get(p.number) === p.headCommit ? p : { ...p, headMoved: true },
115
+ );
116
+ return { pullRequests, limit };
117
+ }
118
+
119
+ /** The paths one pull request changes, or null when `gh pr diff` would not say. */
120
+ export async function changedFiles(gh: string, cwd: string, number: number): Promise<readonly string[] | null> {
121
+ const diff = await $`${gh} pr diff ${number} --name-only`.cwd(cwd).quiet().nothrow();
122
+ if (diff.exitCode !== 0) return null;
123
+ return diff.text().split("\n").map((l) => l.trim()).filter((l) => l !== "");
124
+ }
package/src/remote.ts ADDED
@@ -0,0 +1,177 @@
1
+ // Read-only GitHub API fallback for the symbol level (flyingrobots/footprint#55).
2
+ //
3
+ // A pull request's head (or base) commit is often not in the local clone: a fork's head in CI, any
4
+ // pull request nobody fetched. The symbol level then reads that side over `gh api` instead of
5
+ // asking for a `git fetch`, which would write to `.git`; footprint declares no writes.
6
+ //
7
+ // Two calls, both GET, both naming only commit ids and the file's own path:
8
+ //
9
+ // gh api repos/{owner}/{repo}/compare/<baseRefOid>...<headRefOid>
10
+ // gh api -H 'Accept: application/vnd.github.raw' repos/{owner}/{repo}/contents/<path>?ref=<sha>
11
+ //
12
+ // `{owner}/{repo}` is gh's own placeholder, filled from the working directory's remote. The
13
+ // compare of two commit ids is exact: `merge_base_commit.sha` is the merge base, and each file's
14
+ // `patch` is the diff from that merge base to the head, the same comparison `git diff <merge-base>
15
+ // <head>` makes locally. (`gh pr diff` is not used: it diffs against the pull request's *current*
16
+ // merge base, which can differ from the one the commits pin, flyingrobots/footprint#55.) The
17
+ // contents are read at the merge base and at the head, by commit id, never a branch name.
18
+ //
19
+ // Whatever cannot be tied to exact commits is a failure with a code, never an empty answer: a
20
+ // compare without a commit-id merge base, a file with no patch (GitHub omits one for binary and
21
+ // very large diffs) or renamed, a file the compare did not list (its file list is capped), a
22
+ // rate limit, a timeout, a call past the budget, contents over 1 MiB.
23
+
24
+ import type { Failure } from "./symbols.ts";
25
+ import { classifyFailure } from "./pulls.ts";
26
+
27
+ /** At most this many `gh api` calls per run: a compare per pull request and a contents read per end of each shared file. */
28
+ export const REMOTE_BUDGET = 32;
29
+ /** Each call is stopped after this long. */
30
+ export const REMOTE_TIMEOUT_MS = 20_000;
31
+ /** Contents larger than this are not read; the file is undetermined. */
32
+ export const MAX_CONTENT_BYTES = 1024 * 1024;
33
+
34
+ /** A compare, read as the merge base it pins and each file's patch (or why it has none). */
35
+ export interface RemoteCompare {
36
+ readonly mergeBase: string;
37
+ readonly patches: ReadonlyMap<string, string | Failure>;
38
+ }
39
+
40
+ export interface Remote {
41
+ compare(base: string, head: string): Promise<RemoteCompare | Failure>;
42
+ content(sha: string, path: string): Promise<string | Failure>;
43
+ stats(): { readonly calls: number; readonly budget: number; readonly timeoutMs: number };
44
+ }
45
+
46
+ const COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
47
+
48
+ /** `gh api repos/.../compare/...` as the merge base it pins and the patches of its files. Pure. */
49
+ export function parseCompare(text: string): RemoteCompare | Failure {
50
+ let v: unknown;
51
+ try {
52
+ v = JSON.parse(text);
53
+ } catch {
54
+ return { code: "gh.compare_unpinned", reason: "the GitHub compare answered output that is not JSON, so there is no exact merge base" };
55
+ }
56
+ const o = typeof v === "object" && v !== null && !Array.isArray(v) ? (v as { merge_base_commit?: { sha?: unknown }; files?: unknown }) : null;
57
+ const sha = o?.merge_base_commit?.sha;
58
+ if (typeof sha !== "string" || !COMMIT.test(sha)) {
59
+ return { code: "gh.compare_unpinned", reason: "the GitHub compare did not state its merge base as a commit id (merge_base_commit.sha), so the comparison is not pinned to exact commits" };
60
+ }
61
+ if (!Array.isArray(o?.files)) return { code: "gh.compare_unpinned", reason: "the GitHub compare carried no file list" };
62
+ const patches = new Map<string, string | Failure>();
63
+ for (const f of o.files as unknown[]) {
64
+ const e = typeof f === "object" && f !== null ? (f as { filename?: unknown; status?: unknown; patch?: unknown }) : null;
65
+ if (e === null || typeof e.filename !== "string") continue;
66
+ if (e.status === "renamed" || e.status === "copied") {
67
+ patches.set(e.filename, { code: "gh.patch_unavailable", reason: `GitHub reports ${e.filename} as ${String(e.status)}, and its patch is against another path; footprint reads renames as unknown rather than guess` });
68
+ } else if (typeof e.patch !== "string") {
69
+ patches.set(e.filename, { code: "gh.patch_unavailable", reason: `GitHub gave no patch for ${e.filename} (it omits one for binary files and very large diffs)` });
70
+ } else {
71
+ patches.set(e.filename, e.patch);
72
+ }
73
+ }
74
+ return { mergeBase: sha, patches };
75
+ }
76
+
77
+ /** The path of a contents read: each segment percent-encoded, so `#`, `?` and `%` in a file name stay in the path. */
78
+ export function contentsPath(sha: string, path: string): string {
79
+ return `repos/{owner}/{repo}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${sha}`;
80
+ }
81
+
82
+ interface Ran { readonly code: number; readonly out: string; readonly err: string }
83
+
84
+ /** `gh` with its stdout capped; killed at the deadline, or when stdout passes the cap. */
85
+ async function runGh(gh: string, cwd: string, args: string[], timeoutMs: number, maxBytes: number): Promise<Ran | "timeout" | "too_large"> {
86
+ let proc: ReturnType<typeof Bun.spawn>;
87
+ try {
88
+ proc = Bun.spawn([gh, ...args], { cwd, stdout: "pipe", stderr: "pipe", stdin: "ignore", timeout: timeoutMs, killSignal: "SIGKILL" });
89
+ } catch (e) {
90
+ return { code: 127, out: "", err: `gh could not start: ${e instanceof Error ? e.message : String(e)}` };
91
+ }
92
+ const outReader = (proc.stdout as ReadableStream<Uint8Array>).getReader();
93
+ const errReader = (proc.stderr as ReadableStream<Uint8Array>).getReader();
94
+ let tooLarge = false;
95
+ const drain = async (reader: ReadableStreamDefaultReader<Uint8Array>, cap: number, isOut: boolean): Promise<string> => {
96
+ const decoder = new TextDecoder();
97
+ let text = "";
98
+ let bytes = 0;
99
+ for (;;) {
100
+ const { done, value } = await reader.read();
101
+ if (done) return text + decoder.decode();
102
+ bytes += value.length;
103
+ if (bytes > cap) {
104
+ if (isOut) { tooLarge = true; proc.kill("SIGKILL"); }
105
+ reader.cancel().catch(() => {});
106
+ return text;
107
+ }
108
+ text += decoder.decode(value, { stream: true });
109
+ }
110
+ };
111
+ let timer: ReturnType<typeof setTimeout> | undefined;
112
+ const deadline = new Promise<"timeout">((resolve) => { timer = setTimeout(() => resolve("timeout"), timeoutMs); });
113
+ const done = Promise.all([proc.exited, drain(outReader, maxBytes, true), drain(errReader, 64 * 1024, false)]);
114
+ const settled = await Promise.race([done, deadline]);
115
+ clearTimeout(timer);
116
+ if (settled === "timeout") {
117
+ proc.kill("SIGKILL");
118
+ outReader.cancel().catch(() => {}); errReader.cancel().catch(() => {});
119
+ done.catch(() => {});
120
+ return "timeout";
121
+ }
122
+ if (tooLarge) return "too_large";
123
+ const [code, out, err] = settled;
124
+ if (proc.signalCode !== null && proc.signalCode !== undefined) return "timeout";
125
+ return { code, out, err };
126
+ }
127
+
128
+ /**
129
+ * The real remote reader, over `gh`. Bounded like the outline calls: `budget` calls per run
130
+ * (counted when started, cached by request), `timeoutMs` each. After a rate limit no further call
131
+ * is made, since each would only fail the same way.
132
+ */
133
+ export function ghRemote(gh: string, cwd: string, opts: { budget?: number; timeoutMs?: number } = {}): Remote {
134
+ const budget = opts.budget ?? REMOTE_BUDGET;
135
+ const timeoutMs = opts.timeoutMs ?? REMOTE_TIMEOUT_MS;
136
+ let calls = 0;
137
+ let limited: Failure | null = null;
138
+ const cache = new Map<string, Promise<unknown>>();
139
+
140
+ /** One bounded call, or why not. `args` are the whole `gh` argument list. */
141
+ const call = async (args: string[], what: string, maxBytes: number): Promise<string | Failure> => {
142
+ if (limited !== null) return limited;
143
+ if (calls >= budget) return { code: "gh.budget_spent", reason: `the run's budget of ${budget} gh api call${budget === 1 ? "" : "s"} was spent before ${what} was read` };
144
+ calls += 1;
145
+ const r = await runGh(gh, cwd, args, timeoutMs, maxBytes);
146
+ if (r === "timeout") return { code: "gh.timeout", reason: `gh api for ${what} did not answer within ${timeoutMs} ms and was stopped` };
147
+ if (r === "too_large") return { code: "gh.content_too_large", reason: `${what} is larger than ${MAX_CONTENT_BYTES} bytes, which footprint does not read` };
148
+ if (r.code !== 0) {
149
+ const f = classifyFailure(r.err, r.code);
150
+ const failure: Failure = f.code === "gh.rate_limited" ? f : { code: "gh.remote_failed", reason: `gh api for ${what} failed: ${f.reason}` };
151
+ if (failure.code === "gh.rate_limited") limited = failure;
152
+ return failure;
153
+ }
154
+ return r.out;
155
+ };
156
+
157
+ const once = <T>(key: string, make: () => Promise<T>): Promise<T> => {
158
+ let p = cache.get(key) as Promise<T> | undefined;
159
+ if (p === undefined) { p = make(); cache.set(key, p); }
160
+ return p;
161
+ };
162
+
163
+ return {
164
+ compare: (base, head) => {
165
+ if (!COMMIT.test(base) || !COMMIT.test(head)) return Promise.resolve({ code: "gh.compare_unpinned", reason: "the base or head is not a full commit id, so the compare is not pinned to exact commits" });
166
+ return once(`compare\0${base}\0${head}`, async () => {
167
+ const out = await call(["api", `repos/{owner}/{repo}/compare/${base}...${head}`], `the compare ${base.slice(0, 12)}...${head.slice(0, 12)}`, 64 * MAX_CONTENT_BYTES);
168
+ return typeof out === "string" ? parseCompare(out) : out;
169
+ });
170
+ },
171
+ content: (sha, path) => {
172
+ if (!COMMIT.test(sha)) return Promise.resolve({ code: "gh.compare_unpinned", reason: "the revision is not a full commit id, so its content is not pinned" });
173
+ return once(`content\0${sha}\0${path}`, () => call(["api", "-H", "Accept: application/vnd.github.raw", contentsPath(sha, path)], `${path} at ${sha.slice(0, 12)}`, MAX_CONTENT_BYTES));
174
+ },
175
+ stats: () => ({ calls, budget, timeoutMs }),
176
+ };
177
+ }