piroboros 0.3.2 → 0.3.4

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/dist/ws/git.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync } from "node:fs";
2
+ import { createReadStream, existsSync } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
3
4
  import { join } from "node:path";
4
5
  import { canonicalize } from "../paths.js";
5
- // Host git for Workspaces. piroboros never runs git with a Workspace as the repository: every call here is against the live
6
- // repository, carries SAFE_GIT, and gets an environment without any GIT_* name in any letter case, so nothing in the
7
- // user's shell, a git hook parent or a Workspace config changes what it reads or runs.
6
+ // Host git for Workspaces. Every call here carries SAFE_GIT and gets an environment without any GIT_* name in any letter case,
7
+ // so nothing in the user's shell, a git hook parent or a Workspace config changes what it reads or runs. Calls are against the
8
+ // live repository, with one exception: `init`, `baseCommit` (`fast-import` and `read-tree`) build the Workspace's own repository at open, when the host has
9
+ // just written the folder and nothing of Vesperia's is in it. After that piroboros never runs git with a Workspace as the repository.
8
10
  /** A message for the user: the reason a Workspace cannot open or a mode cannot be resolved, with the way out. */
9
11
  export class WsRefusal extends Error {
10
12
  }
@@ -27,8 +29,8 @@ export function gitEnv(literal, source = process.env) {
27
29
  }
28
30
  const firstLine = (text) => text.trim().split(/\r?\n/u)[0] ?? "";
29
31
  const dubious = (project) => ` piroboros ignores GIT_* variables, including GIT_CONFIG_GLOBAL; run git config --global --add safe.directory ${project} in a shell where GIT_CONFIG_GLOBAL is not set.`;
30
- /** The config keys copied into a git Workspace; everything else (fsmonitor, hooksPath, filters, includes, credentials) is dropped. */
31
- const CONFIG_KEYS = /^(?:core\.(?:repositoryformatversion|bare|filemode|symlinks|ignorecase|precomposeunicode|autocrlf|eol|safecrlf|logallrefupdates|quotepath)|extensions\.(?:objectformat|refstorage)|user\.(?:name|email)|remote\..+\.(?:url|fetch)|branch\..+\.(?:remote|merge))$/u;
32
+ /** The config keys copied into a git Workspace; everything else (fsmonitor, hooksPath, filters, includes, credentials, the repository format) is dropped. */
33
+ const CONFIG_KEYS = /^(?:core\.(?:bare|filemode|symlinks|ignorecase|precomposeunicode|autocrlf|eol|safecrlf|logallrefupdates|quotepath)|user\.(?:name|email)|remote\..+\.(?:url|fetch)|branch\..+\.(?:remote|merge))$/u;
32
34
  export class HostGit {
33
35
  home;
34
36
  spy;
@@ -36,6 +38,7 @@ export class HostGit {
36
38
  this.home = home;
37
39
  this.spy = spy;
38
40
  }
41
+ /** `feed` writes a large stdin itself (await `put` on each chunk); `input` is a small one. */
39
42
  run(cwd, args, options = {}) {
40
43
  const env = gitEnv(options.literal ?? true);
41
44
  const argv = [...safeGit(this.home), ...args];
@@ -50,8 +53,13 @@ export class HostGit {
50
53
  err += text; });
51
54
  child.stdin.on("error", () => { });
52
55
  child.on("error", (error) => reject(error.code === "ENOENT" ? new WsRefusal("git is not installed or not on PATH, so a Workspace cannot be made; install git, or set workspace.enabled to false to run in place") : error));
53
- child.on("close", (code) => resolve({ code, out: Buffer.concat(out), err }));
54
- child.stdin.end(options.input);
56
+ let fed;
57
+ child.on("close", (code) => (fed !== undefined ? reject(fed) : resolve({ code, out: Buffer.concat(out), err })));
58
+ if (options.feed === undefined) {
59
+ child.stdin.end(options.input);
60
+ return;
61
+ }
62
+ options.feed(child.stdin).then(() => child.stdin.end(), (error) => { fed = error; child.kill(); });
55
63
  });
56
64
  }
57
65
  fail(project, result, what) {
@@ -117,22 +125,87 @@ export class HostGit {
117
125
  const r = await this.run(project, ["rev-parse", "HEAD"]);
118
126
  return r.code === 0 ? r.out.toString("utf8").trim() : undefined;
119
127
  }
120
- /** The commit ids HEAD and every ref point at. `knownHead` is the caller's own `head()` ("" for none), to skip a second call. */
121
- async refIds(project, knownHead) {
122
- const refs = await this.run(project, ["for-each-ref", "--format=%(objectname)"]);
123
- if (refs.code !== 0)
124
- throw this.fail(project, refs, "for-each-ref");
125
- const head = knownHead === undefined ? await this.head(project) : knownHead === "" ? undefined : knownHead;
126
- return [...new Set([...(head === undefined ? [] : [head]), ...refs.out.toString("utf8").split(/\r?\n/u).filter((id) => id !== "")])];
128
+ /** The branch HEAD is on, or undefined when it is detached. */
129
+ async branch(project) {
130
+ const r = await this.run(project, ["symbolic-ref", "-q", "--short", "HEAD"]);
131
+ return r.code === 0 && r.out.toString("utf8").trim() !== "" ? r.out.toString("utf8").trim() : undefined;
127
132
  }
128
- /** The ids of the list the repository does not have. */
129
- async missingObjects(project, ids) {
130
- if (ids.length === 0)
131
- return [];
132
- const r = await this.run(project, ["cat-file", "--batch-check"], { input: `${ids.join("\n")}\n` });
133
+ /** A new empty repository in `folder` (no hook templates), HEAD on `branch` when given. See the note at the top: this runs against a Workspace. */
134
+ async init(folder, branch) {
135
+ const r = await this.run(folder, ["init", "-q", "--template="]);
133
136
  if (r.code !== 0)
134
- throw this.fail(project, r, "cat-file");
135
- return r.out.toString("utf8").split(/\r?\n/u).filter((line) => /\bmissing$/u.test(line)).map((line) => line.split(" ")[0]);
137
+ throw this.fail(folder, r, "init");
138
+ if (branch === undefined)
139
+ return;
140
+ const h = await this.run(folder, [`--git-dir=${join(folder, ".git")}`, "symbolic-ref", "HEAD", `refs/heads/${branch}`]);
141
+ if (h.code !== 0)
142
+ throw this.fail(folder, h, "symbolic-ref");
143
+ }
144
+ /**
145
+ * Make the one base commit of `folder` from the copied files (fixed identity), as one `fast-import` stream of the raw bytes, then `read-tree` for the index. Neither runs a clean
146
+ * filter, an eol conversion or a hook, so no filter of the user's global or system git config runs on the host, and a few loose objects stay out of the Workspace.
147
+ * Each file is read from `folder` once, one at a time. See the note at the top: this runs against a Workspace.
148
+ */
149
+ async baseCommit(folder, files) {
150
+ const where = [`--git-dir=${join(folder, ".git")}`, `--work-tree=${folder}`];
151
+ const ref = await this.run(folder, [...where, "symbolic-ref", "-q", "HEAD"]);
152
+ const branch = ref.out.toString("utf8").trim();
153
+ if (ref.code !== 0 || !branch.startsWith("refs/heads/"))
154
+ throw this.fail(folder, ref, "symbolic-ref");
155
+ const quote = (path) => `"${path.replace(/[\\"\x00-\x1f\x7f]/gu, (c) => (c === "\\" || c === '"' ? `\\${c}` : `\\${c.charCodeAt(0).toString(8).padStart(3, "0")}`))}"`;
156
+ const put = (w, chunk) => (w.write(chunk) || w.destroyed ? Promise.resolve() : new Promise((done) => { const end = () => { w.off("drain", end); w.off("close", end); done(); }; w.once("drain", end); w.once("close", end); }));
157
+ const feed = async (w) => {
158
+ // Small pieces gather into ~256 KiB writes: a pipe write per piece costs more than reading the file. A big file streams through.
159
+ let batch = [];
160
+ let held = 0;
161
+ const add = async (chunk) => { const b = typeof chunk === "string" ? Buffer.from(chunk) : chunk; batch.push(b); held += b.length; if (held >= 262_144)
162
+ await flush(); };
163
+ const flush = async () => { const b = Buffer.concat(batch); batch = []; held = 0; await put(w, b); };
164
+ await add(`commit ${branch}\ncommitter piroboros <piroboros@localhost> ${Math.floor(Date.now() / 1000)} +0000\ndata <<EOM\npiroboros Workspace base\nEOM\n`);
165
+ // A file read costs about 0.7 ms here, so 16 small files are read ahead (at most 16 MiB held); each result is the bytes, or the error to throw in its turn.
166
+ const small = (f) => f.link === undefined && f.size <= 1_048_576;
167
+ const ahead = [];
168
+ let next = 0;
169
+ for (let i = 0; i < files.length; i += 1) {
170
+ while (ahead.length < 16 && next < files.length) {
171
+ const g = files[next++];
172
+ ahead.push(small(g) ? readFile(join(folder, g.path)).catch((error) => error) : Promise.resolve(Buffer.alloc(0)));
173
+ }
174
+ const f = files[i];
175
+ const bytes = await ahead.shift();
176
+ if (bytes instanceof Error)
177
+ throw bytes;
178
+ if (w.destroyed)
179
+ return;
180
+ await add(`M ${f.mode} inline ${quote(f.path)}\n`);
181
+ if (f.link !== undefined) {
182
+ const text = Buffer.from(f.link);
183
+ await add(`data ${text.length}\n`);
184
+ await add(text);
185
+ }
186
+ else if (small(f)) {
187
+ if (bytes.length !== f.size)
188
+ throw new Error(`${f.path} changed while it was committed`);
189
+ await add(`data ${f.size}\n`);
190
+ await add(bytes);
191
+ }
192
+ else {
193
+ await add(`data ${f.size}\n`);
194
+ await flush();
195
+ for await (const chunk of createReadStream(join(folder, f.path)))
196
+ await put(w, chunk);
197
+ }
198
+ await add("\n");
199
+ }
200
+ await add("done\n");
201
+ await flush();
202
+ };
203
+ const imported = await this.run(folder, [...where, "fast-import", "--quiet", "--done", "--date-format=raw"], { feed });
204
+ if (imported.code !== 0)
205
+ throw this.fail(folder, imported, "fast-import");
206
+ const index = await this.run(folder, [...where, "read-tree", "HEAD"]);
207
+ if (index.code !== 0)
208
+ throw this.fail(folder, index, "read-tree");
136
209
  }
137
210
  /** The live repository's own config reduced to the allowed keys, as a fresh INI text. Every remote gets a push URL that fails. */
138
211
  async copyConfig(gitDir) {