@a2f0/agent-tool 0.1.59 → 0.1.60

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.59",
3
+ "version": "0.1.60",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
@@ -8,7 +8,13 @@ export interface StepResolution { findings: StepFinding[]; errors: string[] }
8
8
 
9
9
  const MAX_DEPTH = 32;
10
10
  const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh"]);
11
- const WRAPPERS = new Set(["exec", "command", "time", "nohup", "nice"]);
11
+ /** Commands that run the command after them, with their options that take a separate value. */
12
+ const WRAPPERS: ReadonlyMap<string, ReadonlySet<string>> = new Map(Object.entries({
13
+ exec: ["-a"], command: [], nohup: [], nice: ["-n", "--adjustment"], time: ["-o", "--output", "-f", "--format"],
14
+ timeout: ["-s", "--signal", "-k", "--kill-after"], stdbuf: ["-i", "-o", "-e", "--input", "--output", "--error"],
15
+ env: ["-u", "--unset", "-C", "--chdir", "-S", "--split-string", "-a", "--argv0", "--env0-from", "-P", "-L", "-U"],
16
+ xargs: ["-a", "--arg-file", "-d", "--delimiter", "-E", "-I", "-J", "-L", "--max-lines", "-n", "--max-args", "-P", "--max-procs", "-R", "-S", "-s", "--max-chars", "--process-slot-var"],
17
+ }).map(([name, values]) => [name, new Set(values)]));
12
18
  const KEYWORDS = new Set(["if", "then", "else", "elif", "do", "while", "until", "!", "{", "}", "fi", "done", "esac"]);
13
19
  const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
14
20
 
@@ -34,11 +40,14 @@ interface Context { root: string; seen: Set<string>; findings: StepFinding[]; er
34
40
 
35
41
  /**
36
42
  * Follow a declared push-gate step through package scripts, shell strings,
37
- * and `agent-tool run-group` plans to every test runner, build, or dependency
38
- * install it reaches. Executables and script files are leaves: their contents
39
- * are not inspected. Workspace filters resolve to every workspace package
40
- * declaring the script, which can over-report but never misses one. A command
41
- * that both builds and tests, such as `cargo test`, is reported once, as a test.
43
+ * command runners such as `env`, `uv run`, or `python -m`, and `agent-tool
44
+ * run-group` plans to every test runner, build, or dependency install it
45
+ * reaches. Executables and script files are leaves: their contents are not
46
+ * inspected. Workspace filters resolve to every workspace package declaring
47
+ * the script, which can over-report but never misses one. A command that both
48
+ * builds and tests, such as `cargo test`, is reported once, as a test; a runner
49
+ * that installs before running its command, such as `uv run pytest`, is
50
+ * reported as an install and its command as what it does.
42
51
  */
43
52
  export function resolveStep(root: string, command: string[]): StepResolution {
44
53
  const context: Context = { root, seen: new Set(), findings: [], errors: [] };
@@ -51,16 +60,34 @@ function report(context: Context, kind: StepFinding["kind"], runner: string, cha
51
60
  context.findings.push({ kind, runner, chain: chain.at(-1) === runner ? chain : [...chain, runner] });
52
61
  }
53
62
 
63
+ /**
64
+ * The options in one word, as getopt reads them: `--name=value`, `--name`
65
+ * with its value in the next word, or bundled short options (`-iC dir`,
66
+ * `-Cdir`), where the first that takes a value takes the rest of the word or,
67
+ * when nothing is left, the next word, which `next` supplies.
68
+ */
69
+ function optionWords(word: string, takesValue: ReadonlySet<string>, next: () => string | undefined): [string, string | undefined][] {
70
+ if (word.startsWith("--") || word.length <= 2) {
71
+ const equals = word.indexOf("=");
72
+ return equals > 0 ? [[word.slice(0, equals), word.slice(equals + 1)]] : [[word, takesValue.has(word) ? next() : undefined]];
73
+ }
74
+ const found: [string, string | undefined][] = [];
75
+ for (let at = 1; at < word.length; at++) {
76
+ const name = `-${word[at]}`;
77
+ if (!takesValue.has(name)) { found.push([name, undefined]); continue; }
78
+ const rest = word.slice(at + 1).replace(/^=/, "");
79
+ found.push([name, rest || next()]);
80
+ break;
81
+ }
82
+ return found;
83
+ }
84
+
54
85
  /** Skip leading options, consuming the separate value of the ones that take one; returns the options seen. */
55
86
  function options(argv: string[], spec: Tool): { rest: string[]; seen: Map<string, string | true> } {
56
87
  const seen = new Map<string, string | true>();
57
88
  let index = 0;
58
89
  while (index < argv.length && argv[index]!.startsWith("-") && argv[index] !== "--") {
59
- const value = argv[index]!;
60
- const equals = value.indexOf("=");
61
- if (equals > 0) seen.set(value.slice(0, equals), value.slice(equals + 1));
62
- else if (spec.values.has(value) && index + 1 < argv.length) { seen.set(value, argv[index + 1]!); index++; }
63
- else seen.set(value, true);
90
+ for (const [name, value] of optionWords(argv[index]!, spec.values, () => index + 1 < argv.length ? argv[++index] : undefined)) seen.set(name, value ?? true);
64
91
  index++;
65
92
  }
66
93
  return { rest: argv.slice(index), seen };
@@ -120,10 +147,10 @@ function workspaceDirectories(context: Context, root = context.root): string[] {
120
147
  return [...directories];
121
148
  }
122
149
 
123
- /** Package managers run scripts from the nearest `package.json` at or above the directory, within the repository. */
124
- function packageRoot(context: Context, directory: string): string {
150
+ /** Package managers run scripts from the nearest `package.json` (or other `manifest`) at or above the directory, within the repository. */
151
+ function packageRoot(context: Context, directory: string, manifest = "package.json"): string {
125
152
  let current = directory;
126
- while (!existsSync(path.join(current, "package.json")) && current !== context.root && current.startsWith(`${context.root}${path.sep}`)) current = path.dirname(current);
153
+ while (!existsSync(path.join(current, manifest)) && current !== context.root && current.startsWith(`${context.root}${path.sep}`)) current = path.dirname(current);
127
154
  return current;
128
155
  }
129
156
 
@@ -148,12 +175,46 @@ function runScript(context: Context, name: string, args: string[], directory: st
148
175
  if (!found && fallback) visit(context, fallback, directory, chain, depth + 1);
149
176
  }
150
177
 
151
- function visit(context: Context, input: string[], cwd: string, chain: string[], depth: number): void {
152
- if (depth > MAX_DEPTH) { context.errors.push(`Resolution deeper than ${MAX_DEPTH} levels: ${chain.join(" -> ")}`); return; }
178
+ /**
179
+ * Strip what runs a command rather than being it: `NAME=value` assignments and
180
+ * wrappers such as `env -u NAME`, `nice -n 5`, or `timeout 60`, with their
181
+ * options. Returns the command and the directory it runs in (`env -C`), or
182
+ * null when nothing runs (`command -v`).
183
+ */
184
+ function unwrap(input: string[], cwd: string): { argv: string[]; cwd: string } | null {
153
185
  const argv = [...input];
154
- while (argv.length && (ASSIGNMENT.test(argv[0]!) || WRAPPERS.has(argv[0]!))) argv.shift();
155
- if (argv[0] === "env") { argv.shift(); while (argv.length && (argv[0]!.startsWith("-") || ASSIGNMENT.test(argv[0]!))) argv.shift(); }
156
- if (!argv.length) return;
186
+ let directory = cwd;
187
+ while (argv.length) {
188
+ if (ASSIGNMENT.test(argv[0]!)) { argv.shift(); continue; }
189
+ const wrapper = path.basename(argv[0]!);
190
+ const takesValue = WRAPPERS.get(wrapper);
191
+ if (!takesValue) break;
192
+ argv.shift();
193
+ while (argv[0]?.startsWith("-")) {
194
+ const option = argv.shift()!;
195
+ if (option === "--") break;
196
+ for (const [name, value] of optionWords(option, takesValue, () => argv.shift())) {
197
+ // `command -v` and `command -V` only describe the command.
198
+ if (wrapper === "command" && (name === "-v" || name === "-V")) return null;
199
+ if (wrapper !== "env" || value === undefined) continue;
200
+ if (name === "-C" || name === "--chdir") directory = path.resolve(directory, value);
201
+ // `env -S 'a b'` reads its words as if they were given separately.
202
+ else if (name === "-S" || name === "--split-string") argv.unshift(...splitShell(value).flat());
203
+ }
204
+ }
205
+ // `timeout` takes its duration before the command.
206
+ if (wrapper === "timeout") argv.shift();
207
+ }
208
+ return { argv, cwd: directory };
209
+ }
210
+
211
+ function visit(context: Context, input: string[], invokedIn: string, chain: string[], depth: number): void {
212
+ if (depth > MAX_DEPTH) { context.errors.push(`Resolution deeper than ${MAX_DEPTH} levels: ${chain.join(" -> ")}`); return; }
213
+ const unwrapped = unwrap(input, invokedIn);
214
+ if (unwrapped?.argv.length) dispatch(context, unwrapped.argv, unwrapped.cwd, chain, depth);
215
+ }
216
+
217
+ function dispatch(context: Context, argv: string[], cwd: string, chain: string[], depth: number): void {
157
218
  // `npx vitest@4` names the runner with a version selector.
158
219
  const name = path.basename(argv[0]!).replace(/(?<=.)@[^@/]*$/, "");
159
220
  const args = argv.slice(1);
@@ -167,9 +228,15 @@ function visit(context: Context, input: string[], cwd: string, chain: string[],
167
228
  else if (name === "bunx" || name === "npx") execute(context, args, cwd, chain, depth);
168
229
  else if (name === "npm" || name === "pnpm" || name === "yarn") packageManager(context, name, args, cwd, chain, depth, text);
169
230
  else if (name === "turbo") turbo(context, args, cwd, chain, text);
231
+ else if (name === "uv" || name === "uvx") uv(context, name === "uvx" ? ["tool", "run", ...args] : args, cwd, chain, depth, text);
232
+ else if (name === "poetry" || name === "pdm" || name === "hatch" || name === "pipenv" || name === "pipx") pythonProject(context, name, args, cwd, chain, depth, text);
233
+ else if (/^python[\d.]*$/.test(name)) python(context, args, cwd, chain, depth, text);
234
+ else if (name === "coverage") { if (args[0] === "run") coverageRun(context, args.slice(1), cwd, chain, depth, text); }
235
+ else if (name === "mise") mise(context, args, cwd, chain, depth);
170
236
  else if (testRunner(name, args)) report(context, "test", text, chain);
171
237
  else if (builds(name, args)) report(context, "build", text, chain);
172
- else if (["pod", "bundle", "pip", "pip3"].includes(name) && args[0] === "install") report(context, "install", text, chain);
238
+ else if ((name === "pod" || name === "bundle") && args[0] === "install") report(context, "install", text, chain);
239
+ else if (/^pip[\d.]*$/.test(name) && options(args, PYTHON_TOOLS.pip).rest[0] === "install" && !previews("pip", "install", args)) report(context, "install", text, chain);
173
240
  else if (name === "bundle" && args[0] === "exec") visit(context, args.slice(1), cwd, chain, depth + 1);
174
241
  }
175
242
 
@@ -217,14 +284,13 @@ const GRADLE_TEST = gradleTask("test\\w*");
217
284
  const GRADLE_BUILD = gradleTask("assemble\\w*|build(?:Needed|Dependents)?|bundle\\w*|install\\w*");
218
285
 
219
286
  function testRunner(name: string, args: string[]): boolean {
220
- if (["jest", "vitest", "mocha", "ava", "maestro", "detox", "pytest", "rspec"].includes(name)) return true;
287
+ if (["jest", "vitest", "mocha", "ava", "maestro", "detox", "pytest", "py.test", "tox", "nox", "rspec"].includes(name)) return true;
221
288
  const first = subcommand(name, args);
222
289
  if (name === "node") return args.some(arg => arg === "--test" || arg.startsWith("--test="));
223
290
  if (["playwright", "deno", "go", "swift"].includes(name)) return first === "test";
224
291
  if (name === "cargo") return first === "test" || first === "nextest";
225
292
  if (name === "gradle" || name === "gradlew") return positionals(args, GRADLE_VALUES).some(task => GRADLE_TEST.test(task));
226
293
  if (name === "xcodebuild") return xcodebuildActions(args).some(action => action === "test" || action === "test-without-building");
227
- if (/^python[\d.]*$/.test(name)) return args[0] === "-m" && args[1] === "pytest";
228
294
  return false;
229
295
  }
230
296
 
@@ -234,12 +300,12 @@ const WEBPACK_OTHER = new Set(["serve", "server", "s", "info", "i", "configtest"
234
300
  const XCODEBUILD_OTHER = new Set(["-list", "-showBuildSettings", "-showBuildSettingsForIndex", "-showsdks", "-showdestinations", "-showTestPlans", "-version", "-usage", "-help", "-license", "-checkFirstLaunchStatus", "-runFirstLaunch", "-resolvePackageDependencies", "-exportArchive", "-create-xcframework", "-find-executable", "-find-library", "-downloadPlatform", "-downloadAllPlatforms", "-importPlatform"]);
235
301
 
236
302
  /**
237
- * Bundlers, framework builds, native compilers, and image builds. Static
238
- * checks are not builds: `tsc` (whether `--noEmit` or `-b`), `cargo
239
- * check|clippy|fmt`, linters, and formatters.
303
+ * Bundlers, framework builds, native compilers, image builds, and Python
304
+ * package builds. Static checks are not builds: `tsc` (whether `--noEmit` or
305
+ * `-b`), `cargo check|clippy|fmt`, linters, formatters, and type checkers.
240
306
  */
241
307
  function builds(name: string, args: string[]): boolean {
242
- if (name === "rollup" || name === "tsup") return true;
308
+ if (name === "rollup" || name === "tsup" || name === "pyproject-build") return true;
243
309
  if (name === "esbuild") return args.some(arg => arg === "--bundle" || /^--out(?:file|dir)(?:=|$)/.test(arg));
244
310
  const first = subcommand(name, args);
245
311
  if (name === "webpack" || name === "webpack-cli") return !WEBPACK_OTHER.has(first ?? "");
@@ -394,25 +460,22 @@ function bun(context: Context, args: string[], cwd: string, chain: string[], dep
394
460
  else runScript(context, sub, rest.slice(1), directory, workspaceScoped(seen, TOOLS.bun), chain, depth, null);
395
461
  }
396
462
 
397
- /** npm reads its own options anywhere before `--`, so `npm run check --workspaces` selects workspaces. */
398
- function npmOptions(args: string[]): { rest: string[]; seen: Map<string, string | true> } {
463
+ /** Options read anywhere before `--`, as npm reads `npm run check --workspaces` and mise `mise x node@24 -C dir -- …`; returns the positional words, then `--` and what follows it. */
464
+ function scatteredOptions(args: string[], spec: Tool): { rest: string[]; seen: Map<string, string | true> } {
399
465
  const separator = args.indexOf("--");
400
466
  const before = separator === -1 ? args : args.slice(0, separator);
401
467
  const seen = new Map<string, string | true>(), positional: string[] = [];
402
468
  for (let index = 0; index < before.length; index++) {
403
469
  const value = before[index]!;
404
470
  if (!value.startsWith("-")) { positional.push(value); continue; }
405
- const equals = value.indexOf("=");
406
- if (equals > 0) seen.set(value.slice(0, equals), value.slice(equals + 1));
407
- else if (TOOLS.npm.values.has(value) && index + 1 < before.length) seen.set(value, before[++index]!);
408
- else seen.set(value, true);
471
+ for (const [name, found] of optionWords(value, spec.values, () => index + 1 < before.length ? before[++index] : undefined)) seen.set(name, found ?? true);
409
472
  }
410
473
  return { rest: separator === -1 ? positional : [...positional, ...args.slice(separator)], seen };
411
474
  }
412
475
 
413
476
  function packageManager(context: Context, manager: "npm" | "pnpm" | "yarn", args: string[], cwd: string, chain: string[], depth: number, text: string): void {
414
477
  const spec = TOOLS[manager];
415
- const { rest, seen } = manager === "npm" ? npmOptions(args) : options(args, spec);
478
+ const { rest, seen } = manager === "npm" ? scatteredOptions(args, spec) : options(args, spec);
416
479
  const directory = directoryOption(cwd, seen);
417
480
  const workspaces = workspaceScoped(seen, spec);
418
481
  const sub = rest[0];
@@ -435,6 +498,169 @@ function packageManager(context: Context, manager: "npm" | "pnpm" | "yarn", args
435
498
  else if (manager !== "npm") runScript(context, sub, rest.slice(1), directory, workspaces, chain, depth, rest);
436
499
  }
437
500
 
501
+ /** Options that take a separate value, for each Python runner and project manager, before and after its subcommand. */
502
+ const PYTHON_TOOLS = {
503
+ uv: tool([
504
+ "--directory", "--project", "--cache-dir", "--color", "--config-file", "--allow-insecure-host",
505
+ "-w", "--with", "--with-editable", "--with-requirements", "--from", "-c", "--constraints", "-b", "--build-constraints", "--overrides",
506
+ "--extra", "--no-extra", "--group", "--no-group", "--only-group", "--package", "--env-file", "-p", "--python", "--python-platform", "--torch-backend",
507
+ "--index", "--default-index", "-i", "--index-url", "--extra-index-url", "-f", "--find-links", "--index-strategy", "--keyring-provider",
508
+ "-P", "--upgrade-package", "--resolution", "--prerelease", "--fork-strategy", "--exclude-newer", "--exclude-newer-package", "--no-sources-package",
509
+ "--reinstall-package", "--link-mode", "-C", "--config-setting", "--config-settings-package", "--no-build-isolation-package", "--no-build-package",
510
+ "--no-binary-package", "--refresh-package",
511
+ // Hidden from `--help`, but they still take a value.
512
+ "--python-preference", "--preview-features", "--python-fetch", "--max-recursion-depth",
513
+ ]),
514
+ poetry: tool(["-C", "--directory", "-P", "--project"]),
515
+ // pdm takes `-p`, `--project`, and `--venv` only after its subcommand (`pdm -p api run` fails), but reading them before it too means a misplaced one never hides the command.
516
+ pdm: tool(["-c", "--config", "-p", "--project", "--venv"]),
517
+ pdmRun: tool(["-p", "--project", "-k", "--skip", "--venv", "--env", "--env-file", "--working-dir"]),
518
+ hatch: tool(["-e", "--env", "-p", "--project", "--data-dir", "--cache-dir", "--config"]),
519
+ hatchEnvRun: tool(["-e", "--env", "-i", "--include", "-x", "--exclude", "-f", "--filter"]),
520
+ pipenv: tool(["--python", "--pypi-mirror"]),
521
+ pipx: tool(["--python-args", "--with", "--spec", "--python", "--fetch-python", "--index-url", "--pip-args", "--cooldown", "--backend"]),
522
+ pip: tool(["--python", "--log", "--log-file", "--proxy", "--retries", "--resume-retries", "--timeout", "--exists-action", "--trusted-host", "--cert", "--client-cert", "--cache-dir", "--use-feature", "--use-deprecated", "--keyring-provider"]),
523
+ coverage: tool(["--rcfile", "--source", "--include", "--omit", "--context", "--concurrency", "--data-file", "--debug", "--save-signal"]),
524
+ } as const;
525
+ const MISE = tool(["-C", "--cd", "-E", "--env", "-j", "--jobs", "-c", "--command", "--allow-env", "--allow-net", "--allow-read", "--allow-write", "--secrets"]);
526
+ /** Subcommands that install a Python project's dependencies into its environment. */
527
+ const PYTHON_INSTALLS: Partial<Record<keyof typeof PYTHON_TOOLS, readonly string[]>> = {
528
+ uv: ["sync", "add", "remove"], poetry: ["install", "sync", "add", "remove", "update"], pdm: ["install", "sync", "add", "remove", "update"],
529
+ // `pipenv upgrade` only updates the lockfile; `pipenv update` also syncs.
530
+ pipenv: ["install", "sync", "update"],
531
+ };
532
+ /**
533
+ * A Python install that only previews or changes declarations and locks:
534
+ * `--dry-run`, `uv sync --check`, `uv add|remove` with `--no-sync` or
535
+ * `--frozen`, `pdm add|remove|update --no-sync`, or poetry's `--lock`. `pdm
536
+ * install --check` checks the lockfile and then installs.
537
+ */
538
+ function previews(tool: string, sub: string | undefined, args: string[]): boolean {
539
+ return args.some(arg => arg === "--dry-run"
540
+ || (tool === "uv" && sub === "sync" && arg === "--check")
541
+ || (tool === "uv" && (sub === "add" || sub === "remove") && (arg === "--no-sync" || arg === "--frozen"))
542
+ || (tool === "pdm" && (sub === "add" || sub === "remove" || sub === "update") && arg === "--no-sync")
543
+ || (tool === "poetry" && arg === "--lock"));
544
+ }
545
+ /** `uvx` and `pipx run` take a requirement for the command they run, such as `ruff==0.6`, `ruff>=0.6`, or `ruff[all]`; the command is its name. */
546
+ const requirement = ([first, ...rest]: string[]) => first === undefined ? [] : [first.replace(/^([A-Za-z0-9][\w.-]*)\s*(?:\[[^\]]*\])?\s*(?:[=<>!~].*)?$/s, "$1"), ...rest];
547
+
548
+ /** The directory a command runs in after options such as `--directory` or `-C`, applied in order. */
549
+ function movedTo(cwd: string, names: string[], ...seen: Map<string, string | true>[]): string {
550
+ let directory = cwd;
551
+ for (const options of seen) for (const name of names) { const value = options.get(name); if (typeof value === "string") directory = path.resolve(directory, value); }
552
+ return directory;
553
+ }
554
+
555
+ /**
556
+ * `uv run` syncs the project's environment before its command, even with
557
+ * `--frozen` or `--locked`, unless `--no-sync`, `--no-project`, or a script
558
+ * (`--script`, `--gui-script`) skips it; `-m` runs a module. `UV_NO_SYNC` is
559
+ * not read: whether a command sees a variable cannot be told from the step, so
560
+ * only the flag counts. `uvx` is `uv tool run`, whose cached tool environment, like `npx`'s
561
+ * download, is not counted as an install; neither are `--with` requirements.
562
+ */
563
+ function uv(context: Context, args: string[], cwd: string, chain: string[], depth: number, text: string): void {
564
+ const spec = PYTHON_TOOLS.uv;
565
+ const { rest, seen } = options(args, spec);
566
+ const sub = rest[0], words = rest.slice(1);
567
+ // uv reads its global options anywhere, so `uv tool --no-cache run` is `uv tool run`.
568
+ const tool = sub === "tool" ? options(words, spec) : { rest: [], seen: new Map<string, string | true>() };
569
+ if (sub === "run" || tool.rest[0] === "run") {
570
+ const run = scriptOptions(sub === "run" ? words : tool.rest.slice(1), spec);
571
+ const flags = new Set([...seen.keys(), ...tool.seen.keys(), ...run.seen.keys()]);
572
+ // Even without a command, `uv run` syncs before it lists what it could run.
573
+ if (sub === "run" && !["--no-sync", "--no-project", "-s", "--script", "--gui-script"].some(flag => flags.has(flag))) report(context, "install", text, chain);
574
+ if (!run.rest.length) return;
575
+ const module = sub === "run" && (run.seen.has("-m") || run.seen.has("--module"));
576
+ visit(context, module ? ["python", "-m", ...run.rest] : sub === "run" ? run.rest : requirement(run.rest), movedTo(cwd, ["--directory"], seen, tool.seen, run.seen), chain, depth + 1);
577
+ } else if ((PYTHON_INSTALLS.uv!.includes(sub ?? "") || (sub === "pip" && ["install", "sync"].includes(options(words, spec).rest[0] ?? ""))) && !previews("uv", sub, words)) report(context, "install", text, chain);
578
+ else if (sub === "build") report(context, "build", text, chain);
579
+ }
580
+
581
+ /**
582
+ * `poetry run`, `pdm run`, `pipenv run`, and `pipx run` run their command as
583
+ * given; `hatch run` and `hatch env run` first create and sync the
584
+ * environment, and `hatch run` takes leading `+`/`-` matrix selectors and an
585
+ * `env:` prefix. `poetry -C` moves the command; `pdm run` keeps its directory
586
+ * unless `--working-dir` names one, relative to the project root (`-p`, else
587
+ * the nearest `pyproject.toml`). Script names they look up in
588
+ * `pyproject.toml`, `hatch.toml`, or `Pipfile` are leaves.
589
+ */
590
+ function pythonProject(context: Context, name: "poetry" | "pdm" | "hatch" | "pipenv" | "pipx", args: string[], cwd: string, chain: string[], depth: number, text: string): void {
591
+ const spec = PYTHON_TOOLS[name];
592
+ const { rest, seen } = options(args, spec);
593
+ const sub = rest[0], words = rest.slice(1);
594
+ if (sub === "run" || (name === "hatch" && sub === "env" && words[0] === "run")) {
595
+ let run: { rest: string[]; seen: Map<string, string | true> };
596
+ if (name === "hatch" && sub === "run") {
597
+ let at = 0;
598
+ while (at < words.length && /^[+-]/.test(words[at]!) && words[at] !== "--") at++;
599
+ const command = words[at] === "--" ? words.slice(at + 1) : words.slice(at);
600
+ const prefix = command[0]?.indexOf(":") ?? -1;
601
+ run = { rest: prefix === -1 ? command : [command[0]!.slice(prefix + 1), ...command.slice(1)], seen: new Map() };
602
+ } else run = scriptOptions(sub === "run" ? words : words.slice(1), name === "hatch" ? PYTHON_TOOLS.hatchEnvRun : name === "pdm" ? PYTHON_TOOLS.pdmRun : spec);
603
+ if (!run.rest.length) return;
604
+ if (name === "hatch") report(context, "install", text, chain);
605
+ let directory = movedTo(cwd, name === "poetry" ? ["-C", "--directory"] : [], seen, run.seen);
606
+ const working = name === "pdm" ? run.seen.get("--working-dir") : undefined;
607
+ if (typeof working === "string") {
608
+ const project = run.seen.get("--project") ?? run.seen.get("-p") ?? seen.get("--project") ?? seen.get("-p");
609
+ directory = path.resolve(typeof project === "string" ? path.resolve(cwd, project) : packageRoot(context, cwd, "pyproject.toml"), working);
610
+ }
611
+ visit(context, name === "pipx" ? requirement(run.rest) : run.rest, directory, chain, depth + 1);
612
+ } else if (PYTHON_INSTALLS[name]?.includes(sub ?? "")) { if (!previews(name, sub, words)) report(context, "install", text, chain); }
613
+ else if (sub === "build" && name !== "pipenv" && name !== "pipx") report(context, "build", text, chain);
614
+ else if (name === "hatch" && sub === "test") report(context, "test", text, chain);
615
+ }
616
+
617
+ /**
618
+ * `python [options] -m <module> [args]` runs the module as its command would:
619
+ * `-m pytest` is a test run and `-m pip install` an install. `-m unittest`
620
+ * tests and `-m build` builds. Code (`-c`), standard input, and script files
621
+ * are leaves.
622
+ */
623
+ function python(context: Context, args: string[], cwd: string, chain: string[], depth: number, text: string): void {
624
+ for (let index = 0; index < args.length; index++) {
625
+ const word = args[index]!;
626
+ if (word === "--check-hash-based-pycs") { index++; continue; }
627
+ // A script file, `-` for standard input, or a long option such as `--version`.
628
+ if (!/^-[^-]/.test(word)) return;
629
+ for (let at = 1; at < word.length; at++) {
630
+ const flag = word[at]!;
631
+ if (!"cmWX".includes(flag)) continue;
632
+ // An option that takes a value takes the rest of its word, else the next word.
633
+ const value = at + 1 < word.length ? word.slice(at + 1) : args[++index];
634
+ if (flag === "c" || value === undefined) return;
635
+ if (flag === "m") {
636
+ if (value === "build") report(context, "build", text, chain);
637
+ else if (value === "unittest") report(context, "test", text, chain);
638
+ else visit(context, [value, ...args.slice(index + 1)], cwd, chain, depth + 1);
639
+ return;
640
+ }
641
+ break;
642
+ }
643
+ }
644
+ }
645
+
646
+ /** `coverage run -m <module>` runs the module as `python -m` does; a program file is a leaf. */
647
+ function coverageRun(context: Context, args: string[], cwd: string, chain: string[], depth: number, text: string): void {
648
+ const { rest, seen } = options(args, PYTHON_TOOLS.coverage);
649
+ if ((seen.has("-m") || seen.has("--module")) && rest.length) python(context, ["-m", ...rest], cwd, chain, depth, text);
650
+ }
651
+
652
+ /** `mise exec|x [tool@version...] -- <command>` runs its command, and `-c` a shell string, in the directory `-C` names. */
653
+ function mise(context: Context, args: string[], cwd: string, chain: string[], depth: number): void {
654
+ const { rest, seen } = options(args, MISE);
655
+ if (rest[0] !== "exec" && rest[0] !== "x") return;
656
+ const exec = scatteredOptions(rest.slice(1), MISE);
657
+ const directory = movedTo(cwd, ["-C", "--cd"], seen, exec.seen);
658
+ const call = exec.seen.get("-c") ?? exec.seen.get("--command");
659
+ if (typeof call === "string") visitShell(context, call, directory, chain, depth + 1);
660
+ const separator = exec.rest.indexOf("--");
661
+ if (separator !== -1 && separator + 1 < exec.rest.length) visit(context, exec.rest.slice(separator + 1), directory, chain, depth + 1);
662
+ }
663
+
438
664
  /** The checkout holding `directory`: this repository's root when it is inside it, else the nearest directory with a `.git`. */
439
665
  function checkoutOf(context: Context, directory: string): string {
440
666
  if (directory === context.root || directory.startsWith(`${context.root}${path.sep}`)) {