traceyard 0.0.0-stage → 0.1.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.
@@ -0,0 +1,249 @@
1
+ import { execFile } from "node:child_process";
2
+ import { realpath } from "node:fs/promises";
3
+ import { posix } from "node:path";
4
+ import { promisify } from "node:util";
5
+
6
+ const run = promisify(execFile);
7
+
8
+ export async function git(cwd, args, { timeoutMs = 15000 } = {}) {
9
+ const { stdout } = await run("git", args, {
10
+ cwd,
11
+ timeout: timeoutMs,
12
+ maxBuffer: 8 * 1024 * 1024,
13
+ });
14
+ return stdout.trim();
15
+ }
16
+
17
+ /** The top of the git repository that contains `cwd`. */
18
+ export async function repositoryRoot(cwd) {
19
+ try {
20
+ // Real paths, so Windows short names (RUNNER~1) and symlinked temp dirs
21
+ // compare equal to the long path git reports.
22
+ return await realpath(await git(cwd, ["rev-parse", "--show-toplevel"]));
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ /** Resolve a ref to its full SHA, or null if this clone does not have it. */
29
+ export async function resolveCommit(repo, ref) {
30
+ try {
31
+ return await git(repo, ["rev-parse", "--verify", "--quiet", ref + "^{commit}"]);
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ /** Files that differ between two commits, as repository-relative paths. */
38
+ export async function changedFiles(repo, from, to) {
39
+ // -z keeps names as they are. Without it Git quotes and escapes non-ASCII
40
+ // names, and a quoted path matches none of the test-input rules.
41
+ const out = await git(repo, ["diff", "--name-only", "--no-renames", "-z", from, to], {
42
+ timeoutMs: 60000,
43
+ });
44
+ return out.split("\0").filter(Boolean);
45
+ }
46
+
47
+ /** True when tracked files have uncommitted changes. Untracked files are ignored. */
48
+ export async function hasUncommittedChanges(repo) {
49
+ const out = await git(repo, ["status", "--porcelain", "--untracked-files=no"]);
50
+ return out.length > 0;
51
+ }
52
+
53
+ /** "owner/name" for the origin remote when it points at GitHub, otherwise null. */
54
+ export async function githubRepository(repo) {
55
+ let url;
56
+ try {
57
+ url = await git(repo, ["remote", "get-url", "origin"]);
58
+ } catch {
59
+ return null;
60
+ }
61
+ const match = url.match(/github\.com[:/]([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/i);
62
+ return match?.[1] ?? null;
63
+ }
64
+
65
+ /** Full SHA of HEAD, or null in a repository with no commits. */
66
+ export async function headCommit(repo) {
67
+ return resolveCommit(repo, "HEAD");
68
+ }
69
+
70
+ /**
71
+ * A file's contents at a commit (or in the working tree when commit is null).
72
+ * Null when the file doesn't exist there or isn't inside the repository.
73
+ */
74
+ export async function showFile(repo, commit, path) {
75
+ if (!path || path.startsWith("/") || path.split("/").includes("..")) return null;
76
+ try {
77
+ if (commit) return await git(repo, ["show", `${commit}:${path}`], { timeoutMs: 15000 });
78
+ const { readFile } = await import("node:fs/promises");
79
+ const { join } = await import("node:path");
80
+ return await readFile(join(repo, path), "utf8");
81
+ } catch {
82
+ return null;
83
+ }
84
+ }
85
+
86
+ const MAX_UNTRACKED = 2000;
87
+
88
+ const gitBuffer = (repo, args) =>
89
+ run("git", args, {
90
+ cwd: repo,
91
+ timeout: 60000,
92
+ maxBuffer: 256 * 1024 * 1024,
93
+ encoding: "buffer",
94
+ }).then(({ stdout }) => stdout);
95
+
96
+ /**
97
+ * Snapshot of the working tree a `check` runs against: HEAD, the diff of
98
+ * tracked files against HEAD (staged and unstaged), and the blob IDs of
99
+ * untracked files that aren't ignored. The same tree always gives the same
100
+ * fingerprint, and any edit to a tracked or untracked file changes it.
101
+ * `complete` is false when some untracked files could not be hashed.
102
+ */
103
+ export async function worktreeSnapshot(repo) {
104
+ const { createHash } = await import("node:crypto");
105
+ const head = (await resolveCommit(repo, "HEAD")) ?? "unborn";
106
+ const diff = await gitBuffer(repo, [
107
+ "diff",
108
+ "HEAD",
109
+ "--binary",
110
+ "--no-ext-diff",
111
+ "--no-color",
112
+ ]).catch(
113
+ // No HEAD yet: every tracked file is staged, so diff the index instead.
114
+ () => gitBuffer(repo, ["diff", "--cached", "--binary", "--no-ext-diff", "--no-color"]),
115
+ );
116
+ const tracked = createHash("sha256")
117
+ .update("head\0" + head + "\0diff\0")
118
+ .update(diff)
119
+ .digest("hex");
120
+ const listed = (
121
+ await gitBuffer(repo, ["ls-files", "--others", "--exclude-standard", "-z"])
122
+ ).toString("utf8");
123
+ const names = listed.split("\0").filter(Boolean).sort();
124
+ // hash-object reads one path per line, so a name with a newline can't be hashed.
125
+ const hashed = names.filter((path) => !path.includes("\n")).slice(0, MAX_UNTRACKED);
126
+ const untracked = new Map();
127
+ if (hashed.length) {
128
+ const ids = await new Promise((done, fail) => {
129
+ const child = execFile(
130
+ "git",
131
+ ["hash-object", "--no-filters", "--stdin-paths"],
132
+ { cwd: repo, timeout: 60000, maxBuffer: 8 * 1024 * 1024 },
133
+ (error, stdout) => (error ? fail(error) : done(stdout.trim().split("\n"))),
134
+ );
135
+ child.stdin.end(hashed.join("\n") + "\n");
136
+ });
137
+ hashed.forEach((path, index) => untracked.set(path, ids[index] ?? ""));
138
+ }
139
+ const hash = createHash("sha256").update("tracked\0" + tracked + "\0untracked\0" + names.length);
140
+ for (const [path, id] of untracked) hash.update("\0" + path + "\0" + id);
141
+ return {
142
+ fingerprint: hash.digest("hex"),
143
+ tracked,
144
+ untracked,
145
+ complete: hashed.length === names.length,
146
+ };
147
+ }
148
+
149
+ /**
150
+ * True when `after` no longer matches the tree `before` described: a tracked
151
+ * file changed, or an untracked file that existed before was edited or
152
+ * removed. New untracked files are ignored, because test runners create
153
+ * caches (__pycache__, coverage) in repositories that don't ignore them.
154
+ */
155
+ export const worktreeChanged = (before, after) =>
156
+ before.tracked !== after.tracked ||
157
+ [...before.untracked].some(([path, id]) => after.untracked.get(path) !== id);
158
+
159
+ /** Every file tracked at a commit, as repository-relative paths. */
160
+ export async function filesAtCommit(repo, commit) {
161
+ const out = await gitBuffer(repo, ["ls-tree", "-r", "-z", "--name-only", "--full-tree", commit]);
162
+ return out.toString("utf8").split("\0").filter(Boolean);
163
+ }
164
+
165
+ /**
166
+ * True when `ancestor` is on `commit`'s own line of history (first parents
167
+ * only). A commit that arrived through a merge doesn't count: a merge can
168
+ * bring in a side commit without taking any of its files.
169
+ */
170
+ export async function onFirstParentLine(repo, ancestor, commit) {
171
+ try {
172
+ const line = await gitBuffer(repo, ["rev-list", "--first-parent", commit, "--"]);
173
+ return line.toString("utf8").split("\n").includes(ancestor);
174
+ } catch {
175
+ return false;
176
+ }
177
+ }
178
+
179
+ /** Symlinks tracked at a commit, as `path -> target text`. */
180
+ async function symlinksAtCommit(repo, commit) {
181
+ const out = await gitBuffer(repo, ["ls-tree", "-r", "-z", "--full-tree", commit]);
182
+ const links = new Map();
183
+ for (const entry of out.toString("utf8").split("\0")) {
184
+ const match = entry.match(/^120000 blob ([0-9a-f]+)\t([\s\S]+)$/);
185
+ if (match)
186
+ links.set(match[2], (await gitBuffer(repo, ["cat-file", "blob", match[1]])).toString("utf8"));
187
+ }
188
+ return links;
189
+ }
190
+
191
+ /**
192
+ * Every repository path read when opening `link`: each link passed through,
193
+ * including linked folders partway along a target, and the final path. Targets
194
+ * outside the repository end the walk.
195
+ */
196
+ function pathsBehind(link, links) {
197
+ const seen = [];
198
+ let done = link.split("/").slice(0, -1);
199
+ let rest = [link.split("/").at(-1)];
200
+ // The limit stops link cycles.
201
+ for (let hops = 0; rest.length;) {
202
+ const part = rest.shift();
203
+ if (part === "" || part === ".") continue;
204
+ if (part === "..") {
205
+ if (!done.length) return seen;
206
+ done.pop();
207
+ continue;
208
+ }
209
+ const path = [...done, part].join("/");
210
+ const target = links.get(path);
211
+ if (target === undefined) {
212
+ done.push(part);
213
+ continue;
214
+ }
215
+ seen.push(path);
216
+ if (posix.isAbsolute(target) || ++hops > 40) return seen;
217
+ rest = [...target.split("/"), ...rest];
218
+ }
219
+ seen.push(done.join("/"));
220
+ return seen;
221
+ }
222
+
223
+ /**
224
+ * Symlinks that lead to something changed between two commits although the link
225
+ * itself did not. A config or test file that is a link can be rewritten this
226
+ * way without its own name appearing in the diff.
227
+ */
228
+ export async function changedThroughLinks(repo, from, to, changed) {
229
+ const maps = [await symlinksAtCommit(repo, from), await symlinksAtCommit(repo, to)];
230
+ const touched = new Set(changed);
231
+ const reached = (link, path) =>
232
+ path !== link &&
233
+ (path === ""
234
+ ? touched.size > 0
235
+ : [...touched].some((f) => f === path || f.startsWith(path + "/")));
236
+ const found = [];
237
+ // Repeat so a linked file inside a linked folder is followed to its end.
238
+ for (let added = true; added;) {
239
+ added = false;
240
+ for (const links of maps)
241
+ for (const link of links.keys())
242
+ if (!touched.has(link) && pathsBehind(link, links).some((path) => reached(link, path))) {
243
+ touched.add(link);
244
+ found.push(link);
245
+ added = true;
246
+ }
247
+ }
248
+ return found;
249
+ }
@@ -0,0 +1,139 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import {
4
+ failingTestsFromLog,
5
+ parseActionsUrl,
6
+ readCheckoutRevision,
7
+ unreadableFailuresInLog,
8
+ } from "../../core/src/ci-link.mjs";
9
+ import { UsageError, BlockedError } from "./errors.mjs";
10
+
11
+ const run = promisify(execFile);
12
+
13
+ /**
14
+ * How to reach the GitHub API: a token from GITHUB_TOKEN or GH_TOKEN, else an
15
+ * authenticated `gh` CLI, else anonymous requests (public repositories only).
16
+ */
17
+ export async function githubAuth(env = process.env) {
18
+ const token = env.GITHUB_TOKEN || env.GH_TOKEN;
19
+ if (token) return { kind: "token", token };
20
+ try {
21
+ await run("gh", ["auth", "status", "--hostname", "github.com"], { timeout: 5000 });
22
+ return { kind: "gh" };
23
+ } catch {
24
+ return { kind: "anonymous" };
25
+ }
26
+ }
27
+
28
+ const refused = (auth) =>
29
+ new BlockedError(
30
+ auth.kind === "anonymous"
31
+ ? "GitHub needs a token to read this Actions run. Set GITHUB_TOKEN or sign in with `gh auth login`."
32
+ : "GitHub refused access to this Actions run. Check that your token can read the repository.",
33
+ );
34
+
35
+ function client(auth, fetcher) {
36
+ if (auth.kind === "gh")
37
+ return {
38
+ async request(path, kind) {
39
+ const call = (extra = []) =>
40
+ run("gh", ["api", ...extra, path], { timeout: 60000, maxBuffer: 64 * 1024 * 1024 });
41
+ try {
42
+ let result;
43
+ try {
44
+ result = await call();
45
+ } catch (error) {
46
+ // Newer gh refuses to print job logs (which contain ANSI colors) without this flag.
47
+ if (!/escape sequences/.test(String(error.stderr ?? ""))) throw error;
48
+ result = await call(["--allow-escape-sequences"]);
49
+ }
50
+ return kind === "text" ? result.stdout : JSON.parse(result.stdout);
51
+ } catch (error) {
52
+ if (/HTTP 40[134]/.test(String(error.stderr ?? error.message))) throw refused(auth);
53
+ throw new BlockedError(
54
+ "The gh CLI could not read the Actions run: " +
55
+ String(error.stderr ?? error.message)
56
+ .trim()
57
+ .slice(0, 300),
58
+ );
59
+ }
60
+ },
61
+ };
62
+ const headers = {
63
+ accept: "application/vnd.github+json",
64
+ "user-agent": "traceyard-cli",
65
+ "x-github-api-version": "2022-11-28",
66
+ ...(auth.token ? { authorization: "Bearer " + auth.token } : {}),
67
+ };
68
+ return {
69
+ async request(path, kind) {
70
+ const response = await fetcher("https://api.github.com" + path, { headers });
71
+ if ([401, 403, 404].includes(response.status)) throw refused(auth);
72
+ if (!response.ok)
73
+ throw new BlockedError(`GitHub returned ${response.status} for the Actions run.`);
74
+ return kind === "text" ? response.text() : response.json();
75
+ },
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Turn a GitHub Actions link into the exact commit the job tested and the test
81
+ * files that failed in it. `repository` is the local clone's GitHub "owner/name".
82
+ */
83
+ export async function resolveActionsLink(
84
+ url,
85
+ repository,
86
+ { auth = { kind: "anonymous" }, fetcher = globalThis.fetch } = {},
87
+ ) {
88
+ const link = parseActionsUrl(url);
89
+ if (!link)
90
+ throw new UsageError(
91
+ "Pass a GitHub Actions run or job link, like https://github.com/owner/repo/actions/runs/123/job/456.",
92
+ );
93
+ if (repository && link.repository.toLowerCase() !== repository.toLowerCase())
94
+ throw new UsageError(
95
+ `This link is for ${link.repository}, but this clone's origin is ${repository}.`,
96
+ );
97
+ const api = client(auth, fetcher);
98
+ const gh = {
99
+ json: (path) => api.request(path, "json"),
100
+ text: (path) => api.request(path, "text"),
101
+ };
102
+ const base = `/repos/${link.repository}/actions`;
103
+ let jobId = link.jobId;
104
+ if (!jobId) {
105
+ const runInfo = await gh.json(
106
+ `${base}/runs/${link.runId}${link.attempt ? `/attempts/${link.attempt}` : ""}`,
107
+ );
108
+ const attempt = link.attempt ?? String(runInfo.run_attempt);
109
+ const { jobs } = await gh.json(
110
+ `${base}/runs/${link.runId}/attempts/${attempt}/jobs?per_page=100`,
111
+ );
112
+ const failed = jobs.filter((job) => ["failure", "timed_out"].includes(job.conclusion ?? ""));
113
+ if (failed.length !== 1)
114
+ throw new UsageError(
115
+ failed.length
116
+ ? "More than one job failed in this run. Open the job that ran the test and pass its link."
117
+ : "No job failed in this run. Pass the link of the job that ran the failing test.",
118
+ );
119
+ jobId = String(failed[0].id);
120
+ }
121
+ const job = await gh.json(`${base}/jobs/${jobId}`);
122
+ if (String(job.run_id) !== link.runId)
123
+ throw new UsageError("This job does not belong to the linked Actions run.");
124
+ if (job.status !== "completed")
125
+ throw new BlockedError("This CI job has not finished yet. Try again when it completes.");
126
+ const log = await gh.text(`${base}/jobs/${jobId}/logs`);
127
+ const checkout = readCheckoutRevision(log, link.repository);
128
+ if (!checkout)
129
+ throw new BlockedError(
130
+ "Traceyard could not find a single checkout in this job's log. Pass the tested commit with --at instead.",
131
+ );
132
+ return {
133
+ commit: checkout.commit,
134
+ mergeCommit: checkout.merge,
135
+ failingTests: failingTestsFromLog(log),
136
+ unreadableFailures: unreadableFailuresInLog(log),
137
+ jobUrl: `https://github.com/${link.repository}/actions/runs/${link.runId}/job/${jobId}`,
138
+ };
139
+ }