architecture-harness 0.7.0 → 0.8.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.
@@ -155,6 +155,85 @@ test("check judges every configured mirror root, including a tests folder outsid
155
155
  rmSync(dir, { recursive: true, force: true });
156
156
  });
157
157
 
158
+ const ENGLISH_RULES = new Set(["english-comment", "english-source"]);
159
+ const englishPaths = (problems) => problems.filter((problem) => ENGLISH_RULES.has(problem.rule)).map((problem) => problem.path).sort();
160
+
161
+ function write(dir, files) {
162
+ for (const [file, contents] of Object.entries(files)) {
163
+ mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
164
+ writeFileSync(path.join(dir, file), contents);
165
+ }
166
+ }
167
+
168
+ // The English gate is a policy gate, so the kit ships it off.
169
+ const ENGLISH_ON = JSON.stringify({ featureRoots: ["backend/src/features"], gates: { "english-source": true } });
170
+
171
+ /** Japanese in a git-ignored folder, under a path in `.git/info/exclude`, and in a tracked file. */
172
+ const JAPANESE = {
173
+ "qc.config.json": ENGLISH_ON,
174
+ ".gitignore": ".gitnexus/\n",
175
+ ".gitnexus/wiki/overview.md": "図面の概要\n",
176
+ "local/draft.md": "下書き\n",
177
+ "docs/tracked.md": "検査の手順\n",
178
+ };
179
+
180
+ test("check skips what git ignores and scans what git tracks", async () => {
181
+ const dir = repo();
182
+ await quiet(() => runInit(load(dir)));
183
+ write(dir, JAPANESE);
184
+ writeFileSync(path.join(dir, ".git/info/exclude"), "local/\n");
185
+ execFileSync("git", ["add", "docs/tracked.md"], { cwd: dir });
186
+ const { problems } = await runCheck(load(dir));
187
+ assert.deepEqual(englishPaths(problems), ["docs/tracked.md"]);
188
+ rmSync(dir, { recursive: true, force: true });
189
+ });
190
+
191
+ test("outside git, check walks the tree and still scans every file", async () => {
192
+ const dir = mkdtempSync(path.join(tmpdir(), "qc-cli-plain-"));
193
+ writeFileSync(path.join(dir, "package.json"), '{"name":"t","private":true,"type":"module"}\n');
194
+ await quiet(() => runInit(load(dir)));
195
+ write(dir, { ...JAPANESE, "node_modules/pkg/readme.md": "日本語\n" });
196
+ const { problems } = await runCheck(load(dir));
197
+ assert.deepEqual(englishPaths(problems), [".gitnexus/wiki/overview.md", "docs/tracked.md", "local/draft.md"]);
198
+ rmSync(dir, { recursive: true, force: true });
199
+ });
200
+
201
+ test("one check lists the repository once, for every gate", async () => {
202
+ const dir = repo();
203
+ await quiet(() => runInit(load(dir)));
204
+ let calls = 0;
205
+ const lister = async (...args) => {
206
+ calls += 1;
207
+ return (await import("./repo-files.mjs")).repoFiles(...args);
208
+ };
209
+ await runCheck(load(dir), [], { lister });
210
+ await runCheck(load(dir), ["docs/decisions.md", "qc.config.json"], { lister });
211
+ assert.equal(calls, 2);
212
+ rmSync(dir, { recursive: true, force: true });
213
+ });
214
+
215
+ test("check with several files reports every problem from each, and judges only those files", async () => {
216
+ const dir = repo();
217
+ await quiet(() => runInit(load(dir)));
218
+ const orders = "backend/src/features/orders";
219
+ const invoices = "backend/src/features/invoices";
220
+ write(dir, {
221
+ "qc.config.json": ENGLISH_ON,
222
+ [`${orders}/index.ts`]: "export {};\n",
223
+ [`${orders}/junk/a.ts`]: "// 注文の補助\nexport {};\n",
224
+ [`${invoices}/index.ts`]: "export {};\n",
225
+ [`${invoices}/junk/b.ts`]: "export {};\n",
226
+ "docs/untouched.md": "触らない\n",
227
+ });
228
+ const { problems } = await runCheck(load(dir), [`${orders}/junk/a.ts`, path.join(dir, invoices, "junk/b.ts")]);
229
+ const features = new Set(problems.filter((problem) => problem.feature).map((problem) => problem.feature.split(path.sep).join("/")));
230
+ assert.deepEqual([...features].sort(), [invoices, orders]);
231
+ assert.deepEqual(englishPaths(problems), [`${orders}/junk/a.ts`]);
232
+ const full = await runCheck(load(dir));
233
+ assert.ok(englishPaths(full.problems).includes("docs/untouched.md"), "no file given must stay the full check");
234
+ rmSync(dir, { recursive: true, force: true });
235
+ });
236
+
158
237
  test("a clean mirror run names every root it judged", async () => {
159
238
  const dir = await mirrored(["backend/src/orders/ship.ts", "backend/tests/orders/ship.test.ts"]);
160
239
  const { lines } = await runCheck(load(dir));
@@ -20,6 +20,7 @@ import {
20
20
  rewrite,
21
21
  squashPlan,
22
22
  } from "../decisions.mjs";
23
+ import { repoFiles } from "./repo-files.mjs";
23
24
 
24
25
  const run = promisify(execFile);
25
26
 
@@ -39,11 +40,9 @@ export const USAGE = `qc decisions — where every decision id is cited, and how
39
40
  --dry-run print what would change and write nothing
40
41
  --force run against a dirty tree`;
41
42
 
42
- // Tracked and untracked-but-not-ignored, so this sees what the citations gate sees.
43
- async function tracked(root) {
44
- const args = ["ls-files", "-z", "--cached", "--others", "--exclude-standard"];
45
- const { stdout } = await run("git", args, { cwd: root, maxBuffer: 64 * 1024 * 1024 });
46
- return [...new Set(stdout.split("\0"))].filter((name) => name !== "" && !BINARY.test(name));
43
+ // The lister every gate reads, so this sees what the citations gate sees.
44
+ async function tracked(config) {
45
+ return (await repoFiles(config.root, { ignores: config.ignores })).filter((name) => !BINARY.test(name));
47
46
  }
48
47
 
49
48
  async function scan(config) {
@@ -51,7 +50,7 @@ async function scan(config) {
51
50
  const exclude = config.decisions.exclude ?? [];
52
51
  const sites = new Map();
53
52
  const generated = new Map();
54
- for (const file of await tracked(config.root)) {
53
+ for (const file of await tracked(config)) {
55
54
  // A vendored tool cites its own upstream register, never this repository's.
56
55
  if (exclude.some((source) => new RegExp(source).test(file))) continue;
57
56
  const contents = await readFile(path.join(config.root, file), "utf8").catch(() => null);
@@ -0,0 +1,29 @@
1
+ // The resource for git's own view of which paths a checkout ignores. An ignored path never reaches
2
+ // a commit, so the edit guard and the Bash edit guard both let it through a protected branch.
3
+
4
+ import { execFile } from "node:child_process";
5
+ import { promisify } from "node:util";
6
+
7
+ const execFileAsync = promisify(execFile);
8
+ const NUL = "\u0000";
9
+
10
+ /**
11
+ * One `git check-ignore` call for every path. A tracked path is never ignored, as in `git status`.
12
+ * @param {string} root the checkout's top level
13
+ * @param {string[]} relPaths forward-slash, relative to `root`
14
+ * @returns {Promise<Set<string>>} the ignored subset; empty when none is, or git cannot tell
15
+ */
16
+ export async function ignoredPaths(root, relPaths) {
17
+ if (relPaths.length === 0) return new Set();
18
+ const pending = execFileAsync("git", ["check-ignore", "--stdin", "-z"], { cwd: root });
19
+ // Git outside a checkout exits before it reads, and the broken pipe must not crash the hook.
20
+ pending.child.stdin.on("error", () => {});
21
+ pending.child.stdin.end(relPaths.join(NUL) + NUL);
22
+ try {
23
+ const { stdout } = await pending;
24
+ return new Set(stdout.split(NUL).filter(Boolean));
25
+ } catch {
26
+ // Exit 1 means no path is ignored; any other failure keeps every path in scope of the guard.
27
+ return new Set();
28
+ }
29
+ }
@@ -0,0 +1,44 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { ignoredPaths } from "./ignored-paths.mjs";
8
+
9
+ /** A checkout that ignores `*.local.json` and tracks one file whose name matches that pattern. */
10
+ function checkout() {
11
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-ignored-")));
12
+ const git = (...args) => execFileSync("git", args, { cwd: base, stdio: "pipe" });
13
+ git("init", "-q", "-b", "main");
14
+ writeFileSync(path.join(base, ".gitignore"), "*.local.json\n");
15
+ writeFileSync(path.join(base, "tracked.local.json"), "{}");
16
+ git("add", ".gitignore");
17
+ git("add", "-f", "tracked.local.json");
18
+ git("-c", "user.name=qc", "-c", "user.email=qc@example.com", "commit", "-q", "-m", "init");
19
+ return { root: base, cleanup: () => rmSync(base, { recursive: true, force: true }) };
20
+ }
21
+
22
+ test("the ignored subset of the paths comes back, in one call", async (t) => {
23
+ const repo = checkout();
24
+ t.after(repo.cleanup);
25
+ const ignored = await ignoredPaths(repo.root, [".claude/settings.local.json", "src/a.ts", "notes.local.json"]);
26
+ assert.deepEqual([...ignored].sort(), [".claude/settings.local.json", "notes.local.json"]);
27
+ });
28
+
29
+ test("a tracked file is never ignored, even when its name matches an ignore pattern", async (t) => {
30
+ const repo = checkout();
31
+ t.after(repo.cleanup);
32
+ assert.equal((await ignoredPaths(repo.root, ["tracked.local.json"])).size, 0);
33
+ });
34
+
35
+ test("no path ignored, no paths, or no checkout is the empty set", async (t) => {
36
+ const repo = checkout();
37
+ t.after(repo.cleanup);
38
+ assert.equal((await ignoredPaths(repo.root, ["src/a.ts"])).size, 0);
39
+ assert.equal((await ignoredPaths(repo.root, [])).size, 0);
40
+ const outside = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-no-checkout-")));
41
+ t.after(() => rmSync(outside, { recursive: true, force: true }));
42
+ mkdirSync(path.join(outside, "sub"));
43
+ assert.equal((await ignoredPaths(path.join(outside, "sub"), ["a.local.json"])).size, 0);
44
+ });
package/src/cli/qc.mjs CHANGED
@@ -7,7 +7,7 @@ import { runCheck } from "./check.mjs";
7
7
 
8
8
  const USAGE = `qc — architecture gates
9
9
 
10
- qc check [file] every structural gate; one file is the fast path a hook takes
10
+ qc check [file...] every structural gate; files given take the fast path a hook or a commit takes
11
11
  qc init scaffold the docs, config, hooks and workflow into this repository
12
12
  qc feature <name> scaffold a feature in the configured anatomy
13
13
  qc run [name] drive one feature command headless; no name lists them
@@ -17,6 +17,10 @@ const USAGE = `qc — architecture gates
17
17
  qc lease release [path] remove it: --session <id> for your own, --force for another's
18
18
  qc commit-msg <file> refuse a commit message that credits a tool as an author
19
19
  qc decisions [id] where decisions are cited; --squash closes the gaps
20
+ qc worktree add <name> <branch> [--from <ref>]
21
+ fetch, add ../<name> beside the main checkout, install, print the path
22
+ qc worktree remove <name>
23
+ refuse a dirty tree; delete it, then its branch once merged or pushed
20
24
  qc enforcement-map refresh the generated rule/gate table in docs/enforcement.md
21
25
  qc doctor the hooks and the lockfile must run the same harness
22
26
  qc config print the resolved configuration
@@ -34,7 +38,7 @@ async function main() {
34
38
 
35
39
  switch (command) {
36
40
  case "check": {
37
- const { problems, lines } = await runCheck(config, rest[0]);
41
+ const { problems, lines } = await runCheck(config, rest);
38
42
  if (problems.length > 0) {
39
43
  for (const problem of problems) {
40
44
  console.error(`FAIL ${problem.feature ?? problem.path} ${problem.rule}: ${problem.detail}`);
@@ -80,6 +84,10 @@ async function main() {
80
84
  process.exit(await runDecisions(config, rest));
81
85
  return;
82
86
  }
87
+ case "worktree": {
88
+ const { runWorktree } = await import("./worktree.mjs");
89
+ process.exit(await runWorktree(config, rest));
90
+ }
83
91
  case "enforcement-map": {
84
92
  const { runSyncEnforcementMap } = await import("./sync-enforcement-map.mjs");
85
93
  await runSyncEnforcementMap(config);
@@ -0,0 +1,69 @@
1
+ // A resource: the one list of a repository's files. Every gate and `qc decisions` read it, so a
2
+ // path git ignores is invisible to all of them, and one `qc check` spawns git once.
3
+
4
+ import { execFile } from "node:child_process";
5
+ import { readdir, stat } from "node:fs/promises";
6
+ import path from "node:path";
7
+ import { promisify } from "node:util";
8
+ import { globToRegExp } from "../glob.mjs";
9
+
10
+ const execFileAsync = promisify(execFile);
11
+ // The execFile default is 1 MB. A 30,000-file repository lists about 2 MB of paths.
12
+ const MAX_BUFFER = 256 * 1024 * 1024;
13
+
14
+ /** A leading `**` also matches at the root, as ESLint reads the same `ignores`. */
15
+ function ignoredBy(globs) {
16
+ const patterns = globs.map(globToRegExp);
17
+ return (rel) => patterns.some((pattern) => pattern.test(rel) || pattern.test(`/${rel}`));
18
+ }
19
+
20
+ // `-t` tags each entry. `R` is a tracked file gone from the working tree and `S` is skip-worktree, so neither is on disk.
21
+ const NOT_ON_DISK = new Set(["R", "S"]);
22
+
23
+ /** @returns {Promise<string[] | null>} null when `root` is in no git work tree */
24
+ async function gitListing(root, pathspecs) {
25
+ const args = ["--literal-pathspecs", "ls-files", "-z", "-t", "--cached", "--deleted", "--others", "--exclude-standard"];
26
+ if (pathspecs) args.push("--", ...pathspecs);
27
+ try {
28
+ const { stdout } = await execFileAsync("git", args, { cwd: root, maxBuffer: MAX_BUFFER });
29
+ const entries = stdout.split("\0").filter((entry) => entry.length > 2);
30
+ const gone = new Set(entries.filter((entry) => NOT_ON_DISK.has(entry[0])).map((entry) => entry.slice(2)));
31
+ return entries.map((entry) => entry.slice(2)).filter((file) => !gone.has(file));
32
+ } catch {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ /** The walk outside git: every file, with `.git` and each ignored folder pruned. */
38
+ async function walkListing(root, pathspecs, ignored) {
39
+ const files = [];
40
+ async function visit(rel) {
41
+ for (const entry of await readdir(path.join(root, rel), { withFileTypes: true }).catch(() => [])) {
42
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
43
+ if (!entry.isDirectory()) files.push(child);
44
+ else if (entry.name !== ".git" && !ignored(`${child}/`)) await visit(child);
45
+ }
46
+ }
47
+ if (!pathspecs) await visit("");
48
+ for (const spec of pathspecs ?? []) {
49
+ const found = await stat(path.join(root, spec)).catch(() => null);
50
+ if (found?.isDirectory()) await visit(spec);
51
+ else if (found) files.push(spec);
52
+ }
53
+ return files;
54
+ }
55
+
56
+ /**
57
+ * Tracked files and untracked files git does not ignore, then minus `ignores`.
58
+ * @param {string} root the repository root that `qc.config.json` sits in
59
+ * @param {{ignores?: string[], pathspecs?: string[]}} [options] pathspecs are literal, relative to `root`
60
+ * @returns {Promise<string[]>} forward-slash paths relative to `root`, sorted
61
+ */
62
+ export async function repoFiles(root, { ignores = [], pathspecs } = {}) {
63
+ if (pathspecs?.length === 0) return [];
64
+ const ignored = ignoredBy(ignores);
65
+ const listed = (await gitListing(root, pathspecs)) ?? (await walkListing(root, pathspecs, ignored));
66
+ // A trailing slash is an untracked nested repository, which git lists as one entry.
67
+ const files = listed.filter((file) => file !== "" && !file.endsWith("/") && !ignored(file));
68
+ return [...new Set(files)].sort();
69
+ }
@@ -0,0 +1,78 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync } from "node:child_process";
4
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { repoFiles } from "./repo-files.mjs";
8
+
9
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe" });
10
+
11
+ function tree(files) {
12
+ const dir = mkdtempSync(path.join(tmpdir(), "qc-files-"));
13
+ for (const [file, contents] of Object.entries(files)) {
14
+ mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
15
+ writeFileSync(path.join(dir, file), contents);
16
+ }
17
+ return dir;
18
+ }
19
+
20
+ function checkout(files) {
21
+ const dir = tree(files);
22
+ git(dir, "init", "-q", "-b", "main");
23
+ return dir;
24
+ }
25
+
26
+ test("an untracked file under a path in .git/info/exclude is not listed", async () => {
27
+ const dir = checkout({ "src/a.ts": "", ".gitnexus/meta.json": "{}" });
28
+ writeFileSync(path.join(dir, ".git/info/exclude"), ".gitnexus/\n");
29
+ assert.deepEqual(await repoFiles(dir), ["src/a.ts"]);
30
+ rmSync(dir, { recursive: true, force: true });
31
+ });
32
+
33
+ test("a tracked file is listed, also under a folder that git ignores", async () => {
34
+ const dir = checkout({ ".gitignore": "vendor/\n", "vendor/kept.ts": "", "vendor/loose.ts": "", "src/a.ts": "" });
35
+ git(dir, "add", "-f", "vendor/kept.ts", "src/a.ts");
36
+ assert.deepEqual(await repoFiles(dir), [".gitignore", "src/a.ts", "vendor/kept.ts"]);
37
+ rmSync(dir, { recursive: true, force: true });
38
+ });
39
+
40
+ test("a tracked file deleted from the working tree, but not staged, is not listed", async () => {
41
+ const dir = checkout({ "src/a.ts": "", "src/b.ts": "" });
42
+ git(dir, "add", "src/a.ts", "src/b.ts");
43
+ git(dir, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "init");
44
+ rmSync(path.join(dir, "src/b.ts"));
45
+ assert.deepEqual(await repoFiles(dir), ["src/a.ts"]);
46
+ rmSync(dir, { recursive: true, force: true });
47
+ });
48
+
49
+ test("the old name of an unstaged move is not listed, and the new name is", async () => {
50
+ const dir = checkout({ "src/old.ts": "" });
51
+ git(dir, "add", "src/old.ts");
52
+ git(dir, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "init");
53
+ writeFileSync(path.join(dir, "src/new.ts"), "");
54
+ rmSync(path.join(dir, "src/old.ts"));
55
+ assert.deepEqual(await repoFiles(dir), ["src/new.ts"]);
56
+ rmSync(dir, { recursive: true, force: true });
57
+ });
58
+
59
+ test("ignores drop a path at the root and below, as ESLint reads them", async () => {
60
+ const dir = checkout({ "dist/a.js": "", "pkg/dist/b.js": "", "pkg/c.tsbuildinfo": "", "pkg/d.ts": "" });
61
+ const ignores = ["**/dist/**", "**/*.tsbuildinfo"];
62
+ assert.deepEqual(await repoFiles(dir, { ignores }), ["pkg/d.ts"]);
63
+ rmSync(dir, { recursive: true, force: true });
64
+ });
65
+
66
+ test("pathspecs scope the listing to those files and folders, literally", async () => {
67
+ const dir = checkout({ "a/[x].ts": "", "a/y.ts": "", "b/z.ts": "", "c.ts": "" });
68
+ assert.deepEqual(await repoFiles(dir, { pathspecs: ["a/[x].ts", "b"] }), ["a/[x].ts", "b/z.ts"]);
69
+ rmSync(dir, { recursive: true, force: true });
70
+ });
71
+
72
+ test("outside git, a walk lists every file and prunes an ignored folder", async () => {
73
+ const dir = tree({ "src/a.ts": "", "node_modules/x/index.js": "", "b/c.md": "" });
74
+ const ignores = ["**/node_modules/**"];
75
+ assert.deepEqual(await repoFiles(dir, { ignores }), ["b/c.md", "src/a.ts"]);
76
+ assert.deepEqual(await repoFiles(dir, { ignores, pathspecs: ["src", "b/c.md", "gone.ts"] }), ["b/c.md", "src/a.ts"]);
77
+ rmSync(dir, { recursive: true, force: true });
78
+ });
@@ -0,0 +1,211 @@
1
+ // A fragment that reads a shell command the way the plugin's hooks need it: its segments, the git
2
+ // calls and directories in them, and whether any segment can write. It never runs the command.
3
+ // A command it cannot read counts as one that can write, so a guard that skips work skips safely.
4
+
5
+ /**
6
+ * @typedef {{ words: string[], redirects: string[] }} Segment
7
+ * `words` are unquoted; `redirects` are the targets of `>`, `>>` and `&>`.
8
+ */
9
+
10
+ const BLANK = /[ \t]/;
11
+ const WORD_END = /[\s;&|<>()]/;
12
+
13
+ /** Skips each pending heredoc body after a newline. @returns the index after the last body. */
14
+ function skipHeredocs(command, start, heredocs) {
15
+ let i = start;
16
+ for (const { delimiter, strip } of heredocs) {
17
+ while (i < command.length) {
18
+ const end = command.indexOf("\n", i);
19
+ const stop = end === -1 ? command.length : end;
20
+ const line = command.slice(i, stop).replace(/\r$/, "");
21
+ i = stop + 1;
22
+ if ((strip ? line.replace(/^\t+/, "") : line) === delimiter) break;
23
+ }
24
+ }
25
+ return i;
26
+ }
27
+
28
+ /** @returns {Segment[]} the segments between unquoted `;`, `&`, `&&`, `|`, `||`, parentheses and newlines. */
29
+ export function segmentsOf(command) {
30
+ const segments = [];
31
+ let words = [];
32
+ let redirects = [];
33
+ let word = "";
34
+ let inWord = false;
35
+ let quote = null;
36
+ let target = null;
37
+ let heredocs = [];
38
+
39
+ const endWord = () => {
40
+ if (!inWord) return;
41
+ if (target === "out") redirects.push(word);
42
+ else if (target !== "in") words.push(word);
43
+ target = null;
44
+ word = "";
45
+ inWord = false;
46
+ };
47
+ const endSegment = () => {
48
+ endWord();
49
+ if (words.length > 0 || redirects.length > 0) segments.push({ words, redirects });
50
+ words = [];
51
+ redirects = [];
52
+ };
53
+
54
+ let i = 0;
55
+ while (i < command.length) {
56
+ const c = command[i];
57
+ const next = command[i + 1];
58
+ if (quote === "'") {
59
+ if (c === "'") quote = null;
60
+ else word += c;
61
+ i++;
62
+ } else if (quote === '"') {
63
+ // Inside double quotes a backslash escapes only these, so a Windows path keeps its separators.
64
+ if (c === "\\" && next !== undefined && '$`"\\\n'.includes(next)) {
65
+ word += next;
66
+ i += 2;
67
+ } else {
68
+ if (c === '"') quote = null;
69
+ else word += c;
70
+ i++;
71
+ }
72
+ } else if (c === "'" || c === '"') {
73
+ quote = c;
74
+ inWord = true;
75
+ i++;
76
+ } else if (c === "\\") {
77
+ if (next !== "\n") word += next ?? "";
78
+ inWord = next !== "\n" || inWord;
79
+ i += 2;
80
+ } else if (c === "\n") {
81
+ endSegment();
82
+ i = skipHeredocs(command, i + 1, heredocs);
83
+ heredocs = [];
84
+ } else if (BLANK.test(c) || c === "\r") {
85
+ endWord();
86
+ i++;
87
+ } else if (c === ";" || c === "(" || c === ")") {
88
+ endSegment();
89
+ i++;
90
+ } else if (c === "|") {
91
+ endSegment();
92
+ i += next === "|" ? 2 : 1;
93
+ } else if (c === "&") {
94
+ if (next === ">") {
95
+ endWord();
96
+ target = "out";
97
+ i += command[i + 2] === ">" ? 3 : 2;
98
+ } else {
99
+ endSegment();
100
+ i += next === "&" ? 2 : 1;
101
+ }
102
+ } else if (c === ">") {
103
+ // A leading descriptor number belongs to the operator, as in `2>file`.
104
+ if (inWord && /^\d+$/.test(word)) {
105
+ word = "";
106
+ inWord = false;
107
+ } else {
108
+ endWord();
109
+ }
110
+ i += next === ">" ? 2 : 1;
111
+ if (command[i] === "&") {
112
+ i++;
113
+ while (/[\d-]/.test(command[i] ?? "")) i++;
114
+ } else {
115
+ target = "out";
116
+ }
117
+ } else if (c === "<") {
118
+ endWord();
119
+ if (next === "<" && command[i + 2] !== "<") {
120
+ i += 2;
121
+ const strip = command[i] === "-";
122
+ if (strip) i++;
123
+ while (BLANK.test(command[i] ?? "")) i++;
124
+ let delimiter = "";
125
+ while (i < command.length && !WORD_END.test(command[i])) {
126
+ if (!`'"\\`.includes(command[i])) delimiter += command[i];
127
+ i++;
128
+ }
129
+ heredocs.push({ delimiter, strip });
130
+ } else {
131
+ i += next === "<" ? 3 : 1;
132
+ target = "in";
133
+ }
134
+ } else {
135
+ word += c;
136
+ inWord = true;
137
+ i++;
138
+ }
139
+ }
140
+ endSegment();
141
+ return segments;
142
+ }
143
+
144
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
145
+
146
+ /** The words after any leading `NAME=value` assignments. */
147
+ const commandWords = (segment) => {
148
+ const start = segment.words.findIndex((word) => !ASSIGNMENT.test(word));
149
+ return start === -1 ? [] : segment.words.slice(start);
150
+ };
151
+
152
+ const isGit = (word) => /(^|[\\/])git(\.exe)?$/.test(word ?? "");
153
+
154
+ /** @returns the git subcommand and each `-C` directory, or null when the segment is no git call. */
155
+ export function gitCall(segment) {
156
+ const [program, ...args] = commandWords(segment);
157
+ if (!isGit(program)) return null;
158
+ const dirs = [];
159
+ for (let i = 0; i < args.length; i++) {
160
+ const arg = args[i];
161
+ if (arg === "-C") dirs.push(args[++i]);
162
+ else if (arg === "-c") i++;
163
+ else if (!arg.startsWith("-")) return { sub: arg, dirs };
164
+ }
165
+ return { sub: null, dirs };
166
+ }
167
+
168
+ /** @returns the directory a `cd` or `pushd` segment moves to, or null. */
169
+ export function cdTarget(segment) {
170
+ const [program, target] = commandWords(segment);
171
+ return program === "cd" || program === "pushd" ? (target ?? "~") : null;
172
+ }
173
+
174
+ const READ_PROGRAMS = new Set([
175
+ "ls", "cat", "head", "tail", "grep", "egrep", "fgrep", "rg", "wc", "pwd", "echo", "printf",
176
+ "cut", "tr", "jq", "which", "type", "stat", "file", "du", "df", "date", "basename",
177
+ "dirname", "realpath", "readlink", "diff", "cmp", "true", "false", "test", "[", "popd",
178
+ ]);
179
+ const GIT_READS = new Set([
180
+ "status", "diff", "log", "show", "rev-parse", "ls-files", "grep", "blame", "branch", "remote",
181
+ "fetch", "describe", "shortlog", "config",
182
+ ]);
183
+ const SED_IN_PLACE = /^(-[A-Za-z]*i|--in-place)/;
184
+
185
+ /** True when the segment writes a file through a redirect other than the null device. */
186
+ export const writesRedirect = (segment) => segment.redirects.some((file) => file !== "/dev/null");
187
+
188
+ /** True when one segment only reads, or only moves between directories. */
189
+ export function isReadOnly(segment) {
190
+ if (writesRedirect(segment)) return false;
191
+ if (cdTarget(segment) !== null) return true;
192
+ const git = gitCall(segment);
193
+ if (git) return GIT_READS.has(git.sub);
194
+ const [program, ...args] = commandWords(segment);
195
+ if (program === "sed") return !args.some((arg) => SED_IN_PLACE.test(arg));
196
+ return READ_PROGRAMS.has(program);
197
+ }
198
+
199
+ /** False only when every segment is known to read, so an unknown program counts as a write. */
200
+ export const mayWrite = (command) => !segmentsOf(command).every(isReadOnly);
201
+
202
+ /** Every directory the command names through `cd` or `git -C`, in order, as written. */
203
+ export function checkoutDirs(command) {
204
+ const dirs = [];
205
+ for (const segment of segmentsOf(command)) {
206
+ const cd = cdTarget(segment);
207
+ if (cd !== null) dirs.push(cd);
208
+ dirs.push(...(gitCall(segment)?.dirs ?? []).filter(Boolean));
209
+ }
210
+ return dirs;
211
+ }