@intellectual-frontiers/system 0.0.0-stage → 0.1.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/git.ts ADDED
@@ -0,0 +1,163 @@
1
+ // Spec: 0001-system FR-014
2
+ /**
3
+ * A Git repository read by running `git` (commons 0007-grc FR-021): the commit at `HEAD`, whether the working tree is clean, the paths
4
+ * changed between two revisions, and a file's bytes as it is at a revision. Each runs `git -C REPO ...` by its argument vector, never
5
+ * through a shell, with no pager, no terminal prompt, no optional locks and messages in English; paths are read NUL-separated (`-z`), so
6
+ * spaces, quotes and non-ASCII names come back as they are. Every failure is an `Err` naming what went wrong, a repository that is not
7
+ * there and a `git` that is not installed included; nothing here throws.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { changedPaths, head } from "./git.ts";
12
+ * const h = await head(".");
13
+ * if (h.kind === "ok") console.log(h.value);
14
+ * const changed = await changedPaths(".", "HEAD~1", "HEAD"); // { kind: "ok", value: ["src/a.ts", ...] }
15
+ * ```
16
+ *
17
+ * @module
18
+ */
19
+ import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
20
+ import type { Brand } from "@intellectual-frontiers/core";
21
+ import { NotFound } from "./errors.ts";
22
+ import { output } from "./proc.ts";
23
+
24
+ /** A commit's object id: 40 (SHA-1) or 64 (SHA-256) lower-case hexadecimal digits, made only by `commitIdOf`. */
25
+ export type CommitId = Brand<string, "CommitId">;
26
+
27
+ /** Text as a commit id, or undefined where it is not 40 or 64 lower-case hexadecimal digits. */
28
+ export function commitIdOf(text: string): CommitId | undefined {
29
+ return /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(text) ? (text as CommitId) : undefined; // checked just now: the brand's one constructor
30
+ }
31
+
32
+ /** Why a repository could not be read. */
33
+ export type GitError =
34
+ | { readonly kind: "git-missing"; readonly program: string }
35
+ | { readonly kind: "not-a-repository"; readonly repo: string; readonly message: string }
36
+ | { readonly kind: "bad-revision"; readonly rev: string; readonly message: string }
37
+ | { readonly kind: "no-such-path"; readonly rev: string; readonly path: string; readonly message: string }
38
+ | { readonly kind: "failed"; readonly args: readonly string[]; readonly code: number; readonly message: string };
39
+
40
+ /** A Git error as one sentence. */
41
+ export function formatGitError(e: GitError): string {
42
+ switch (e.kind) {
43
+ case "git-missing":
44
+ return `${e.program} is not installed (or not on PATH)`;
45
+ case "not-a-repository":
46
+ return `${e.repo} is not a Git repository: ${e.message}`;
47
+ case "bad-revision":
48
+ return `no revision ${e.rev}: ${e.message}`;
49
+ case "no-such-path":
50
+ return `no file ${e.path} at ${e.rev}: ${e.message}`;
51
+ case "failed":
52
+ return `git ${e.args.join(" ")} failed (${e.code}): ${e.message}`;
53
+ default:
54
+ return absurd(e);
55
+ }
56
+ }
57
+
58
+ /** How `git` is run: the program (`git` on PATH by default). */
59
+ export type GitOptions = { readonly program?: string };
60
+
61
+ const ENV: Readonly<Record<string, string>> = {
62
+ GIT_TERMINAL_PROMPT: "0",
63
+ GIT_PAGER: "cat",
64
+ PAGER: "cat",
65
+ GIT_OPTIONAL_LOCKS: "0",
66
+ LC_ALL: "C",
67
+ LANGUAGE: "C",
68
+ };
69
+
70
+ type Ran = { readonly stdout: Uint8Array; readonly stderr: string; readonly code: number };
71
+
72
+ /** `git --no-pager -C repo ...args`, its output, or `git-missing` where there is no git. */
73
+ async function git(repo: string, args: readonly string[], options: GitOptions): Promise<Result<Ran, GitError>> {
74
+ const program = options.program ?? "git";
75
+ try {
76
+ const r = await output([program, "--no-pager", "-C", repo, ...args], { env: ENV });
77
+ return ok({ stdout: r.stdout, stderr: new TextDecoder().decode(r.stderr).trim(), code: r.code });
78
+ } catch (e) {
79
+ if (e instanceof NotFound) return err({ kind: "git-missing", program });
80
+ return err({ kind: "failed", args, code: -1, message: e instanceof Error ? e.message : String(e) });
81
+ }
82
+ }
83
+
84
+ /** A failed run as the error it says it is: no repository (or no folder) there, else `fallback`. */
85
+ function failure(repo: string, args: readonly string[], r: Ran, fallback?: GitError): GitError {
86
+ if (/not a git repository|cannot change to/i.test(r.stderr)) return { kind: "not-a-repository", repo, message: r.stderr };
87
+ return fallback ?? { kind: "failed", args, code: r.code, message: r.stderr };
88
+ }
89
+
90
+ /** A revision that would read as an option is refused rather than passed to git. */
91
+ function checkRev(rev: string): Result<string, GitError> {
92
+ return rev === "" || rev.startsWith("-")
93
+ ? err({ kind: "bad-revision", rev, message: "a revision may not be empty or start with -" })
94
+ : ok(rev);
95
+ }
96
+
97
+ /** The NUL-separated fields of git's `-z` output, as text. */
98
+ function nulFields(bytes: Uint8Array): readonly string[] {
99
+ const text = new TextDecoder().decode(bytes);
100
+ return text.split("\0").filter((p) => p !== "");
101
+ }
102
+
103
+ /** The commit `HEAD` points to; `bad-revision` in a repository with no commit yet. */
104
+ export async function head(repo: string, options: GitOptions = {}): Promise<Result<CommitId, GitError>> {
105
+ const args = ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"];
106
+ const r = await git(repo, args, options);
107
+ if (r.kind === "err") return r;
108
+ if (r.value.code !== 0)
109
+ return err(failure(repo, args, r.value, { kind: "bad-revision", rev: "HEAD", message: r.value.stderr || "no commit yet" }));
110
+ const text = new TextDecoder().decode(r.value.stdout).trim();
111
+ const id = commitIdOf(text);
112
+ return id === undefined ? err({ kind: "failed", args, code: 0, message: `not a commit id: ${text}` }) : ok(id);
113
+ }
114
+
115
+ /** Whether the working tree and the index match `HEAD`, with no untracked file that is not ignored. */
116
+ export async function isClean(repo: string, options: GitOptions = {}): Promise<Result<boolean, GitError>> {
117
+ const args = ["status", "--porcelain=v1", "-z", "--untracked-files=normal", "--ignore-submodules=none"];
118
+ const r = await git(repo, args, options);
119
+ if (r.kind === "err") return r;
120
+ if (r.value.code !== 0) return err(failure(repo, args, r.value));
121
+ return ok(r.value.stdout.length === 0);
122
+ }
123
+
124
+ /**
125
+ * The paths (relative to the repository's top, `/`-separated) whose content differs between two revisions, in Git's order, each once;
126
+ * a rename gives both its old and its new path.
127
+ */
128
+ export async function changedPaths(
129
+ repo: string,
130
+ from: string,
131
+ to: string,
132
+ options: GitOptions = {},
133
+ ): Promise<Result<readonly string[], GitError>> {
134
+ for (const rev of [from, to]) {
135
+ const c = checkRev(rev);
136
+ if (c.kind === "err") return c;
137
+ const v = await git(repo, ["rev-parse", "--verify", "--quiet", `${rev}^{commit}`], options);
138
+ if (v.kind === "err") return v;
139
+ if (v.value.code !== 0)
140
+ return err(failure(repo, ["rev-parse", rev], v.value, { kind: "bad-revision", rev, message: v.value.stderr || "unknown revision" }));
141
+ }
142
+ const args = ["diff", "--name-only", "-z", "--no-renames", "--no-ext-diff", "--no-textconv", from, to, "--"];
143
+ const r = await git(repo, args, options);
144
+ if (r.kind === "err") return r;
145
+ if (r.value.code !== 0) return err(failure(repo, args, r.value));
146
+ return ok([...new Set(nulFields(r.value.stdout))]);
147
+ }
148
+
149
+ /** A file's bytes as it is at a revision, its path relative to the repository's top (`/`-separated); `no-such-path` where it is not there. */
150
+ export async function fileAt(repo: string, rev: string, path: string, options: GitOptions = {}): Promise<Result<Uint8Array, GitError>> {
151
+ const c = checkRev(rev);
152
+ if (c.kind === "err") return c;
153
+ const v = await git(repo, ["rev-parse", "--verify", "--quiet", `${rev}^{commit}`], options);
154
+ if (v.kind === "err") return v;
155
+ if (v.value.code !== 0)
156
+ return err(failure(repo, ["rev-parse", rev], v.value, { kind: "bad-revision", rev, message: v.value.stderr || "unknown revision" }));
157
+ const rel = path.replaceAll("\\", "/").replace(/^\.\//, "");
158
+ const args = ["cat-file", "blob", `${rev}:${rel}`];
159
+ const r = await git(repo, args, options);
160
+ if (r.kind === "err") return r;
161
+ if (r.value.code !== 0) return err(failure(repo, args, r.value, { kind: "no-such-path", rev, path: rel, message: r.value.stderr }));
162
+ return ok(r.value.stdout);
163
+ }