@a2f0/agent-tool 0.1.73 → 0.1.74

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,311 @@
1
+ /** Which store namespace a repository uses, and the owner file that reserves it. */
2
+ import { spawnSync } from "node:child_process";
3
+ import { linkSync, mkdirSync, readdirSync, readFileSync, readlinkSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { gitValue } from "./git";
6
+ import { readRecord } from "./record";
7
+ import { LINK, lexists, type Target, writeAtomic } from "./store";
8
+
9
+ /** owner/name from a GitHub remote URL in the forms Git accepts; any other host is not GitHub. */
10
+ export function githubRepo(url: string): string | undefined {
11
+ const match =
12
+ /^(?:git@github\.com:|(?:ssh:\/\/)?git@github\.com\/|(?:https?|git|ssh):\/\/(?:[^@/\s]+@)?github\.com(?::\d+)?\/)([A-Za-z0-9][A-Za-z0-9-]*)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(
13
+ url.trim(),
14
+ );
15
+ return match ? `${match[1]}/${match[2]}` : undefined;
16
+ }
17
+
18
+ /**
19
+ * owner/name as GitHub reports it now, following renames and fixing case. Asks
20
+ * about origin's repository by name, since bare `gh repo view` prefers an
21
+ * `upstream` remote and would name a fork's parent. MATRIX_ARTIFACTS_NO_GH
22
+ * skips the network (offline use and tests).
23
+ */
24
+ function canonicalRepo(root: string, parsed?: string): Resolved | undefined {
25
+ if (process.env.MATRIX_ARTIFACTS_NO_GH) return undefined;
26
+ // Without a github.com origin there is no name to ask about, and bare `gh repo view` could answer for a fork's parent.
27
+ if (!parsed) return undefined;
28
+ // Bounded: a stalled network falls back to origin's URL rather than hanging `status`.
29
+ // Host-qualified, so a GH_HOST pointing elsewhere never answers for a github.com origin.
30
+ const result = spawnSync("gh", ["repo", "view", `github.com/${parsed}`, "--json", "nameWithOwner,id", "--jq", '.nameWithOwner + " " + .id'], {
31
+ cwd: root,
32
+ encoding: "utf8",
33
+ stdio: ["ignore", "pipe", "ignore"],
34
+ timeout: 20_000,
35
+ });
36
+ const [repo, id] = result.status === 0 ? result.stdout.trim().split(/\s+/) : [];
37
+ return repo && /^[^/\s]+\/[^/\s]+$/.test(repo) ? { repo, ...(id ? { id } : {}) } : undefined;
38
+ }
39
+
40
+ /** GitHub's current name for a repository and its node id, which survives renames and transfers. */
41
+ export interface Resolved {
42
+ readonly repo: string;
43
+ readonly id?: string;
44
+ }
45
+
46
+ /** origin's GitHub name, GitHub's current name for it, and its node id, each when known. */
47
+ function identity(root: string, resolve: (root: string, parsed?: string) => Resolved | string | undefined) {
48
+ const remote = gitValue(root, "remote", "get-url", "origin");
49
+ const parsed = remote ? githubRepo(remote) : undefined;
50
+ const resolved = resolve(root, parsed);
51
+ if (typeof resolved === "string") return { parsed, canonical: resolved, id: undefined };
52
+ return { parsed, canonical: resolved?.repo, id: resolved?.id };
53
+ }
54
+
55
+ /**
56
+ * A repository's store namespace: its GitHub name, like matrix-secrets'. GitHub
57
+ * names it when reachable (a clone's remote can carry a pre-rename name or other
58
+ * casing); otherwise origin's URL does. A repository with neither needs --project.
59
+ */
60
+ export function targetFor(root: string, project?: string, resolve: (root: string, parsed?: string) => Resolved | string | undefined = canonicalRepo): Target {
61
+ const { parsed, canonical, id } = identity(root, resolve);
62
+ const repo = canonical ?? parsed;
63
+ const name = namespaceName(root, repo, project);
64
+ return {
65
+ name: path.basename(root),
66
+ root,
67
+ project: name,
68
+ ...(repo ? { repo } : {}),
69
+ verified: canonical !== undefined,
70
+ ...(canonical && parsed && parsed !== canonical ? { alias: parsed } : {}),
71
+ ...(project ? { explicit: true } : {}),
72
+ ...(id ? { id } : {}),
73
+ };
74
+ }
75
+
76
+ /** --project, else the repository's name; refuses a repository with neither, and names that are not one plain directory. */
77
+ function namespaceName(root: string, repo: string | undefined, project: string | undefined): string {
78
+ if (!repo && !project) throw new Error(`${root} has no GitHub origin; pass --project to name its namespace`);
79
+ const name = project ?? repo!.split("/")[1]!;
80
+ if (!/^[A-Za-z0-9._-]+$/.test(name) || name === "." || name === "..") throw new Error(`'${name}' is not a usable project name`);
81
+ return name;
82
+ }
83
+
84
+ /** The repository a namespace belongs to, reserved by the first clone that links or captures into it. */
85
+ export const OWNER = "repository.json";
86
+
87
+ /** A namespace's owner file: its repository and the remote names GitHub confirmed for it. */
88
+ interface Owner {
89
+ repo: string;
90
+ aliases: string[];
91
+ id?: string | undefined;
92
+ explicit?: boolean | undefined;
93
+ }
94
+
95
+ function readOwner(file: string): Owner | undefined {
96
+ try {
97
+ const value = JSON.parse(readFileSync(file, "utf8")) as { repo?: unknown; aliases?: unknown; id?: unknown; explicit?: unknown };
98
+ if (typeof value.repo !== "string" || value.repo === "") return undefined;
99
+ const aliases = Array.isArray(value.aliases) ? value.aliases.filter((alias): alias is string => typeof alias === "string") : [];
100
+ return { repo: value.repo, aliases, ...(typeof value.id === "string" ? { id: value.id } : {}), ...(value.explicit === true ? { explicit: true } : {}) };
101
+ } catch {
102
+ return undefined;
103
+ }
104
+ }
105
+
106
+ /** Adds a GitHub-confirmed remote name to the owner file, atomically, so offline clones still find the namespace. */
107
+ function writeOwner(file: string, owner: Owner): void {
108
+ const body = {
109
+ repo: owner.repo,
110
+ ...(owner.aliases.length ? { aliases: owner.aliases } : {}),
111
+ ...(owner.id ? { id: owner.id } : {}),
112
+ ...(owner.explicit ? { explicit: true } : {}),
113
+ };
114
+ writeAtomic(file, `${JSON.stringify(body)}\n`);
115
+ }
116
+
117
+ /**
118
+ * Read, change, and write the owner file under its own short lock, so two
119
+ * clones recording different aliases at once both keep theirs. `change`
120
+ * returns the new owner, or undefined to leave the file alone.
121
+ */
122
+ export function updateOwner(file: string, change: (owner: Owner | undefined) => Owner | undefined, waitMs = 10_000): void {
123
+ const lock = `${file}.lock`;
124
+ const mine = `${lock}.${process.pid}.${process.hrtime.bigint()}`;
125
+ writeFileSync(mine, `${process.pid}\n`, { flag: "wx" });
126
+ try {
127
+ linkWhenFree(mine, lock, waitMs);
128
+ try {
129
+ const next = change(readOwner(file));
130
+ if (next) writeOwner(file, next);
131
+ } finally {
132
+ unlinkSync(lock);
133
+ }
134
+ } finally {
135
+ unlinkSync(mine);
136
+ }
137
+ }
138
+
139
+ /** Hard-links `mine` to `lock` once no other process holds it, polling for up to `waitMs`. */
140
+ function linkWhenFree(mine: string, lock: string, waitMs: number): void {
141
+ for (const deadline = Date.now() + waitMs; ; ) {
142
+ try {
143
+ linkSync(mine, lock);
144
+ return;
145
+ } catch (error) {
146
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
147
+ // Never broken automatically: two recovering processes could each remove the other's fresh lock.
148
+ if (Date.now() > deadline)
149
+ throw new Error(`${lock} is held; an update takes milliseconds, so if no link or capture is running it was left by a killed process: remove it`);
150
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
151
+ }
152
+ }
153
+ }
154
+
155
+ /** Reserve the namespace for this repository, or explain whose it is. */
156
+ export function claimNamespace(target: Target, artifacts: string, apply: boolean): string | undefined {
157
+ const file = path.join(artifacts, target.project, OWNER);
158
+ const damaged = () => lexists(file) && readOwner(file) === undefined;
159
+ if (!apply) return decideClaim(target, artifacts, readOwner(file), damaged()).error;
160
+ // Decide and write under the owner lock, so a concurrent claim sees this one's result.
161
+ mkdirSync(path.dirname(file), { recursive: true });
162
+ let error: string | undefined;
163
+ updateOwner(file, owner => {
164
+ const result = decideClaim(target, artifacts, owner, damaged());
165
+ error = result.error;
166
+ return result.error ? undefined : result.next;
167
+ });
168
+ return error;
169
+ }
170
+
171
+ /** Why a claim is refused, or the owner record to write; neither when the namespace is this repository's as recorded. */
172
+ interface Claim {
173
+ readonly error?: string;
174
+ readonly next?: Owner;
175
+ }
176
+
177
+ const lower = (name: string) => name.toLowerCase();
178
+
179
+ function foreignClaim(holder: string, identity: string): Claim {
180
+ return { error: `the store holds captures of ${holder}, not ${identity}; pass --project to use another namespace` };
181
+ }
182
+
183
+ function decideClaim(target: Target, artifacts: string, owner: Owner | undefined, damaged: boolean): Claim {
184
+ const identity = target.repo ?? `local:${target.project}`;
185
+ if (damaged) return foreignClaim("(unreadable repository.json)", identity);
186
+ if (!owner) return firstClaim(target, artifacts, identity);
187
+ return ownedClaim(target, owner, identity);
188
+ }
189
+
190
+ /** A namespace with no owner file yet: refuse it only when its capture record names another repository. */
191
+ function firstClaim(target: Target, artifacts: string, identity: string): Claim {
192
+ const recorded = readRecord(path.join(artifacts, target.project, "screenshots"))?.repo;
193
+ const renamed = target.alias !== undefined && recorded !== undefined && lower(recorded) === lower(target.alias);
194
+ if (recorded !== undefined && lower(recorded) !== lower(identity) && !renamed) return foreignClaim(recorded, identity);
195
+ return {
196
+ next: {
197
+ repo: identity,
198
+ aliases: target.verified && target.alias ? [target.alias] : [],
199
+ id: target.verified ? target.id : undefined,
200
+ explicit: target.explicit,
201
+ },
202
+ };
203
+ }
204
+
205
+ /** A namespace with an owner: this repository's under its name, a confirmed earlier name, or its GitHub id. */
206
+ function ownedClaim(target: Target, owner: Owner, identity: string): Claim {
207
+ // GitHub's node id survives renames and transfers; a different id is a different repository, whatever its name.
208
+ if (target.verified && target.id !== undefined && owner.id !== undefined && owner.id !== target.id) {
209
+ return foreignClaim(`${owner.repo} (another GitHub repository, ${owner.id})`, identity);
210
+ }
211
+ const names = [owner.repo, ...owner.aliases].map(lower);
212
+ const sameName = lower(owner.repo) === lower(identity);
213
+ // The same repository after renames or transfers: GitHub confirmed origin's old name, which the namespace
214
+ // knows, or GitHub's id matches the recorded one.
215
+ const priorName = target.alias !== undefined && names.includes(lower(target.alias));
216
+ const sameId = target.verified === true && target.id !== undefined && owner.id === target.id;
217
+ if (!sameName && !(target.verified && (priorName || sameId))) return foreignClaim(owner.repo, identity);
218
+ if (!target.verified) return {};
219
+ return confirmedOwner(target, owner, identity);
220
+ }
221
+
222
+ /**
223
+ * The owner record once GitHub confirmed this repository as `identity`: that
224
+ * name, every other name it was known by as an alias, and its id; nothing to
225
+ * write when the record already says so.
226
+ */
227
+ function confirmedOwner(target: Target, owner: Owner, identity: string): Claim {
228
+ const aliases = [...owner.aliases, owner.repo, ...(target.alias ? [target.alias] : [])].filter(
229
+ (name, index, all) => lower(name) !== lower(identity) && all.findIndex(other => lower(other) === lower(name)) === index,
230
+ );
231
+ const next = { ...owner, repo: identity, aliases, id: owner.id ?? target.id };
232
+ const changed = JSON.stringify(next) !== JSON.stringify({ ...owner, id: owner.id });
233
+ return changed ? { next } : {};
234
+ }
235
+
236
+ /**
237
+ * The target with its project spelled like an existing namespace that differs
238
+ * only in case, so a repository whose GitHub name gains capitals keeps its store
239
+ * on case-sensitive filesystems too.
240
+ */
241
+ export function existingCase(target: Target, artifacts: string): Target {
242
+ if (target.explicit) return target;
243
+ let entries: string[];
244
+ try {
245
+ entries = readdirSync(artifacts);
246
+ } catch {
247
+ return target;
248
+ }
249
+ if (entries.includes(target.project)) return target;
250
+ const variant = entries.find(entry => entry.toLowerCase() === target.project.toLowerCase());
251
+ return variant ? { ...target, project: variant } : target;
252
+ }
253
+
254
+ /**
255
+ * The namespace that already serves this repository: one whose owner file names
256
+ * its GitHub repository, or lists origin's name as an alias GitHub confirmed
257
+ * earlier. Renames and transfers therefore keep one store whether a clone's
258
+ * remote uses the old or the new name, online or offline. --project is never
259
+ * overridden.
260
+ */
261
+ export function knownNamespace(target: Target, artifacts: string): Target {
262
+ if (!target.repo) return target;
263
+ if (target.explicit) {
264
+ // The chosen namespace stays; offline, a confirmed old name of its owner still counts as that owner.
265
+ const owner = readOwner(path.join(artifacts, target.project, OWNER));
266
+ const confirmed = !target.verified && owner?.aliases.some(alias => alias.toLowerCase() === target.repo!.toLowerCase());
267
+ return confirmed ? { ...target, repo: owner!.repo } : target;
268
+ }
269
+ let entries: string[];
270
+ try {
271
+ entries = readdirSync(artifacts);
272
+ } catch {
273
+ return target;
274
+ }
275
+ const names = [target.repo, target.alias].filter((name): name is string => name !== undefined).map(name => name.toLowerCase());
276
+ const matches = entries
277
+ .filter(entry => !entry.startsWith("."))
278
+ .flatMap(entry => {
279
+ const owner = readOwner(path.join(artifacts, entry, OWNER));
280
+ if (!owner) return [];
281
+ const canonical = owner.repo.toLowerCase() === target.repo!.toLowerCase();
282
+ // Offline, origin's name counts only as an alias GitHub confirmed for that namespace.
283
+ const confirmed = owner.aliases.some(alias => names.includes(alias.toLowerCase()));
284
+ const verifiedAlias = target.verified && target.alias !== undefined && owner.repo.toLowerCase() === target.alias.toLowerCase();
285
+ return canonical || confirmed || verifiedAlias ? [{ entry, owner, canonical }] : [];
286
+ });
287
+ // Prefer the namespace this clone already links to, then the one its current name owns (its own
288
+ // directory first), then this project's directory, so an extra --project namespace never takes over.
289
+ const linked = linkedNamespace(target, artifacts);
290
+ // Namespaces made with --project are extras: used implicitly only by a clone already linked to one.
291
+ const primary = matches.filter(match => !match.owner.explicit);
292
+ const chosen =
293
+ matches.find(match => match.entry === linked) ??
294
+ primary.find(match => match.canonical && match.entry === target.project) ??
295
+ primary.find(match => match.entry === target.project) ??
296
+ primary.find(match => match.canonical) ??
297
+ primary[0];
298
+ if (!chosen) return target;
299
+ return { ...target, project: chosen.entry, repo: target.verified ? target.repo : chosen.owner.repo };
300
+ }
301
+
302
+ /** The namespace this clone's link points into, when it links to a namespace's screenshots in this store. */
303
+ export function linkedNamespace(target: Target, artifacts: string): string | undefined {
304
+ try {
305
+ const relative = path.relative(artifacts, path.resolve(target.root, readlinkSync(path.join(target.root, LINK)))).split(path.sep);
306
+ if (relative.length === 2 && relative[1] === "screenshots") return relative[0];
307
+ } catch {
308
+ /* not linked */
309
+ }
310
+ return undefined;
311
+ }
@@ -0,0 +1,157 @@
1
+ /** A capture's provenance record, `capture.json` in the shared directory. */
2
+ import { mkdirSync, readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { git, gitValue } from "./git";
5
+ import { writeAtomic } from "./store";
6
+
7
+ /** Provenance of the newest capture, inside the shared directory. */
8
+ export const RECORD = "capture.json";
9
+
10
+ /** How a capture that ran to the end was judged. */
11
+ export type FinishedStatus = "complete" | "failed" | "incomplete";
12
+
13
+ /** The fields a capture records when it starts; they do not change when it finishes. */
14
+ export interface RecordFields {
15
+ readonly schemaVersion: 1;
16
+ readonly project: string;
17
+ /** owner/name from origin, when it is a GitHub remote. */
18
+ readonly repo?: string;
19
+ readonly commit: string;
20
+ readonly branch: string | null;
21
+ /** The working tree had changes the commit does not hold. */
22
+ readonly dirty: boolean;
23
+ /** HEAD was reachable from origin's default branch; null when that is unknown. */
24
+ readonly merged: boolean | null;
25
+ /** Arguments passed to the capture; non-empty usually means a partial capture. */
26
+ readonly args: string[];
27
+ /**
28
+ * For a partial capture, the capture whose other images it kept. A partial
29
+ * capture over a dirty or unfinished one stays dirty or `incomplete`, so
30
+ * only a full, clean capture clears them.
31
+ */
32
+ readonly over?: { readonly commit: string; readonly status: CaptureRecord["status"]; readonly dirty: boolean };
33
+ readonly checkout: string;
34
+ readonly host: string;
35
+ readonly startedAt: string;
36
+ }
37
+
38
+ /** A capture still running, or one whose process was killed before it could finish. */
39
+ export interface RunningRecord extends RecordFields {
40
+ readonly status: "running";
41
+ readonly finishedAt?: never;
42
+ readonly exitCode?: never;
43
+ }
44
+
45
+ interface FinishedRecord extends RecordFields {
46
+ readonly status: FinishedStatus;
47
+ readonly finishedAt: string;
48
+ readonly exitCode: number | null;
49
+ }
50
+
51
+ /** The record moves `start` -> running -> `finish` -> complete, failed or incomplete. */
52
+ export type CaptureRecord = RunningRecord | FinishedRecord;
53
+
54
+ /**
55
+ * A record as read back from `capture.json`. Older versions wrote finished
56
+ * records without `finishedAt` or `exitCode`, and readers still accept them,
57
+ * so nothing read from disk may assume the finished fields exist.
58
+ */
59
+ export interface StoredRecord extends RecordFields {
60
+ readonly status: CaptureRecord["status"];
61
+ readonly finishedAt?: string;
62
+ readonly exitCode?: number | null;
63
+ }
64
+
65
+ type StartEvent = { readonly type: "start"; readonly fields: RecordFields };
66
+
67
+ export type RecordEvent =
68
+ | StartEvent
69
+ | { readonly type: "finish"; readonly status: FinishedStatus; readonly finishedAt: string; readonly exitCode: number | null };
70
+
71
+ /**
72
+ * The record's only transition. `start` replaces any record, since the lock
73
+ * settled the one before; `finish` settles only a running record and is
74
+ * ignored otherwise.
75
+ */
76
+ export function transition(record: StoredRecord | undefined, event: StartEvent): RunningRecord;
77
+ export function transition(record: CaptureRecord, event: RecordEvent): CaptureRecord;
78
+ export function transition(record: CaptureRecord | undefined, event: RecordEvent): CaptureRecord | undefined;
79
+ export function transition(record: StoredRecord | undefined, event: RecordEvent): StoredRecord | undefined {
80
+ switch (event.type) {
81
+ case "start":
82
+ return { ...event.fields, status: "running" };
83
+ case "finish": {
84
+ if (record?.status !== "running") return record;
85
+ const { status, finishedAt, exitCode } = event;
86
+ return { ...record, status, finishedAt, exitCode };
87
+ }
88
+ default:
89
+ return assertNever(event);
90
+ }
91
+ }
92
+
93
+ function assertNever(value: never): never {
94
+ throw new Error(`Unhandled record event: ${JSON.stringify(value)}`);
95
+ }
96
+
97
+ const STATUSES = new Set(["running", "complete", "failed", "incomplete"]);
98
+
99
+ /** Whether a parsed record has every field a decision reads, with the right type. */
100
+ export function validRecord(value: unknown): value is StoredRecord {
101
+ if (typeof value !== "object" || value === null) return false;
102
+ const record = value as Record<string, unknown>;
103
+ const over = record.over as Record<string, unknown> | undefined;
104
+ return (
105
+ record.schemaVersion === 1 &&
106
+ typeof record.status === "string" &&
107
+ STATUSES.has(record.status) &&
108
+ typeof record.commit === "string" &&
109
+ /^[0-9a-f]{40}([0-9a-f]{24})?$/.test(record.commit) &&
110
+ typeof record.dirty === "boolean" &&
111
+ (record.merged === null || typeof record.merged === "boolean") &&
112
+ Array.isArray(record.args) &&
113
+ record.args.every(arg => typeof arg === "string") &&
114
+ (record.repo === undefined || typeof record.repo === "string") &&
115
+ typeof record.project === "string" &&
116
+ (record.branch === null || typeof record.branch === "string") &&
117
+ typeof record.checkout === "string" &&
118
+ typeof record.host === "string" &&
119
+ typeof record.startedAt === "string" &&
120
+ (record.finishedAt === undefined || typeof record.finishedAt === "string") &&
121
+ (over === undefined ||
122
+ (typeof over === "object" &&
123
+ over !== null &&
124
+ typeof over.commit === "string" &&
125
+ typeof over.status === "string" &&
126
+ STATUSES.has(over.status) &&
127
+ typeof over.dirty === "boolean"))
128
+ );
129
+ }
130
+
131
+ /** The newest capture's record; a missing or malformed one reads as no record, which is never complete. */
132
+ export function readRecord(store: string): StoredRecord | undefined {
133
+ try {
134
+ const value: unknown = JSON.parse(readFileSync(path.join(store, RECORD), "utf8"));
135
+ return validRecord(value) ? value : undefined;
136
+ } catch {
137
+ return undefined;
138
+ }
139
+ }
140
+
141
+ /** Replace the record atomically, so a reader never sees half a file. */
142
+ export function writeRecord(store: string, record: CaptureRecord): void {
143
+ mkdirSync(store, { recursive: true });
144
+ writeAtomic(path.join(store, RECORD), `${JSON.stringify(record, null, 2)}\n`);
145
+ }
146
+
147
+ /** Where a capture's commit sits relative to a repository's HEAD. */
148
+ export function relation(root: string, commit: string): { relation: "current" | "behind" | "ahead" | "diverged" | "unknown"; commits?: number } {
149
+ const head = gitValue(root, "rev-parse", "HEAD");
150
+ if (!head) return { relation: "unknown" };
151
+ if (commit === head) return { relation: "current" };
152
+ if (git(root, "cat-file", "-e", `${commit}^{commit}`).status !== 0) return { relation: "unknown" };
153
+ const count = (range: string) => Number(gitValue(root, "rev-list", "--count", range) ?? NaN);
154
+ if (git(root, "merge-base", "--is-ancestor", commit, head).status === 0) return { relation: "behind", commits: count(`${commit}..${head}`) };
155
+ if (git(root, "merge-base", "--is-ancestor", head, commit).status === 0) return { relation: "ahead", commits: count(`${head}..${commit}`) };
156
+ return { relation: "diverged" };
157
+ }
@@ -0,0 +1,47 @@
1
+ /** The shared store's layout, and the file primitives every part of it writes with. */
2
+ import { lstatSync, renameSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ /** The link every clone carries, and the directory its capture writes. */
6
+ export const LINK = ".screenshots";
7
+
8
+ /** Held for the length of one capture, beside the shared directory. */
9
+ export const LOCK = ".capture.lock";
10
+
11
+ export interface Target {
12
+ readonly name: string;
13
+ readonly root: string;
14
+ readonly project: string;
15
+ readonly repo?: string;
16
+ /** GitHub confirmed `repo`; false when it came from origin's URL alone. */
17
+ readonly verified?: boolean;
18
+ /** origin's URL name when GitHub reported another (a rename or other casing). */
19
+ readonly alias?: string;
20
+ /** --project chose the namespace; nothing may substitute another. */
21
+ readonly explicit?: boolean;
22
+ /** GitHub's node id for `repo`, which survives renames and transfers. */
23
+ readonly id?: string;
24
+ }
25
+
26
+ export function storeDir(target: Target, artifacts: string): string {
27
+ return path.join(artifacts, target.project, "screenshots");
28
+ }
29
+
30
+ export function lexists(file: string): boolean {
31
+ try {
32
+ lstatSync(file);
33
+ return true;
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Replaces a file through a private, hidden temporary file beside it, so a
41
+ * reader never sees half a file and concurrent writers never share one.
42
+ */
43
+ export function writeAtomic(file: string, text: string, mode?: number): void {
44
+ const temporary = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${process.hrtime.bigint()}.tmp`);
45
+ writeFileSync(temporary, text, { flag: "wx", ...(mode === undefined ? {} : { mode }) });
46
+ renameSync(temporary, file);
47
+ }
@@ -0,0 +1,68 @@
1
+ /** The repositories a store command selects, and the store they share. */
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { isMatrixWorkspace, namedRoot, workspaceAt, workspaceCheckouts } from "../../system/checkouts";
5
+ import { targetFor } from "./namespace";
6
+ import { LINK, lexists, type Target } from "./store";
7
+
8
+ /** The matrix workspace a repository is, or is a checkout of. */
9
+ function workspaceOf(root: string): string | undefined {
10
+ if (isMatrixWorkspace(root)) return root;
11
+ const parent = path.dirname(root);
12
+ return path.basename(parent) === "checkouts" && isMatrixWorkspace(path.dirname(parent)) ? path.dirname(parent) : undefined;
13
+ }
14
+
15
+ /**
16
+ * MATRIX_ARTIFACTS_DIR, or matrix-artifacts beside the workspace (beside the repository outside one), like
17
+ * matrix-secrets; through symlinks (macOS's /tmp) as far as it exists, so it compares with clones' real roots.
18
+ */
19
+ export function artifactsRoot(root: string, env: NodeJS.ProcessEnv = process.env): string {
20
+ return realAsFarAsExists(path.resolve(env.MATRIX_ARTIFACTS_DIR || path.join(workspaceOf(root) ?? root, "..", "matrix-artifacts")));
21
+ }
22
+
23
+ /** A path with its longest existing prefix resolved through symlinks. */
24
+ function realAsFarAsExists(location: string): string {
25
+ try {
26
+ return realpathSync(location);
27
+ } catch {
28
+ const parent = path.dirname(location);
29
+ return parent === location ? location : path.join(realAsFarAsExists(parent), path.basename(location));
30
+ }
31
+ }
32
+
33
+ export function packageScripts(root: string): Record<string, unknown> {
34
+ try {
35
+ const scripts = (JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")) as { scripts?: unknown }).scripts;
36
+ return typeof scripts === "object" && scripts !== null ? (scripts as Record<string, unknown>) : {};
37
+ } catch {
38
+ return {};
39
+ }
40
+ }
41
+
42
+ /** Whether a repository captures screenshots: a `screenshots` script, or a capture left in .screenshots. */
43
+ export function captures(root: string): boolean {
44
+ return typeof packageScripts(root).screenshots === "string" || lexists(path.join(root, LINK));
45
+ }
46
+
47
+ /** Repositories to act on: named checkouts or paths, else every checkout that captures, else the current repository. */
48
+ export function resolveTargets(cwd: string, names: string[], project?: string): { workspace?: string; targets: Target[] } {
49
+ const { here, workspace } = workspaceAt(cwd);
50
+ if (project && names.length > 1) throw new Error("--project names one repository's namespace; select one repository");
51
+ if (names.length === 0) return unnamedTargets(cwd, here, workspace, project);
52
+ const roots = names.map(name => namedRoot(cwd, workspace, name));
53
+ return { workspace, targets: [...new Set(roots)].map(root => targetFor(root, project)) };
54
+ }
55
+
56
+ /** With no names: every workspace checkout that captures, else the repository holding cwd. */
57
+ function unnamedTargets(cwd: string, here: string | undefined, workspace: string | undefined, project?: string): { workspace?: string; targets: Target[] } {
58
+ if (workspace) {
59
+ const roots = workspaceCheckouts(workspace)
60
+ .map(checkout => checkout.root)
61
+ .filter(captures)
62
+ .sort();
63
+ if (project) throw new Error("--project needs one named repository");
64
+ return { workspace, targets: roots.map(root => targetFor(root)) };
65
+ }
66
+ if (!here) throw new Error(`${cwd} is not inside a git repository; name one`);
67
+ return { targets: [targetFor(realpathSync(here), project)] };
68
+ }