architecture-harness 0.7.0 → 0.9.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.
Files changed (43) hide show
  1. package/package.json +1 -1
  2. package/src/cli/bash-command-guard.mjs +129 -0
  3. package/src/cli/bash-command-guard.test.mjs +96 -0
  4. package/src/cli/bash-edit-guard.mjs +163 -0
  5. package/src/cli/bash-edit-guard.test.mjs +114 -0
  6. package/src/cli/budget-counter.mjs +40 -0
  7. package/src/cli/budget-counter.test.mjs +35 -0
  8. package/src/cli/budget-guard.mjs +56 -0
  9. package/src/cli/budget-guard.test.mjs +90 -0
  10. package/src/cli/budget.mjs +74 -0
  11. package/src/cli/budget.test.mjs +79 -0
  12. package/src/cli/check.mjs +197 -174
  13. package/src/cli/checkout-root.mjs +16 -0
  14. package/src/cli/cli.test.mjs +79 -0
  15. package/src/cli/decisions.mjs +5 -6
  16. package/src/cli/edit-batch-guard.mjs +77 -0
  17. package/src/cli/edit-batch-guard.test.mjs +131 -0
  18. package/src/cli/edit-batch-state.mjs +57 -0
  19. package/src/cli/generated-file-guard.mjs +81 -0
  20. package/src/cli/generated-file-guard.test.mjs +104 -0
  21. package/src/cli/ignored-paths.mjs +29 -0
  22. package/src/cli/ignored-paths.test.mjs +44 -0
  23. package/src/cli/powershell-command.mjs +57 -0
  24. package/src/cli/powershell-command.test.mjs +52 -0
  25. package/src/cli/qc.mjs +10 -2
  26. package/src/cli/repo-files.mjs +65 -0
  27. package/src/cli/repo-files.test.mjs +78 -0
  28. package/src/cli/shell-command.mjs +221 -0
  29. package/src/cli/shell-command.test.mjs +118 -0
  30. package/src/cli/work-order-guard.mjs +19 -21
  31. package/src/cli/work-order-guard.test.mjs +18 -0
  32. package/src/cli/work-order-manifest.mjs +14 -0
  33. package/src/cli/worktree-isolation.mjs +3 -1
  34. package/src/cli/worktree-isolation.test.mjs +13 -0
  35. package/src/cli/worktree.mjs +145 -0
  36. package/src/cli/worktree.test.mjs +110 -0
  37. package/src/config.mjs +9 -0
  38. package/src/enforcement-map.mjs +2 -1
  39. package/src/gates/english-source.mjs +13 -9
  40. package/src/gates/english-source.test.mjs +19 -1
  41. package/src/generated-markers.mjs +16 -0
  42. package/src/glob.mjs +23 -0
  43. package/templates/CLAUDE.md +1 -1
@@ -0,0 +1,57 @@
1
+ // A fragment that reads a PowerShell command the way shell-command.mjs reads a POSIX one, for the
2
+ // Bash edit guard. It shares that parser and its git vocabulary, and an unknown name counts as a write.
3
+
4
+ import { GIT_READS, commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
5
+
6
+ const DIALECT = { escape: "`" };
7
+ const NULL_DEVICES = new Set(["$null", "/dev/null", "nul"]);
8
+
9
+ /** Approved verbs that only read, and the cmdlets and aliases that only read or print. */
10
+ const READ_VERBS = new Set([
11
+ "get", "test", "select", "measure", "format", "compare", "find", "resolve", "convertto",
12
+ "convertfrom", "sort", "group", "where", "join", "split",
13
+ ]);
14
+ const READ_NAMES = new Set([
15
+ "write-output", "write-host", "out-null", "out-string", "out-host", "ls", "dir", "gci", "cat",
16
+ "gc", "type", "sls", "select", "where", "?", "sort", "measure", "pwd", "gl", "echo", "write",
17
+ "gi", "gp", "gcm", "gm", "ft", "fl", "popd", "pop-location",
18
+ ]);
19
+ const LOCATION_NAMES = new Set(["cd", "chdir", "sl", "set-location", "pushd", "push-location"]);
20
+ const PATH_PARAMETERS = new Set(["-path", "-literalpath"]);
21
+
22
+ /** @returns the directory a location change moves to, or null when the segment is none. */
23
+ function locationTarget(segment) {
24
+ const [program, ...args] = commandWords(segment);
25
+ if (!LOCATION_NAMES.has(program?.toLowerCase())) return null;
26
+ for (let i = 0; i < args.length; i++) {
27
+ if (PATH_PARAMETERS.has(args[i].toLowerCase())) return args[i + 1] ?? "~";
28
+ if (!args[i].startsWith("-")) return args[i];
29
+ }
30
+ return "~";
31
+ }
32
+
33
+ function isReadOnly(segment) {
34
+ if (segment.redirects.some((file) => !NULL_DEVICES.has(file.toLowerCase()))) return false;
35
+ // A script block can hold any command, so a segment that carries one is judged a write.
36
+ if (segment.words.some((word) => word.includes("{"))) return false;
37
+ if (locationTarget(segment) !== null) return true;
38
+ const git = gitCall(segment);
39
+ if (git) return GIT_READS.has(git.sub);
40
+ const name = commandWords(segment)[0]?.toLowerCase() ?? "";
41
+ const [verb, noun] = name.split("-");
42
+ return READ_NAMES.has(name) || (noun !== undefined && READ_VERBS.has(verb));
43
+ }
44
+
45
+ /** False only when every segment is known to read, so an unknown command counts as a write. */
46
+ export const mayWrite = (command) => !segmentsOf(command, DIALECT).every(isReadOnly);
47
+
48
+ /** Every directory the command names through a location change or `git -C`, in order, as written. */
49
+ export function checkoutDirs(command) {
50
+ const dirs = [];
51
+ for (const segment of segmentsOf(command, DIALECT)) {
52
+ const target = locationTarget(segment);
53
+ if (target !== null) dirs.push(target);
54
+ dirs.push(...(gitCall(segment)?.dirs ?? []).filter(Boolean));
55
+ }
56
+ return dirs;
57
+ }
@@ -0,0 +1,52 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkoutDirs, mayWrite } from "./powershell-command.mjs";
4
+
5
+ test("a PowerShell command that only reads skips the check, in any letter case", () => {
6
+ for (const command of [
7
+ "Get-ChildItem -Recurse src",
8
+ "get-content a.txt | select-string foo",
9
+ "Test-Path C:\\repo\\a.txt",
10
+ "Get-Content a.txt | Measure-Object -Line",
11
+ "Get-Process | Format-Table Name",
12
+ "Write-Output done",
13
+ 'git status; git diff --stat; git log --oneline -5',
14
+ "Get-Date > $null",
15
+ "Get-Item x 2>$null",
16
+ "Set-Location C:\\repo; Get-Location",
17
+ "ls; cat a.txt; pwd",
18
+ ]) {
19
+ assert.equal(mayWrite(command), false, command);
20
+ }
21
+ });
22
+
23
+ test("a PowerShell write, an unknown command and a script block are never skipped", () => {
24
+ for (const command of [
25
+ "Set-Content a.txt x",
26
+ "Add-Content a.txt x",
27
+ "Get-Content a.txt | Out-File b.txt",
28
+ "Get-Date > C:\\repo\\d.txt",
29
+ "Write-Output x >> log.txt",
30
+ "New-Item -ItemType File a.txt",
31
+ "Copy-Item a b",
32
+ "Move-Item a b",
33
+ "Remove-Item -Recurse -Force build",
34
+ "Rename-Item a b",
35
+ 'git commit -m "x"',
36
+ "git checkout main -- src",
37
+ "node scripts/codemod.mjs",
38
+ "Get-ChildItem | Where-Object { Remove-Item $_ }",
39
+ "Get-ChildItem | ForEach-Object Name",
40
+ "& C:\\tools\\fix.ps1",
41
+ ]) {
42
+ assert.equal(mayWrite(command), true, command);
43
+ }
44
+ });
45
+
46
+ test("the checkout directories are each location change and each git -C directory, with backslashes kept", () => {
47
+ assert.deepEqual(
48
+ checkoutDirs('Set-Location C:\\repo\\a; git -C "C:\\b c" status; cd ..\\d; Push-Location -Path C:\\e; popd'),
49
+ ["C:\\repo\\a", "C:\\b c", "..\\d", "C:\\e"],
50
+ );
51
+ assert.deepEqual(checkoutDirs("Get-ChildItem"), []);
52
+ });
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,65 @@
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 { globMatcher } 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
+ const ignoredBy = globMatcher;
15
+
16
+ // `-t` tags each entry. `R` is a tracked file gone from the working tree and `S` is skip-worktree, so neither is on disk.
17
+ const NOT_ON_DISK = new Set(["R", "S"]);
18
+
19
+ /** @returns {Promise<string[] | null>} null when `root` is in no git work tree */
20
+ async function gitListing(root, pathspecs) {
21
+ const args = ["--literal-pathspecs", "ls-files", "-z", "-t", "--cached", "--deleted", "--others", "--exclude-standard"];
22
+ if (pathspecs) args.push("--", ...pathspecs);
23
+ try {
24
+ const { stdout } = await execFileAsync("git", args, { cwd: root, maxBuffer: MAX_BUFFER });
25
+ const entries = stdout.split("\0").filter((entry) => entry.length > 2);
26
+ const gone = new Set(entries.filter((entry) => NOT_ON_DISK.has(entry[0])).map((entry) => entry.slice(2)));
27
+ return entries.map((entry) => entry.slice(2)).filter((file) => !gone.has(file));
28
+ } catch {
29
+ return null;
30
+ }
31
+ }
32
+
33
+ /** The walk outside git: every file, with `.git` and each ignored folder pruned. */
34
+ async function walkListing(root, pathspecs, ignored) {
35
+ const files = [];
36
+ async function visit(rel) {
37
+ for (const entry of await readdir(path.join(root, rel), { withFileTypes: true }).catch(() => [])) {
38
+ const child = rel ? `${rel}/${entry.name}` : entry.name;
39
+ if (!entry.isDirectory()) files.push(child);
40
+ else if (entry.name !== ".git" && !ignored(`${child}/`)) await visit(child);
41
+ }
42
+ }
43
+ if (!pathspecs) await visit("");
44
+ for (const spec of pathspecs ?? []) {
45
+ const found = await stat(path.join(root, spec)).catch(() => null);
46
+ if (found?.isDirectory()) await visit(spec);
47
+ else if (found) files.push(spec);
48
+ }
49
+ return files;
50
+ }
51
+
52
+ /**
53
+ * Tracked files and untracked files git does not ignore, then minus `ignores`.
54
+ * @param {string} root the repository root that `qc.config.json` sits in
55
+ * @param {{ignores?: string[], pathspecs?: string[]}} [options] pathspecs are literal, relative to `root`
56
+ * @returns {Promise<string[]>} forward-slash paths relative to `root`, sorted
57
+ */
58
+ export async function repoFiles(root, { ignores = [], pathspecs } = {}) {
59
+ if (pathspecs?.length === 0) return [];
60
+ const ignored = ignoredBy(ignores);
61
+ const listed = (await gitListing(root, pathspecs)) ?? (await walkListing(root, pathspecs, ignored));
62
+ // A trailing slash is an untracked nested repository, which git lists as one entry.
63
+ const files = listed.filter((file) => file !== "" && !file.endsWith("/") && !ignored(file));
64
+ return [...new Set(files)].sort();
65
+ }
@@ -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,221 @@
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
+ const POSIX_ESCAPE = "\\";
29
+
30
+ /**
31
+ * @param dialect `escape` is the escape character: a backslash for a POSIX shell, a backtick for PowerShell.
32
+ * @returns {Segment[]} the segments between unquoted `;`, `&`, `&&`, `|`, `||`, parentheses and newlines.
33
+ */
34
+ export function segmentsOf(command, { escape = POSIX_ESCAPE } = {}) {
35
+ const segments = [];
36
+ let words = [];
37
+ let redirects = [];
38
+ let word = "";
39
+ let inWord = false;
40
+ let quote = null;
41
+ let target = null;
42
+ let heredocs = [];
43
+
44
+ const endWord = () => {
45
+ if (!inWord) return;
46
+ if (target === "out") redirects.push(word);
47
+ else if (target !== "in") words.push(word);
48
+ target = null;
49
+ word = "";
50
+ inWord = false;
51
+ };
52
+ const endSegment = () => {
53
+ endWord();
54
+ if (words.length > 0 || redirects.length > 0) segments.push({ words, redirects });
55
+ words = [];
56
+ redirects = [];
57
+ };
58
+
59
+ let i = 0;
60
+ while (i < command.length) {
61
+ const c = command[i];
62
+ const next = command[i + 1];
63
+ if (quote === "'") {
64
+ if (c === "'") quote = null;
65
+ else word += c;
66
+ i++;
67
+ } else if (quote === '"') {
68
+ // Inside double quotes a backslash escapes only these, so a Windows path keeps its separators.
69
+ // A backtick escapes any character.
70
+ if (c === escape && next !== undefined && (escape !== POSIX_ESCAPE || '$`"\\\n'.includes(next))) {
71
+ word += next;
72
+ i += 2;
73
+ } else {
74
+ if (c === '"') quote = null;
75
+ else word += c;
76
+ i++;
77
+ }
78
+ } else if (c === "'" || c === '"') {
79
+ quote = c;
80
+ inWord = true;
81
+ i++;
82
+ } else if (c === escape) {
83
+ if (next !== "\n") word += next ?? "";
84
+ inWord = next !== "\n" || inWord;
85
+ i += 2;
86
+ } else if (c === "\n") {
87
+ endSegment();
88
+ i = skipHeredocs(command, i + 1, heredocs);
89
+ heredocs = [];
90
+ } else if (BLANK.test(c) || c === "\r") {
91
+ endWord();
92
+ i++;
93
+ } else if (c === ";" || c === "(" || c === ")") {
94
+ endSegment();
95
+ i++;
96
+ } else if (c === "|") {
97
+ endSegment();
98
+ i += next === "|" ? 2 : 1;
99
+ } else if (c === "&") {
100
+ if (next === ">") {
101
+ endWord();
102
+ target = "out";
103
+ i += command[i + 2] === ">" ? 3 : 2;
104
+ } else {
105
+ endSegment();
106
+ i += next === "&" ? 2 : 1;
107
+ }
108
+ } else if (c === ">") {
109
+ // A leading descriptor number belongs to the operator, as in `2>file`.
110
+ if (inWord && /^\d+$/.test(word)) {
111
+ word = "";
112
+ inWord = false;
113
+ } else {
114
+ endWord();
115
+ }
116
+ i += next === ">" ? 2 : 1;
117
+ if (command[i] === "&") {
118
+ i++;
119
+ while (/[\d-]/.test(command[i] ?? "")) i++;
120
+ } else {
121
+ target = "out";
122
+ }
123
+ } else if (c === "<") {
124
+ endWord();
125
+ if (next === "<" && command[i + 2] !== "<") {
126
+ i += 2;
127
+ const strip = command[i] === "-";
128
+ if (strip) i++;
129
+ while (BLANK.test(command[i] ?? "")) i++;
130
+ let delimiter = "";
131
+ while (i < command.length && !WORD_END.test(command[i])) {
132
+ if (!`'"\\`.includes(command[i])) delimiter += command[i];
133
+ i++;
134
+ }
135
+ heredocs.push({ delimiter, strip });
136
+ } else {
137
+ i += next === "<" ? 3 : 1;
138
+ target = "in";
139
+ }
140
+ } else {
141
+ word += c;
142
+ inWord = true;
143
+ i++;
144
+ }
145
+ }
146
+ endSegment();
147
+ return segments;
148
+ }
149
+
150
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
151
+
152
+ /** The words after any leading `NAME=value` assignments. */
153
+ export const commandWords = (segment) => {
154
+ const start = segment.words.findIndex((word) => !ASSIGNMENT.test(word));
155
+ return start === -1 ? [] : segment.words.slice(start);
156
+ };
157
+
158
+ const isGit = (word) => /(^|[\\/])git(\.exe)?$/i.test(word ?? "");
159
+
160
+ /**
161
+ * @returns the git subcommand, each `-C` directory, each `-c` setting and the words after the
162
+ * subcommand, or null when the segment is no git call.
163
+ */
164
+ export function gitCall(segment) {
165
+ const [program, ...words] = commandWords(segment);
166
+ if (!isGit(program)) return null;
167
+ const dirs = [];
168
+ const configs = [];
169
+ for (let i = 0; i < words.length; i++) {
170
+ const word = words[i];
171
+ if (word === "-C") dirs.push(words[++i]);
172
+ else if (word === "-c") configs.push(words[++i]);
173
+ else if (!word.startsWith("-")) return { sub: word, dirs, configs, args: words.slice(i + 1) };
174
+ }
175
+ return { sub: null, dirs, configs, args: [] };
176
+ }
177
+
178
+ /** @returns the directory a `cd` or `pushd` segment moves to, or null. */
179
+ export function cdTarget(segment) {
180
+ const [program, target] = commandWords(segment);
181
+ return program === "cd" || program === "pushd" ? (target ?? "~") : null;
182
+ }
183
+
184
+ const READ_PROGRAMS = new Set([
185
+ "ls", "cat", "head", "tail", "grep", "egrep", "fgrep", "rg", "wc", "pwd", "echo", "printf",
186
+ "cut", "tr", "jq", "which", "type", "stat", "file", "du", "df", "date", "basename",
187
+ "dirname", "realpath", "readlink", "diff", "cmp", "true", "false", "test", "[", "popd",
188
+ ]);
189
+ export const GIT_READS = new Set([
190
+ "status", "diff", "log", "show", "rev-parse", "ls-files", "grep", "blame", "branch", "remote",
191
+ "fetch", "describe", "shortlog", "config",
192
+ ]);
193
+ const SED_IN_PLACE = /^(-[A-Za-z]*i|--in-place)/;
194
+
195
+ /** True when the segment writes a file through a redirect other than the null device. */
196
+ export const writesRedirect = (segment) => segment.redirects.some((file) => file !== "/dev/null");
197
+
198
+ /** True when one segment only reads, or only moves between directories. */
199
+ export function isReadOnly(segment) {
200
+ if (writesRedirect(segment)) return false;
201
+ if (cdTarget(segment) !== null) return true;
202
+ const git = gitCall(segment);
203
+ if (git) return GIT_READS.has(git.sub);
204
+ const [program, ...args] = commandWords(segment);
205
+ if (program === "sed") return !args.some((arg) => SED_IN_PLACE.test(arg));
206
+ return READ_PROGRAMS.has(program);
207
+ }
208
+
209
+ /** False only when every segment is known to read, so an unknown program counts as a write. */
210
+ export const mayWrite = (command) => !segmentsOf(command).every(isReadOnly);
211
+
212
+ /** Every directory the command names through `cd` or `git -C`, in order, as written. */
213
+ export function checkoutDirs(command) {
214
+ const dirs = [];
215
+ for (const segment of segmentsOf(command)) {
216
+ const cd = cdTarget(segment);
217
+ if (cd !== null) dirs.push(cd);
218
+ dirs.push(...(gitCall(segment)?.dirs ?? []).filter(Boolean));
219
+ }
220
+ return dirs;
221
+ }
@@ -0,0 +1,118 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { checkoutDirs, gitCall, isReadOnly, mayWrite, segmentsOf } from "./shell-command.mjs";
4
+
5
+ const wordsOf = (command) => segmentsOf(command).map((segment) => segment.words);
6
+
7
+ test("a command splits on unquoted separators, and a quoted separator stays in its word", () => {
8
+ assert.deepEqual(wordsOf(`git add -A && git commit -m "a; b && c" | cat; echo x || true`), [
9
+ ["git", "add", "-A"],
10
+ ["git", "commit", "-m", "a; b && c"],
11
+ ["cat"],
12
+ ["echo", "x"],
13
+ ["true"],
14
+ ]);
15
+ });
16
+
17
+ test("a heredoc body belongs to its command, not to new segments", () => {
18
+ const command = "git commit -F - <<'EOF'\nsubject; with && tokens | here\n\nbody line\nEOF\ngit push";
19
+ assert.deepEqual(wordsOf(command), [["git", "commit", "-F", "-"], ["git", "push"]]);
20
+ });
21
+
22
+ test("a heredoc inside a quoted command substitution stays one word", () => {
23
+ const command = `git commit -m "$(cat <<'EOF'\nsubject; don't split\nEOF\n)"`;
24
+ assert.equal(segmentsOf(command).length, 1);
25
+ });
26
+
27
+ test("a redirect target is recorded apart from the words, and a descriptor copy is not a target", () => {
28
+ const [segment] = segmentsOf("echo x > out.txt 2>/dev/null");
29
+ assert.deepEqual(segment.words, ["echo", "x"]);
30
+ assert.deepEqual(segment.redirects, ["out.txt", "/dev/null"]);
31
+ assert.deepEqual(segmentsOf("npm test 2>&1")[0].redirects, []);
32
+ assert.deepEqual(segmentsOf("cat log >> all.log")[0].redirects, ["all.log"]);
33
+ });
34
+
35
+ test("a git call names its subcommand and every -C directory", () => {
36
+ const [segment] = segmentsOf(`GIT_PAGER=cat git -C "C:/a b" -c core.x=y --no-pager commit -m x`);
37
+ assert.deepEqual(gitCall(segment), { sub: "commit", dirs: ["C:/a b"], configs: ["core.x=y"], args: ["-m", "x"] });
38
+ assert.equal(gitCall(segmentsOf("gitk --all")[0]), null);
39
+ });
40
+
41
+ test("a backslash inside double quotes stays, unless it escapes a quote, a dollar, or itself", () => {
42
+ const [segment] = segmentsOf(String.raw`git -C "C:\Users\me\wt" commit -m "say \"hi\" for \$5"`);
43
+ assert.deepEqual(segment.words.slice(2), [String.raw`C:\Users\me\wt`, "commit", "-m", 'say "hi" for $5']);
44
+ });
45
+
46
+ test("a read-only command is one whose every segment reads", () => {
47
+ for (const command of [
48
+ "ls -la",
49
+ "cat a.txt | grep b",
50
+ "git status --porcelain",
51
+ "git diff HEAD~1 -- src",
52
+ "rg foo src",
53
+ "sed -n '1,5p' file.ts",
54
+ "head -5 f 2>/dev/null",
55
+ "cd /repo && git log --oneline 2>&1 | tail -3",
56
+ ]) {
57
+ assert.equal(mayWrite(command), false, command);
58
+ }
59
+ });
60
+
61
+ test("any segment that can write makes the command a possible write", () => {
62
+ for (const command of [
63
+ "sed -i 's/a/b/' f.ts",
64
+ "sed -ni.bak 's/a/b/p' f.ts",
65
+ "echo x > f.ts",
66
+ "node scripts/codemod.mjs",
67
+ "python x.py",
68
+ "mv a b",
69
+ "cp a b",
70
+ "rm a",
71
+ "git checkout main -- src",
72
+ "pnpm codegen",
73
+ "npx prettier --write .",
74
+ "ls && tee out.txt",
75
+ "touch f",
76
+ "sort -o out.txt in.txt",
77
+ "uniq in.txt out.txt",
78
+ ]) {
79
+ assert.equal(mayWrite(command), true, command);
80
+ }
81
+ });
82
+
83
+ test("isReadOnly judges one segment", () => {
84
+ assert.equal(isReadOnly(segmentsOf("grep -rn x src")[0]), true);
85
+ assert.equal(isReadOnly(segmentsOf("grep -rn x src > hits.txt")[0]), false);
86
+ });
87
+
88
+ test("the checkout directories are every cd target and every git -C directory, in order", () => {
89
+ assert.deepEqual(checkoutDirs(`cd /repo/a && git -C "../b c" status; git -C /repo/d commit -m x`), [
90
+ "/repo/a",
91
+ "../b c",
92
+ "/repo/d",
93
+ ]);
94
+ assert.deepEqual(checkoutDirs("ls"), []);
95
+ });
96
+
97
+ test("a git call carries each -c setting and the words after its subcommand", () => {
98
+ const [segment] = segmentsOf(`git -c core.hooksPath=/dev/null -C repo commit -m "a b" --no-verify`);
99
+ assert.deepEqual(gitCall(segment), {
100
+ sub: "commit",
101
+ dirs: ["repo"],
102
+ configs: ["core.hooksPath=/dev/null"],
103
+ args: ["-m", "a b", "--no-verify"],
104
+ });
105
+ assert.deepEqual(gitCall(segmentsOf("git --version")[0]), { sub: null, dirs: [], configs: [], args: [] });
106
+ });
107
+
108
+ test("the PowerShell escape keeps a backslash literal and escapes with a backtick", () => {
109
+ const powershell = { escape: "`" };
110
+ assert.deepEqual(
111
+ segmentsOf('Set-Content C:\\a\\b.txt "x`"y" ; Get-Item `$HOME', powershell).map((segment) => segment.words),
112
+ [
113
+ ["Set-Content", "C:\\a\\b.txt", 'x"y'],
114
+ ["Get-Item", "$HOME"],
115
+ ],
116
+ );
117
+ assert.deepEqual(segmentsOf("Get-Date > C:\\out\\d.txt", powershell)[0].redirects, ["C:\\out\\d.txt"]);
118
+ });