@kaynooo/cli-guard 0.8.0 → 0.9.1

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 (3) hide show
  1. package/README.md +2 -0
  2. package/dist/cli.js +368 -70
  3. package/package.json +8 -8
package/README.md CHANGED
@@ -14,10 +14,12 @@ guard check --json --cwd "$PWD" - < command.txt
14
14
  | --- | --- | --- |
15
15
  | `remote` | `ssh`, `scp`, `sftp`, `mosh`, `rsync` to a host, `DOCKER_HOST=ssh://`, `docker -H ssh://` | `src/remote.ts` |
16
16
  | `git` | `git stash` (pointing at `proof`, `base`, a commit first or `git worktree add`), `git add -A`/`.`/`-u`, `git commit -a` in any flag cluster, `git push` the user did not ask for, `git push --tags` without `--atomic` | `src/git.ts` |
17
+ | `destructive` | `git reset --hard`, discarding the whole tree (`checkout -- .`, `checkout -f`, `restore .`, `switch -f`), `git clean -f`, a force push (`--force`, `-f`, `--mirror`, `+refspec`; `--force-with-lease` passes), `git branch -D`, a `git rebase` (`--continue` and `--abort` pass), `filter-branch`, `rm -r` on `/`, `~`, `$HOME`, `.`, `..`, `*` or a top-level directory, a download piped into a shell (`curl ... \| sh`, `bash <(curl ...)`); each refusal names the safe route: a commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` | `src/destructive.ts` |
17
18
  | `commit` | a commit message breaking the format: no Conventional Commit title, a trailer, a body over two lines, a bullet list, a hard wrap; `-m`, `-F <file>` and `-F -` with a heredoc are read; the refusal spells the rule out and points at `gc` | `src/commit.ts`, the validator in `@kaynooo/cli-git` |
18
19
  | `sql` | a SQL client, console or dump tool fed a write (INSERT, UPDATE, DELETE, DDL, migrations, fixtures) outside a test database | `@kaynooo/cli-db` (`src/clients.ts`, `src/guard.ts`) |
19
20
  | `env` | a command reading, writing or printing an env file or the whole environment; `guard path` refuses a file tool opening one | `@kaynooo/cli-env` (`src/guard.ts`) |
20
21
  | `package-manager` | an install with another manager than the nearest lockfile pins, when it cannot be translated | `@kaynooo/cli-pkg` (`src/pin.ts`) |
22
+ | `pkg` | on the hook only, an install `pkg check` refuses or cannot check, pointing at `pkg <name>` before adding it | `@kaynooo/cli-pkg` |
21
23
  | `edit` | when `sub` is installed, a `sed -i` and a python, bun or node script replacing text in a file (`-c`, `-e` or a heredoc), handing over the `sub` command doing the same where its `s` commands or `.replace(...)` calls take literals | `src/replace.ts` |
22
24
 
23
25
  Every rule reads the command with one shell parser (`packages/kit/src/shell.ts`): quotes, heredoc bodies (text, never commands), `env`/`sudo`/`command` wrappers and subshells.
package/dist/cli.js CHANGED
@@ -1,12 +1,11 @@
1
- #!/usr/bin/env bun
1
+ #!/usr/bin/env -S bun --no-env-file
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import { appendFileSync as appendFileSync2, existsSync, mkdirSync as mkdirSync2, readFileSync, rmSync, statSync, writeFileSync } from "fs";
5
+ import { appendFileSync as appendFileSync2, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, rmSync, statSync, writeFileSync } from "fs";
6
6
  import { homedir as homedir2 } from "os";
7
- import { dirname as dirname2 } from "path";
8
- import process10 from "process";
9
-
7
+ import { dirname as dirname4 } from "path";
8
+ import process11 from "process";
10
9
  // ../kit/src/args.ts
11
10
  import process5 from "process";
12
11
  import { parseArgs } from "util";
@@ -306,17 +305,23 @@ var FULL_STOP = /\.$/;
306
305
  function usageLine(usage, colors = paint(process3.stdout)) {
307
306
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
308
307
  }
309
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
310
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
308
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
309
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
311
310
  `);
312
311
  }
312
+ function exitRows(exits, colors = paint(process3.stdout)) {
313
+ if (exits.length === 0)
314
+ return [];
315
+ const width = Math.max(...exits.map(([code]) => String(code).length));
316
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
317
+ }
313
318
  function replacesRows(replaces, colors = paint(process3.stdout)) {
314
319
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
315
320
  }
316
321
  function wantsHelpJson(env = process3.env) {
317
322
  return env.KIT_HELP === "json";
318
323
  }
319
- function description(usage, { examples = [], replaces } = {}) {
324
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
320
325
  const lines = usage.replace(USAGE_PREFIX, "").split(`
321
326
  `);
322
327
  const first = lines[0];
@@ -327,7 +332,9 @@ function description(usage, { examples = [], replaces } = {}) {
327
332
  synopsis: colon === -1 ? first : first.slice(0, colon),
328
333
  summary: colon === -1 ? fallback : first.slice(colon + 2),
329
334
  ...replaces === undefined ? {} : { replaces },
330
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
335
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
336
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
337
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
331
338
  };
332
339
  }
333
340
  function exampleRows(examples, colors = paint(process3.stdout)) {
@@ -452,7 +459,7 @@ function parse(args, usage, options, settings = {}) {
452
459
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
453
460
  let parsed;
454
461
  try {
455
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
462
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
456
463
  } catch (error) {
457
464
  const message = parseError(error);
458
465
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -460,7 +467,7 @@ function parse(args, usage, options, settings = {}) {
460
467
  const values = parsed.values;
461
468
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
462
469
  if (values.help === true) {
463
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
470
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
464
471
  throw new HelpShown;
465
472
  }
466
473
  checkChoices(parsed.values, all);
@@ -502,6 +509,18 @@ function listed(options, allowNegative) {
502
509
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
503
510
  }));
504
511
  }
512
+ function withAliases(args, options) {
513
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
514
+ if (named.size === 0)
515
+ return args;
516
+ const separator = args.indexOf("--");
517
+ const own = separator === -1 ? args : args.slice(0, separator);
518
+ return [...own.map((arg) => {
519
+ const at = arg.indexOf("=");
520
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
521
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
522
+ }), ...separator === -1 ? [] : args.slice(separator)];
523
+ }
505
524
  function withBare(args, options) {
506
525
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
507
526
  if (bare.size === 0)
@@ -682,6 +701,8 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
682
701
  var RESET_STYLE = `${ESC}[0m`;
683
702
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
684
703
  // ../kit/src/cli.ts
704
+ import { readFileSync, realpathSync } from "fs";
705
+ import { dirname as dirname2, join as join2 } from "path";
685
706
  import process8 from "process";
686
707
 
687
708
  // ../kit/src/usage.ts
@@ -978,10 +999,22 @@ async function printCandidates(found) {
978
999
  console.log(line);
979
1000
  return 0;
980
1001
  }
1002
+ function packageVersion(entry = Bun.main) {
1003
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
1004
+ try {
1005
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
1006
+ if (typeof version === "string")
1007
+ return version;
1008
+ } catch {}
1009
+ if (dirname2(dir) === dir)
1010
+ return "0.0.0";
1011
+ }
1012
+ }
981
1013
  async function runCli(cli, argv = process8.argv.slice(2)) {
1014
+ const version = cli.version ?? packageVersion();
982
1015
  if (argv[0] === COMPLETE)
983
1016
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
984
- const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(cli.version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version: cli.version, redact: cli.redact });
1017
+ const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
985
1018
  if (cli.usage !== false) {
986
1019
  try {
987
1020
  recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
@@ -1010,9 +1043,6 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
1010
1043
  var {Glob } = globalThis.Bun;
1011
1044
  var SESSION_FILES = new Glob("*.json");
1012
1045
  var ACCOUNT_DIRS = new Glob("*/sessions");
1013
- // package.json
1014
- var version = "0.8.0";
1015
-
1016
1046
  // ../kit/src/shell.ts
1017
1047
  var SEPARATORS = new Set([`
1018
1048
  `, ";", "|"]);
@@ -1042,13 +1072,20 @@ var OCTAL = /^[0-7]{1,3}/;
1042
1072
  var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
1043
1073
  var MAX_DEPTH = 8;
1044
1074
  var MAX_BRACES = 256;
1045
- var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh"]);
1046
- var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, "su", "runuser"]);
1075
+ var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
1076
+ var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
1077
+ var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
1078
+ var POWERSHELL_COMMAND = /^-c(?:o(?:m(?:m(?:a(?:nd?)?)?)?)?)?$/i;
1079
+ var POWERSHELL = new Set(["pwsh", "powershell"]);
1080
+ var FUNCTION_DEFINITION = /^[\w.:-]+\(\)\{?$/;
1081
+ var FUNCTION_NAME = /^[\w.:-]+$/;
1047
1082
  var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
1083
+ var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
1084
+ var LET_PIECE = /^\s*let\s/;
1048
1085
  var PRINTERS = new Set(["echo", "printf"]);
1049
1086
  var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
1050
- function wrapper(short = "", long = [], operands = 0) {
1051
- return { short, long, operands };
1087
+ function wrapper(short = "", long = [], operands = 0, runsString = false) {
1088
+ return { short, long, operands, runsString };
1052
1089
  }
1053
1090
  var WRAPPERS = new Map([
1054
1091
  ["command", wrapper()],
@@ -1066,6 +1103,11 @@ var WRAPPERS = new Map([
1066
1103
  ["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
1067
1104
  ["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
1068
1105
  ["chroot", wrapper("", ["--userspec", "--groups"], 1)],
1106
+ ["watch", wrapper("n", ["--interval"], 0, true)],
1107
+ ["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
1108
+ ["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
1109
+ ["unbuffer", wrapper()],
1110
+ ["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
1069
1111
  ["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
1070
1112
  ]);
1071
1113
  function closerOf(quote) {
@@ -1137,10 +1179,19 @@ function splitCommand(command) {
1137
1179
  quote = char;
1138
1180
  continue;
1139
1181
  }
1182
+ if (char === "$" && command[i + 1] === "[") {
1183
+ const close = command.indexOf("]", i);
1184
+ i = close === -1 ? command.length : close;
1185
+ continue;
1186
+ }
1140
1187
  if (char === "`") {
1141
1188
  i = closingBackquote(command, i);
1142
1189
  continue;
1143
1190
  }
1191
+ if (command.startsWith("((", char === "$" ? i + 1 : i) && (char === "$" || startsComment(command, i))) {
1192
+ i = closingParen(command, char === "$" ? i + 1 : i);
1193
+ continue;
1194
+ }
1144
1195
  if (char === "#" && startsComment(command, i)) {
1145
1196
  const newline = command.indexOf(`
1146
1197
  `, i);
@@ -1149,7 +1200,7 @@ function splitCommand(command) {
1149
1200
  i = end - 1;
1150
1201
  continue;
1151
1202
  }
1152
- const heredoc = char === "<" && command[i + 1] === "<" && command[i + 2] !== "<" ? HEREDOC.exec(command.slice(i)) : null;
1203
+ const heredoc = char === "<" && command[i + 1] === "<" && command[i + 2] !== "<" && !LET_PIECE.test(command.slice(start, i)) ? HEREDOC.exec(command.slice(i)) : null;
1153
1204
  if (heredoc) {
1154
1205
  heredocs.push({ word: heredoc[2] ?? heredoc[3] ?? heredoc[4] ?? "", stripsTabs: heredoc[1] === "-", isQuoted: heredoc[4] === undefined });
1155
1206
  i += heredoc[0].length - 1;
@@ -1411,11 +1462,23 @@ function skipOptions(tokens, spec) {
1411
1462
  function parseCommand(text) {
1412
1463
  const tokens = tokenize(text);
1413
1464
  const assignments = [];
1465
+ const strings = [];
1414
1466
  let isWrapped = false;
1415
1467
  for (;; ) {
1416
1468
  const first = tokens[0] ?? "";
1417
1469
  const spec = WRAPPERS.get(first.split("/").pop() ?? "");
1418
- if (OPENERS.test(first)) {
1470
+ if (first === "function" && tokens.length > 1) {
1471
+ isWrapped = true;
1472
+ tokens.splice(0, 2);
1473
+ if (tokens[0] === "()")
1474
+ tokens.shift();
1475
+ } else if (FUNCTION_DEFINITION.test(first)) {
1476
+ isWrapped = true;
1477
+ tokens.shift();
1478
+ } else if (tokens[1] === "()" && FUNCTION_NAME.test(first)) {
1479
+ isWrapped = true;
1480
+ tokens.splice(0, 2);
1481
+ } else if (OPENERS.test(first)) {
1419
1482
  isWrapped = true;
1420
1483
  const rest = first.replace(OPENERS, "");
1421
1484
  if (rest === "")
@@ -1438,6 +1501,8 @@ function parseCommand(text) {
1438
1501
  isWrapped = true;
1439
1502
  tokens.shift();
1440
1503
  skipOptions(tokens, spec);
1504
+ if (spec.runsString && WHITESPACE.test(tokens[0] ?? ""))
1505
+ strings.push(tokens[0] ?? "");
1441
1506
  } else {
1442
1507
  break;
1443
1508
  }
@@ -1449,7 +1514,7 @@ function parseCommand(text) {
1449
1514
  if (tokens.length > 0)
1450
1515
  tokens.splice(-1, 1, ...last === "" ? [] : [last]);
1451
1516
  const [program = "", ...args] = tokens;
1452
- return { program: program.split("/").pop() ?? "", args, assignments, isWrapped };
1517
+ return { program: program.split("/").pop() ?? "", args, assignments, isWrapped, strings };
1453
1518
  }
1454
1519
  function shellQuote(word) {
1455
1520
  return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
@@ -1463,7 +1528,8 @@ function commandStrings(tokens) {
1463
1528
  const name = token.split("/").pop() ?? "";
1464
1529
  if (!COMMAND_STRING_PROGRAMS.has(name))
1465
1530
  continue;
1466
- const isUser = name === "su" || name === "runuser";
1531
+ const isScanned = SCANNED_PROGRAMS.has(name);
1532
+ const isPowershell = POWERSHELL.has(name);
1467
1533
  let isValue = false;
1468
1534
  for (let j = i + 1;j < tokens.length; j++) {
1469
1535
  const option = tokens[j] ?? "";
@@ -1471,19 +1537,20 @@ function commandStrings(tokens) {
1471
1537
  isValue = false;
1472
1538
  continue;
1473
1539
  }
1474
- if (SHELL_VALUE_OPTIONS.has(option)) {
1540
+ if (SHELL_VALUE_OPTIONS.has(option) || name === "fish" && FISH_VALUE_OPTIONS.has(option)) {
1475
1541
  isValue = true;
1476
1542
  continue;
1477
1543
  }
1478
- if (option.startsWith("--command=")) {
1479
- found.push(option.slice("--command=".length));
1544
+ if (option.startsWith("--command=") || option.startsWith("--commands=")) {
1545
+ found.push(option.slice(option.indexOf("=") + 1));
1480
1546
  break;
1481
1547
  }
1482
- if (option === "--command" || !option.startsWith("--") && option.startsWith("-") && option.slice(1).includes("c")) {
1483
- found.push(tokens[j + 1] ?? "");
1548
+ const isCommandOption = isPowershell ? POWERSHELL_COMMAND.test(option) : !option.startsWith("--") && option.startsWith("-") && option.slice(1).includes("c");
1549
+ if (option === "--command" || option === "--commands" || isCommandOption) {
1550
+ found.push(isPowershell ? tokens.slice(j + 1).join(" ") : tokens[j + 1] ?? "");
1484
1551
  break;
1485
1552
  }
1486
- if (!option.startsWith("-") && !isUser)
1553
+ if (!option.startsWith("-") && !isScanned)
1487
1554
  break;
1488
1555
  }
1489
1556
  }
@@ -1516,8 +1583,8 @@ function findExecs(args) {
1516
1583
  }
1517
1584
  function nestedCommands(piece, previous) {
1518
1585
  const tokens = tokenize(piece.command);
1519
- const { program, args } = parseCommand(piece.command);
1520
- const found = commandStrings(tokens);
1586
+ const { program, args, strings } = parseCommand(piece.command);
1587
+ const found = [...commandStrings(tokens), ...strings];
1521
1588
  if (program === "eval")
1522
1589
  found.push(args.join(" "));
1523
1590
  if (program === "find")
@@ -1800,12 +1867,18 @@ var STATEMENT_LONGS = new Set(["--command", "--execute"]);
1800
1867
  var DATABASE_LONGS = new Set(["--dbname", "--database"]);
1801
1868
  var VALUE_LONGS = new Set(["--host", "--port", "--username", "--user", "--output", "--set", "--variable", "--field-separator", "--record-separator", "--pset", "--log-file", "--socket"]);
1802
1869
  var PRINTERS2 = new Set(["echo", "printf"]);
1870
+ var FILE_LONGS = new Set(["--file"]);
1871
+ var KNOWN_LONGS = [...STATEMENT_LONGS, ...FILE_LONGS, ...DATABASE_LONGS, ...VALUE_LONGS];
1803
1872
  var LIST_OPTIONS = new Set(["-l", "--list"]);
1804
1873
  var REDIRECT_ONLY2 = /^\d*(?:>|>>|>&|&>|>\||<&|<>)$/;
1805
1874
  var REDIRECT_START2 = /^\d*>|^&>/;
1806
1875
  var URL_DATABASE = /^[a-z][a-z\d+.-]*:\/\/[^/]*\/([^?#]*)/i;
1807
1876
  var WRITING_CONSOLE = /^(?:doctrine:(?:migrations:(?:migrate|execute|rollup)|schema:(?:update|create|drop)|database:(?:create|drop)|fixtures:load)|migrate(?::\w+)?|db:(?:seed|wipe))$/;
1808
1877
  var TEST_SCOPED = /(?:^|[^a-z])test/i;
1878
+ var ASSIGNMENT2 = /^([A-Z_]\w*)=/i;
1879
+ var TARGET_VARIABLE = /(?:^|_|^PG)(?:ENV|ENVIRONMENT|DATABASE|DB|DBNAME|DSN|URL)$|^(?:DB|DATABASE)_NAME$/i;
1880
+ var USER_OPTION = /^(?:-[uU]|--user(?:name)?)$/;
1881
+ var USER_ATTACHED = /^(?:--user(?:name)?=|-[uU].)/;
1809
1882
  var SHOT_STACK = /\.worktrees\/[^/\s]+\/shot(?:\/|$)|--shot(?:-|$)/;
1810
1883
  var DEVICE_PATH = /^\/(?:dev|proc|sys)\//;
1811
1884
  var STDIN_PATHS = new Set(["-", "/dev/stdin"]);
@@ -1828,6 +1901,12 @@ function programOf(word) {
1828
1901
  function databaseOf(operand) {
1829
1902
  return URL_DATABASE.exec(operand)?.[1] ?? operand;
1830
1903
  }
1904
+ function fullOption(option) {
1905
+ if (KNOWN_LONGS.includes(option) || option.length < 4)
1906
+ return option;
1907
+ const candidates = KNOWN_LONGS.filter((each) => each.startsWith(option));
1908
+ return candidates.length === 1 ? candidates[0] : option;
1909
+ }
1831
1910
  function clientInput(name, args) {
1832
1911
  const input = { statements: [], files: [], databases: [], operands: [] };
1833
1912
  const valueShorts = VALUE_SHORTS[name] ?? "";
@@ -1851,7 +1930,8 @@ function clientInput(name, args) {
1851
1930
  } else if (REDIRECT_START2.test(arg)) {
1852
1931
  continue;
1853
1932
  } else if (arg.startsWith("--")) {
1854
- const [option = "", ...rest] = arg.split("=");
1933
+ const [spelled = "", ...rest] = arg.split("=");
1934
+ const option = fullOption(spelled);
1855
1935
  const attached = rest.length > 0 ? rest.join("=") : undefined;
1856
1936
  const value = attached ?? args[i + 1] ?? "";
1857
1937
  if (STATEMENT_LONGS.has(option))
@@ -1890,10 +1970,19 @@ function clientInput(name, args) {
1890
1970
  input.databases.push(databaseOf(input.operands[0]));
1891
1971
  return input;
1892
1972
  }
1973
+ function isTestWord(word) {
1974
+ const assignment = ASSIGNMENT2.exec(word);
1975
+ if (assignment !== null && !TARGET_VARIABLE.test(assignment[1] ?? ""))
1976
+ return false;
1977
+ return TEST_SCOPED.test(word) || SHOT_STACK.test(word);
1978
+ }
1979
+ function targetWords(words) {
1980
+ return words.filter((word, index) => !USER_OPTION.test(words[index - 1] ?? "") && !USER_ATTACHED.test(word));
1981
+ }
1893
1982
  function isTestScoped(words, client, input) {
1894
1983
  if (client === -1)
1895
- return words.some((word) => TEST_SCOPED.test(word) || SHOT_STACK.test(word));
1896
- return words.slice(0, client).some((word) => TEST_SCOPED.test(word) || SHOT_STACK.test(word)) || (input?.databases ?? []).some((name) => TEST_SCOPED.test(name));
1984
+ return targetWords(words).some(isTestWord);
1985
+ return targetWords(words.slice(0, client)).some(isTestWord) || (input?.databases ?? []).some((name) => TEST_SCOPED.test(name));
1897
1986
  }
1898
1987
  async function fileText(path, read) {
1899
1988
  return DEVICE_PATH.test(path) ? null : read(path);
@@ -1947,6 +2036,7 @@ var GIT_EXCLUDE = /^:(?:!|\^|\(exclude\))/;
1947
2036
  var ENV_PRINTERS = new Set(["env", "printenv"]);
1948
2037
  var DOCKER = new Set(["docker", "docker-compose"]);
1949
2038
  var SHELLS2 = new Set(["sh", "bash", "zsh", "ash"]);
2039
+ var SHELL_COMMAND_FLAG = /^-[abd-z]*c[a-z]*$/;
1950
2040
  var DOCKER_VALUE_OPTIONS = new Set(["-f", "--file", "-p", "--project-name", "--profile", "--env-file", "--project-directory", "--ansi", "--progress", "--parallel", "-H", "--host", "-c", "--context", "--config", "-l", "--log-level"]);
1951
2041
  var EXEC_VALUE_OPTIONS = new Set(["-e", "--env", "--env-file", "-u", "--user", "-w", "--workdir", "--index", "--detach-keys"]);
1952
2042
  var CONFIG_LISTS = new Set(["--services", "--volumes", "--profiles", "--images", "--networks", "--hash", "-q", "--quiet"]);
@@ -1963,8 +2053,9 @@ function firstOperand(words, valueOptions) {
1963
2053
  return words.length;
1964
2054
  }
1965
2055
  function printsEnv([program = "", ...args]) {
1966
- if (SHELLS2.has(program) && args[0] === "-c")
1967
- return splitCommand(args[1] ?? "").some((piece) => ENV_PRINTERS.has(tokenize(piece.command)[0] ?? ""));
2056
+ const flags = args.findIndex((arg) => !arg.startsWith("-") || SHELL_COMMAND_FLAG.test(arg));
2057
+ if (SHELLS2.has(program) && SHELL_COMMAND_FLAG.test(args[flags] ?? ""))
2058
+ return splitCommand(args[flags + 1] ?? "").some((piece) => ENV_PRINTERS.has(tokenize(piece.command)[0] ?? ""));
1968
2059
  return ENV_PRINTERS.has(program);
1969
2060
  }
1970
2061
  function dumpsContainerEnv(program, args) {
@@ -2190,7 +2281,7 @@ function searchesEnvNames(piece) {
2190
2281
  var ENV_NAME_IN_CODE = /(?:^|[^\w.-])(\.env(?:\.[\w.-]*\w)?|\.envrc)(?![\w-])/g;
2191
2282
  var PYTHON_ENVIRON = /\bos\.environ\b(?!\s*(?:\[|\.get\b))/;
2192
2283
  var VARIABLE = /\$(?:(\w+)|\{(\w+)\})/;
2193
- var ASSIGNMENT2 = /^\w+=/;
2284
+ var ASSIGNMENT3 = /^\w+=/;
2194
2285
  var MAX_VARIANTS = 64;
2195
2286
  var INTERPRETERS = new Set(["bun", "deno", "node", "python", "python3", "ruby", "perl", "php", "lua", "awk", "gawk"]);
2196
2287
  var CODE_OPTIONS = new Set(["-e", "-c", "-p", "-E", "-pe", "-r", "--eval", "--print", "--command"]);
@@ -2208,7 +2299,7 @@ function variablesOf(command) {
2208
2299
  for (const piece of splitCommand(command)) {
2209
2300
  const { program, args, assignments } = parseCommand(piece.command);
2210
2301
  const tokens = tokenize(piece.command);
2211
- const declared = DECLARERS.has(program) ? args.filter((arg) => ASSIGNMENT2.test(arg)) : [];
2302
+ const declared = DECLARERS.has(program) ? args.filter((arg) => ASSIGNMENT3.test(arg)) : [];
2212
2303
  for (const assignment of [...assignments, ...declared])
2213
2304
  add(assignment);
2214
2305
  if (tokens[0] === "for" && tokens[2] === "in" && tokens[1] !== undefined)
@@ -2275,7 +2366,7 @@ function parallelRunner(args) {
2275
2366
  function runnerReadsListedEnv(pieces, index, variables) {
2276
2367
  const command = pieces[index]?.command ?? "";
2277
2368
  const { program, args, isWrapped } = parseCommand(command);
2278
- const isXargs = isWrapped && tokenize(command).includes("xargs");
2369
+ const isXargs = isWrapped && tokenize(command).some((word) => word === "xargs" || word === "parallel");
2279
2370
  if (program !== "parallel" && !isXargs)
2280
2371
  return false;
2281
2372
  return !XARGS_SAFE.has(isXargs ? program : parallelRunner(args)) && listsEnvUpstream(pieces, index, variables);
@@ -2387,7 +2478,7 @@ function commitMessageViolation(message) {
2387
2478
  var FOLD_LINES = 150;
2388
2479
 
2389
2480
  // ../out/src/wrap.ts
2390
- var ASSIGNMENT3 = /^\w+=/;
2481
+ var ASSIGNMENT4 = /^\w+=/;
2391
2482
  var EXCLUDED = /(?:^|\s)(?:--json|--help|--version|-h|--watch(?:-?all|=\S*)?|--watchAll)(?:\s|$)/;
2392
2483
  var SHORT_WATCH = /(?:^|\s)(?:\S*\/)?(?:tsc|tsgo|vue-tsc|vitest|jest)\s(?:.*\s)?-w(?:\s|$)/;
2393
2484
  var LONG_RUNNING = /^(?:dev|watch|serve|start|up|run|preview|storybook)(?:[:-]\S*)?$/;
@@ -2488,7 +2579,7 @@ function withoutFilters(command) {
2488
2579
  return { rest, stages };
2489
2580
  }
2490
2581
  function listed2(words) {
2491
- const start = words.findIndex((word) => !ASSIGNMENT3.test(word));
2582
+ const start = words.findIndex((word) => !ASSIGNMENT4.test(word));
2492
2583
  const path = words[start];
2493
2584
  if (path === undefined)
2494
2585
  return false;
@@ -2509,12 +2600,15 @@ function shouldWrap(command) {
2509
2600
  function wrap(command) {
2510
2601
  const { rest, stages } = withoutFilters(command.trim());
2511
2602
  const out = ["out", ...stages.flatMap((stage) => ["--was", shellQuote(stage)]), "--"].join(" ");
2512
- if (scan(rest).segments.length <= 1 && !ASSIGNMENT3.test(rest))
2603
+ if (scan(rest).segments.length <= 1 && !ASSIGNMENT4.test(rest))
2513
2604
  return `${out} ${rest}`;
2514
2605
  return `${out} sh -c ${shellQuote(rest)}`;
2515
2606
  }
2516
2607
 
2517
2608
  // ../pkg/src/added.ts
2609
+ import { existsSync, readdirSync, readFileSync as readFileSync2 } from "fs";
2610
+ import { dirname as dirname3, join as join3 } from "path";
2611
+ import process10 from "process";
2518
2612
  var REDIRECT2 = /^\d*[<>]/;
2519
2613
  var BARE_REDIRECT = /^\d*(?:[<>]|>>)$/;
2520
2614
  var ADDS = {
@@ -2531,27 +2625,62 @@ var RUNS = {
2531
2625
  };
2532
2626
  var RUNNERS = new Set(["bunx", "npx"]);
2533
2627
  var PACKAGE_FLAGS = new Set(["-p", "--package"]);
2534
- var VALUE_FLAGS = new Set(["--cwd", "--filter", "-F", "--workspace", "--registry", "--prefix", "-C", "--dir", "--config", "--cache-dir", "--loglevel", "--tag", "--save-prefix", "--userconfig", "--omit", "--include", "--fetch-timeout", "--fetch-retries", "--install-strategy", "--cache", ...PACKAGE_FLAGS]);
2628
+ var VALUE_FLAGS = new Set(["--cwd", "--filter", "-F", "-c", "--call", "--workspace", "--registry", "--prefix", "-C", "--dir", "--config", "--cache-dir", "--loglevel", "--tag", "--save-prefix", "--userconfig", "--omit", "--include", "--fetch-timeout", "--fetch-retries", "--install-strategy", "--cache", ...PACKAGE_FLAGS]);
2535
2629
  var NOT_REGISTRY = /^(?:[./~]|file:|link:|portal:|workspace:|git[+:]|github:|gitlab:|bitbucket:|https?:)|\.tgz$|^[\w.-]+\/[\w.-]+(?:#.*)?$/;
2536
2630
  var NPM_ALIAS = /^(?:@[^/]+\/)?[^@]+@npm:(.+)$/;
2537
2631
  var PUBLISH = /\b(?:ft|cli\.ts)\s+release\b|\b(?:bun|npm|pnpm|yarn)\s+publish\b|\bjust\s+(?:patch|minor|major)\b/;
2632
+ var EXACT_SPEC = /^(?:@[^/]+\/)?[^@]+@\d+\.\d+\.\d+(?:[-+][\w.+-]+)?$/;
2633
+ function manifestName(folder) {
2634
+ try {
2635
+ const { name } = JSON.parse(readFileSync2(join3(folder, "package.json"), "utf8"));
2636
+ return typeof name === "string" ? name : undefined;
2637
+ } catch {
2638
+ return;
2639
+ }
2640
+ }
2641
+ function ownPackages() {
2642
+ const names = new Set;
2643
+ let folder = process10.cwd();
2644
+ while (true) {
2645
+ const name = manifestName(folder);
2646
+ if (name !== undefined)
2647
+ names.add(name);
2648
+ for (const member of existsSync(join3(folder, "packages")) ? readdirSync(join3(folder, "packages")) : []) {
2649
+ const memberName = manifestName(join3(folder, "packages", member));
2650
+ if (memberName !== undefined)
2651
+ names.add(memberName);
2652
+ }
2653
+ if (existsSync(join3(folder, ".git")) || dirname3(folder) === folder)
2654
+ return names;
2655
+ folder = dirname3(folder);
2656
+ }
2657
+ }
2658
+ function specName(spec) {
2659
+ return spec.slice(0, spec.lastIndexOf("@"));
2660
+ }
2538
2661
  function addedPackages(command) {
2539
2662
  let published = false;
2663
+ let own;
2540
2664
  return splitCommand(command).flatMap((piece) => {
2541
2665
  published ||= PUBLISH.test(piece.command);
2542
2666
  const { program, args } = parseCommand(piece.command);
2543
2667
  const [sub = "", ...rest] = args;
2544
- if (published)
2545
- return [];
2546
- if (RUNNERS.has(program))
2547
- return runnerPackages(args);
2548
- if (RUNS[program]?.has(sub))
2549
- return runnerPackages(rest);
2550
- if (!ADDS[program]?.has(sub))
2551
- return [];
2552
- return rest.flatMap((word, index) => isSkipped(word, rest[index - 1] ?? "") ? [] : registryName(word));
2668
+ const names = piecePackages(program, sub, args, rest);
2669
+ if (!published)
2670
+ return names;
2671
+ own ??= ownPackages();
2672
+ return names.filter((name) => !EXACT_SPEC.test(name) || !own.has(specName(name)));
2553
2673
  });
2554
2674
  }
2675
+ function piecePackages(program, sub, args, rest) {
2676
+ if (RUNNERS.has(program))
2677
+ return runnerPackages(args);
2678
+ if (RUNS[program]?.has(sub))
2679
+ return runnerPackages(rest);
2680
+ if (!ADDS[program]?.has(sub))
2681
+ return [];
2682
+ return rest.flatMap((word, index) => isSkipped(word, rest[index - 1] ?? "") ? [] : registryName(word));
2683
+ }
2555
2684
  function isSkipped(word, previous) {
2556
2685
  return word.startsWith("-") || REDIRECT2.test(word) || VALUE_FLAGS.has(previous) || BARE_REDIRECT.test(previous);
2557
2686
  }
@@ -2656,7 +2785,9 @@ function installRequests(command, cwd, home) {
2656
2785
  let hasLeadingFlag = false;
2657
2786
  for (let i = 0;i < args.length; i++) {
2658
2787
  const arg = args[i] ?? "";
2659
- const [flag = "", value] = arg.split("=", 2);
2788
+ const equals = arg.indexOf("=");
2789
+ const flag = equals === -1 ? arg : arg.slice(0, equals);
2790
+ const value = equals === -1 ? undefined : arg.slice(equals + 1);
2660
2791
  if (DIR_FLAGS.has(flag) && value !== undefined && value !== "") {
2661
2792
  dir = resolvePath(cwd, value, home);
2662
2793
  } else if (VALUE_FLAGS2.has(arg)) {
@@ -2699,6 +2830,7 @@ var WHOLE_TREE = new Set(["-A", "--all", "-u", "--update", "--no-ignore-removal"
2699
2830
  var COMMIT_VALUE_SHORTS = new Set(["m", "F", "c", "C", "t"]);
2700
2831
  var COMMIT_VALUE_LONGS = new Set(["--message", "--file", "--reuse-message", "--reedit-message", "--template", "--author", "--date", "--fixup", "--squash", "--cleanup", "--trailer", "--pathspec-from-file"]);
2701
2832
  var SHORT_CLUSTER = /^-[A-Z]+$/i;
2833
+ var SHORT_OPTIONS = /^-[A-Z]/i;
2702
2834
  var STAGES_ALL = /[Au]/;
2703
2835
  var ALL_TAGS = new Set(["--tags", "--follow-tags"]);
2704
2836
  var TOP_MAGIC = /^:(?:\/|\([^)]*\))/;
@@ -2762,7 +2894,7 @@ function commitsAll(args) {
2762
2894
  i++;
2763
2895
  continue;
2764
2896
  }
2765
- if (!SHORT_CLUSTER.test(arg))
2897
+ if (!SHORT_OPTIONS.test(arg))
2766
2898
  continue;
2767
2899
  for (const [index, flag] of [...arg.slice(1)].entries()) {
2768
2900
  if (flag === "a")
@@ -2826,6 +2958,10 @@ function heredocBody(text, opener) {
2826
2958
  `), rest: lines.slice(end + 1).join(`
2827
2959
  `) };
2828
2960
  }
2961
+ var FD_PATH = /^\/dev\/fd\/\d+$/;
2962
+ function isStdin(file) {
2963
+ return file === "-" || file === "/dev/stdin" || FD_PATH.test(file);
2964
+ }
2829
2965
  function sourceOf(args, text) {
2830
2966
  const source = { parts: [], file: null, stdin: null, isReused: false, hasTrailerFlag: false };
2831
2967
  const take = (option, value) => {
@@ -2854,7 +2990,7 @@ function sourceOf(args, text) {
2854
2990
  take(option, args[++i] ?? "");
2855
2991
  continue;
2856
2992
  }
2857
- if (!SHORT_CLUSTER.test(arg))
2993
+ if (!SHORT_OPTIONS.test(arg))
2858
2994
  continue;
2859
2995
  for (const [index, flag] of [...arg.slice(1)].entries()) {
2860
2996
  if (flag === "s")
@@ -2865,7 +3001,7 @@ function sourceOf(args, text) {
2865
3001
  break;
2866
3002
  }
2867
3003
  }
2868
- if (source.file === "-")
3004
+ if (source.file !== null && isStdin(source.file))
2869
3005
  source.stdin = heredocBody(text, HEREDOC_OPENER)?.body ?? null;
2870
3006
  return source;
2871
3007
  }
@@ -2942,12 +3078,149 @@ function gcLine(command) {
2942
3078
  return ["gc", shellQuote(title), ...options, "--", ...paths.map((path) => shellQuote(path))].join(" ");
2943
3079
  }
2944
3080
 
3081
+ // src/destructive.ts
3082
+ var FETCHERS = new Set(["curl", "wget", "fetch"]);
3083
+ var EVALUATORS = new Set(["eval", "source", "."]);
3084
+ var FETCH_SUBSTITUTION = /(?:\$\(|<\(|`)\s*(?:curl|wget|fetch)\b/;
3085
+ var RECURSIVE_LETTER = /r/i;
3086
+ var HOME_PREFIX = /^(?:~|\$HOME|\$\{HOME(?::?[-?=+][^}]*)?\}?)(?=\/|$)/;
3087
+ var CURRENT_DIRECTORY = /^(?:\$PWD|\$\{PWD\}?|\$\(pwd\)?|`pwd`?)(?=\/|$)/;
3088
+ var SAFE_REBASE = new Set(["--abort", "--continue", "--quit", "--show-current-patch", "--skip", "--edit-todo"]);
3089
+ var INTERPRETERS2 = new Set(["python", "node", "bun", "perl", "ruby"]);
3090
+ var VERSION_SUFFIX = /[\d.]+$/;
3091
+ var PASS_THROUGH = new Set(["tee", "cat", "pv", "tr", "sed"]);
3092
+ var COMMIT_FIRST = "Commit what you want to keep with `gc` first.";
3093
+ var SAFE_BASE = "`base -- <cmd>` runs a command at HEAD with the working tree untouched, and `git worktree add` gives a clean tree.";
3094
+ var RESET_HARD = `Never \`git reset --hard\`: it throws away uncommitted work, and peer sessions edit this tree live. ${COMMIT_FIRST} \`git reset --soft\` or \`--mixed\` moves HEAD and keeps the changes; ${SAFE_BASE}`;
3095
+ var DISCARD_TREE = `Never discard the whole working tree (\`git checkout -- .\`, \`git checkout -f\`, \`git restore .\`, \`git rm -r .\`, \`git switch -f\`): it throws away uncommitted work, and peer sessions edit this tree live. ${COMMIT_FIRST} Restore named paths only, and \`git restore --staged\` just unstages. ${SAFE_BASE}`;
3096
+ var CLEAN = `Never \`git clean -f\`: it deletes untracked files that peer sessions or the user have not committed yet. \`git clean -n\` lists what it would remove; delete named files yourself.`;
3097
+ var FORCE_PUSH = "Never force-push with `--force`, `-f`, `--mirror` or a `+refspec`: it overwrites commits on the remote. When the user asked for one, `git push --force-with-lease` refuses to overwrite what you have not seen.";
3098
+ var REMOTE_DELETE = "Never delete a remote branch or tag with `git push --delete` or `git push origin :ref`: it removes work from the remote for everyone. Ask the user to run it themselves.";
3099
+ var BRANCH_DELETE = "Never `git branch -D`: it drops commits no other branch holds. `git branch -d` deletes a merged branch only; ask the user before dropping an unmerged one.";
3100
+ var REBASE = `Never start a \`git rebase\`: it rewrites history and stops halfway on conflicts in a tree others edit. ${COMMIT_FIRST} \`git cherry-pick\` or \`git merge\` keep history, and \`git worktree add\` gives a clean tree to do it in. \`--continue\` and \`--abort\` stay allowed.`;
3101
+ var REWRITE_HISTORY = "Never `git filter-branch` or `git filter-repo`: they rewrite every commit of the repository. Ask the user to run it themselves.";
3102
+ var BROAD_RM = "Never `rm -r` on `/`, `~`, `$HOME`, `.`, `..`, `*` or a top-level directory: it deletes far more than the task. Name the exact directory, such as `dist` or `node_modules`.";
3103
+ var PIPE_TO_SHELL = 'Never run what `curl`/`wget` fetches straight in a shell (`| sh`, `bash <(curl ...)`, `eval "$(curl ...)"`): it runs code nobody read. Download it to a file, read it, then run it, or hand the command to the user.';
3104
+ function hasOption(args, long, shorts) {
3105
+ for (const arg of args) {
3106
+ if (arg === "--")
3107
+ return false;
3108
+ if (long.includes(arg) || SHORT_CLUSTER.test(arg) && [...arg.slice(1)].some((letter) => shorts.includes(letter)))
3109
+ return true;
3110
+ }
3111
+ return false;
3112
+ }
3113
+ function isBroadPath(path) {
3114
+ const arg = path.replace(CURRENT_DIRECTORY, ".");
3115
+ const home = HOME_PREFIX.exec(arg);
3116
+ const isAbsolute = home === null && arg.startsWith("/");
3117
+ const parts = [];
3118
+ for (const part of (home === null ? arg : arg.slice(home[0].length)).split("/")) {
3119
+ if (part === ".." && parts.length > 0 && parts.at(-1) !== "..")
3120
+ parts.pop();
3121
+ else if (part === ".." && !isAbsolute && home === null)
3122
+ parts.push(part);
3123
+ else if (part !== "" && part !== "." && part !== "..")
3124
+ parts.push(part);
3125
+ }
3126
+ if (parts.at(-1) === "*" || parts.at(-1) === ".*")
3127
+ parts.pop();
3128
+ if (home !== null)
3129
+ return parts.length === 0;
3130
+ return isAbsolute ? parts.length <= 1 : parts.every((part) => part === "..");
3131
+ }
3132
+ function removesBroadly(args) {
3133
+ if (args.includes("--no-preserve-root"))
3134
+ return true;
3135
+ const options = args.slice(0, args.includes("--") ? args.indexOf("--") : args.length);
3136
+ const isRecursive = options.some((arg) => arg === "--recursive" || SHORT_CLUSTER.test(arg) && RECURSIVE_LETTER.test(arg));
3137
+ if (!isRecursive)
3138
+ return false;
3139
+ const targets = args.filter((arg, i) => !arg.startsWith("-") || args.includes("--") && i > args.indexOf("--"));
3140
+ return targets.some(isBroadPath);
3141
+ }
3142
+ function checksOutTree(rest, operands) {
3143
+ if (rest.includes("--"))
3144
+ return operands.some((arg) => arg !== "--" && isWholeTree(arg));
3145
+ return operands.length === 1 ? isWholeTree(operands[0] ?? "") : operands.slice(1).some(isWholeTree);
3146
+ }
3147
+ function gitDestructive(name, rest) {
3148
+ const operands = rest.filter((arg) => !arg.startsWith("-") || arg === "--");
3149
+ if (name === "reset")
3150
+ return rest.includes("--hard") ? RESET_HARD : null;
3151
+ if (name === "checkout" && !hasOption(rest, ["--patch"], "p") && (hasOption(rest, ["--force"], "f") || checksOutTree(rest, operands)))
3152
+ return DISCARD_TREE;
3153
+ if (name === "switch" && hasOption(rest, ["--force", "--discard-changes"], "f"))
3154
+ return DISCARD_TREE;
3155
+ if (name === "restore") {
3156
+ const isStagedOnly = hasOption(rest, ["--staged"], "S") && !hasOption(rest, ["--worktree"], "W");
3157
+ return !isStagedOnly && !hasOption(rest, ["--patch"], "p") && operands.some((arg) => arg !== "--" && isWholeTree(arg)) ? DISCARD_TREE : null;
3158
+ }
3159
+ if (name === "rm")
3160
+ return !hasOption(rest, ["--cached", "--dry-run"], "n") && operands.some((arg) => arg !== "--" && isWholeTree(arg)) ? DISCARD_TREE : null;
3161
+ if (name === "clean")
3162
+ return hasOption(rest, ["--force"], "f") && !hasOption(rest, ["--dry-run"], "n") ? CLEAN : null;
3163
+ if (name === "push") {
3164
+ const isForced = hasOption(rest, ["--force", "--mirror"], "f") || rest.some((arg) => arg.startsWith("--force=") || !arg.startsWith("-") && arg.startsWith("+"));
3165
+ if (isForced)
3166
+ return FORCE_PUSH;
3167
+ return hasOption(rest, ["--delete"], "d") || rest.some((arg) => arg.startsWith(":") && arg.length > 1) ? REMOTE_DELETE : null;
3168
+ }
3169
+ if (name === "branch")
3170
+ return hasOption(rest, [], "D") || hasOption(rest, ["--delete"], "d") && hasOption(rest, ["--force"], "f") ? BRANCH_DELETE : null;
3171
+ if (name === "rebase")
3172
+ return rest.some((arg) => SAFE_REBASE.has(arg)) ? null : REBASE;
3173
+ return name === "filter-branch" || name === "filter-repo" ? REWRITE_HISTORY : null;
3174
+ }
3175
+ function feedsExecutor(stages) {
3176
+ for (const stage of stages) {
3177
+ const { program, args } = parseCommand(stage.command);
3178
+ const hasScript = args.some((arg) => !arg.startsWith("-"));
3179
+ if (SHELLS.has(program))
3180
+ return !hasOption(args, [], "n") && (!hasScript || args.includes("-s"));
3181
+ if (INTERPRETERS2.has(program.replace(VERSION_SUFFIX, "")))
3182
+ return !hasScript;
3183
+ if (!PASS_THROUGH.has(program) || stage.separator !== "|")
3184
+ return false;
3185
+ }
3186
+ return false;
3187
+ }
3188
+ function runsDownload(command) {
3189
+ const pieces = splitCommand(command);
3190
+ return pieces.some((piece, index) => {
3191
+ const { program } = parseCommand(piece.command);
3192
+ if (FETCHERS.has(program) && piece.separator === "|")
3193
+ return feedsExecutor(pieces.slice(index + 1));
3194
+ return (SHELLS.has(program) || EVALUATORS.has(program)) && FETCH_SUBSTITUTION.test(piece.command);
3195
+ });
3196
+ }
3197
+ function destructiveViolation(command) {
3198
+ if (runsDownload(command))
3199
+ return PIPE_TO_SHELL;
3200
+ for (const piece of splitCommand(command)) {
3201
+ const { program, args } = parseCommand(piece.command);
3202
+ if (program === "rm" && removesBroadly(args))
3203
+ return BROAD_RM;
3204
+ if (program !== "git")
3205
+ continue;
3206
+ const { name, rest } = subcommandOf(args);
3207
+ const violation = gitDestructive(name, rest);
3208
+ if (violation !== null)
3209
+ return violation;
3210
+ }
3211
+ return null;
3212
+ }
3213
+
2945
3214
  // src/remote.ts
2946
3215
  var SHELL_PROGRAMS = new Set(["ssh", "scp", "sftp", "mosh", "mosh-client", "autossh"]);
2947
3216
  var SOCKET_PROGRAMS = new Set(["nc", "ncat", "netcat", "telnet", "socat"]);
2948
3217
  var URL_PROGRAMS = new Set(["git", "docker", "docker-compose"]);
2949
3218
  var DECLARERS2 = new Set(["export", "declare", "typeset"]);
2950
3219
  var RSYNC_REMOTE = /^(?:[\w.-]+@)?[\w.-]{2,}:/;
3220
+ var SCP_ADDRESS = /^[^/:\s-][^/:\s]*:(?!\/\/)/;
3221
+ var SCP_HOST_ADDRESS = /^(?:[\w.-]+@[\w.-]+|[\w-]+(?:\.[\w-]+)+):(?!\/\/)/;
3222
+ var GIT_TRANSPORTS = new Set(["clone", "fetch", "pull", "push", "ls-remote"]);
3223
+ var TRANSPORT_VALUE_OPTIONS = new Set(["--depth", "-b", "--branch", "-o", "--origin", "--push-option", "-c", "--config", "--reference", "--separate-git-dir", "--template", "-j", "--jobs", "--filter", "--shallow-since", "--shallow-exclude", "-u", "--upload-pack", "--receive-pack", "--exec", "--server-option", "--repo", "--deepen"]);
2951
3224
  var SSH_URL = /^ssh:\/\//;
2952
3225
  var SSH_URL_WORD = /^(?:[\w-]+=)?ssh:\/\//;
2953
3226
  var LOOPBACK = /(?:^|[:=@[])(?:localhost|127(?:\.\d+){3}|::1)(?:[:\]/]|$)/;
@@ -2982,6 +3255,24 @@ function isDockerRemote(args, assignments) {
2982
3255
  function isSocketRemote(args) {
2983
3256
  return !args.some((arg) => LISTENS.test(arg) || LOOPBACK.test(arg));
2984
3257
  }
3258
+ function firstOperand2(args) {
3259
+ for (let i = 0;i < args.length; i++) {
3260
+ const arg = args[i] ?? "";
3261
+ if (TRANSPORT_VALUE_OPTIONS.has(arg))
3262
+ i++;
3263
+ else if (!arg.startsWith("-"))
3264
+ return arg;
3265
+ }
3266
+ return;
3267
+ }
3268
+ function isScpAddress(args) {
3269
+ const { name, rest } = subcommandOf(args);
3270
+ if (!GIT_TRANSPORTS.has(name))
3271
+ return false;
3272
+ const address = name === "clone" || name === "ls-remote" ? SCP_ADDRESS : SCP_HOST_ADDRESS;
3273
+ const repository = firstOperand2(rest);
3274
+ return repository !== undefined && address.test(repository);
3275
+ }
2985
3276
  function isRemote(text) {
2986
3277
  const { program, args, assignments } = parseCommand(text);
2987
3278
  const declared = DECLARERS2.has(program) ? args : [];
@@ -2991,6 +3282,8 @@ function isRemote(text) {
2991
3282
  return isSocketRemote(args);
2992
3283
  if (program === "rsync")
2993
3284
  return args.some((arg) => !arg.startsWith("-") && RSYNC_REMOTE.test(arg));
3285
+ if (program === "git" && isScpAddress(args))
3286
+ return true;
2994
3287
  if (program === "kubectl")
2995
3288
  return args.some((arg) => KUBECTL_SERVER.test(arg));
2996
3289
  if ([...assignments, ...declared].some((assignment) => REMOTE_VARIABLE.test(assignment)))
@@ -3363,13 +3656,13 @@ function commitViolation(command, { cwd, read }) {
3363
3656
  for (const source of commitSources(command)) {
3364
3657
  if (source.hasTrailerFlag)
3365
3658
  return TRAILERS;
3366
- if (source.isReused || source.file?.startsWith("/dev/") === true)
3367
- continue;
3368
3659
  const { file } = source;
3660
+ if (source.isReused || file?.startsWith("/dev/") === true && !isStdin(file))
3661
+ continue;
3369
3662
  let message = source.stdin;
3370
3663
  if (file === null)
3371
3664
  message = inlineMessage(source.parts);
3372
- else if (file !== "-")
3665
+ else if (!isStdin(file))
3373
3666
  message = read(absolute(file, cwd));
3374
3667
  if (message === null && (source.parts.length > 0 || file !== null))
3375
3668
  return UNREADABLE_MESSAGE;
@@ -3394,6 +3687,10 @@ function mismatches(command, { cwd, home, exists }) {
3394
3687
  return mismatch === null ? [] : [mismatch];
3395
3688
  });
3396
3689
  }
3690
+ function nestedMismatches(run, context, own) {
3691
+ const ownTexts = new Set(own.map((mismatch) => mismatch.piece.command.trim()));
3692
+ return run.slice(1).flatMap((each) => mismatches(each, context)).filter((mismatch) => !ownTexts.has(mismatch.piece.command.trim())).map((mismatch) => ({ ...mismatch, rewrite: null }));
3693
+ }
3397
3694
  async function checkCommand(command, context) {
3398
3695
  const violations = [];
3399
3696
  const notes = [];
@@ -3414,6 +3711,7 @@ async function checkCommand(command, context) {
3414
3711
  const readSql = async (path) => Promise.resolve(context.read(absolute(path, context.cwd)));
3415
3712
  add("remote", await guarded("remote", () => first(run.map(remoteViolation))));
3416
3713
  add("git", await guarded("git", () => first(run.map((each) => gitViolation(each, context.isPushAsked)))));
3714
+ add("destructive", await guarded("destructive", () => first(run.map(destructiveViolation))));
3417
3715
  const commit = await guarded("commit", () => first(run.map((each) => commitViolation(each, context))));
3418
3716
  add("commit", commit === null ? null : `${commit} ${USE_GC}`);
3419
3717
  add("sql", await guarded("sql", async () => first(await Promise.all(run.map(async (each) => sqlViolation(each, readSql))))));
@@ -3425,7 +3723,7 @@ async function checkCommand(command, context) {
3425
3723
  }));
3426
3724
  add("edit", context.canSub ? await guarded("edit", () => first(run.map(replaceViolation))) : null);
3427
3725
  const found = mismatches(command, context);
3428
- const refused = found.find((mismatch) => mismatch.rewrite === null || !context.canRewrite);
3726
+ const refused = [...found, ...nestedMismatches(run, context, found)].find((mismatch) => mismatch.rewrite === null || !context.canRewrite);
3429
3727
  const rewrite = refused?.rewrite ?? null;
3430
3728
  const route = rewrite === null ? "Run it with the pinned manager instead." : `Run \`${rewrite.trim()}\` instead.`;
3431
3729
  add("package-manager", refused === undefined ? null : `${refused.reason} ${route}`);
@@ -3444,8 +3742,8 @@ function checkPath(path) {
3444
3742
 
3445
3743
  // src/bins.ts
3446
3744
  var BINS = {
3447
- check: "`check`: runs the repo's check, typecheck, lint and test steps (package.json, composer.json and PHP tool configs, a Justfile, a Makefile) and prints only what failed, each full log saved to a file; a step runs inside the running compose service that mounts its folder (`--in <service>`, `--host`), never starting one; validate a change with it rather than chaining the scripts or `docker compose exec` by hand (`--only lint,test`, `--list`, `--slot`).",
3448
- fix: "`fix`: runs the repo's fixers and formatters (its fix, lint:fix and format scripts, php-cs-fixer, just fmt, go fmt, cargo fmt, ruff), in the compose service like `check`, and lists the files they changed.",
3745
+ check: "`check`: runs the repo's check, typecheck, lint and test steps (package.json, composer.json and PHP tool configs, a Justfile, a Makefile) and prints only what failed, each full log saved to a file; a step runs inside the running compose service that mounts its folder (`--in <service>`, `--host`), never starting one; validate a change with it rather than chaining the scripts or `docker compose exec` by hand (`--only lint,test`, `--list`, `--slot`, `--failed` to re-run what failed last, `--fix` for the fixers).",
3746
+ fix: "`fix` (the alias of `check --fix`): runs the repo's fixers and formatters (its fix, lint:fix and format scripts, php-cs-fixer, just fmt, go fmt, cargo fmt, ruff), in the compose service like `check`, and lists the files they changed.",
3449
3747
  errs: "`errs [log]`, `errs -- <cmd>`: turns tsc, tsgo, eslint, bun check, bun test, vitest, playwright, phpunit, phpstan and php-cs-fixer output into one `file:line:col: message (rule)` line per error, counting the lines it did not recognise (`--json`); use it instead of reading raw type, lint or test logs.",
3450
3748
  db: '`db "<sql>"`: one read-only statement against the Postgres, MySQL or MariaDB in DATABASE_URL (`-e KEY` for another) or, without one, the compose project\'s running database service (`-s <service>`, `-c <container>` for any container, `-d <database>`), credentials never shown; a write runs on a database whose name ends in `_test` and is printed for the user to run otherwise; `db tables`, `db describe <table>`, `db dbs`; use it instead of `docker exec <container> psql` or `mysql`.',
3451
3749
  ev: "`ev`: .env files read and edited with values masked (`ev list`, `ev get KEY`, `ev grep <regex>`, `ev show <rev>:<file>`, `ev set`, `ev diff`, `ev missing`); `ev audit [dir]` finds env files others can read or git tracks, and compose files writing secrets out; `ev pins [dir]` lists the env vars reaching outside that the tests of an app leave unpinned.",
@@ -3572,6 +3870,7 @@ async function hook(event, input, machine) {
3572
3870
  var LISTED = [
3573
3871
  { name: "remote", refuses: "ssh, scp, rsync and deploys to a remote machine", route: "hand the command to the user" },
3574
3872
  { name: "git", refuses: "stash, whole-tree add and commit, push without being asked, tags", route: "stage by path with `gc`, push only when asked" },
3873
+ { name: "destructive", refuses: "reset --hard, discarding the tree, clean -f, force push, branch -D, rebase, filter-branch, rm -r on a broad path, curl piped to a shell", route: "commit with `gc` first, `base`, `git worktree add`, `--force-with-lease` only when asked" },
3575
3874
  { name: "commit", refuses: "a commit message breaking the format, an unreadable one, trailers", route: "`gc <title> -m <line> -- <path>...`" },
3576
3875
  { name: "sql", refuses: "SQL writes and DDL, a file the client cannot read", route: '`db "<sql>"`, writes on a `*_test` database or handed over' },
3577
3876
  { name: "env", refuses: "reading or printing an env file, a diff of a tracked one", route: "`ev`, and `rg` for a tree-wide search" },
@@ -3584,7 +3883,7 @@ var RULES2 = LISTED.map((rule) => ({ runs: "check and hook", ...rule }));
3584
3883
  // src/cli.ts
3585
3884
  var checkUsage = `guard check [options] [<command> | -]
3586
3885
 
3587
- Checks a shell command against the rules: remote machines, git (stash, whole-tree add and commit, push, tags), commit messages, SQL writes, env files, package managers and in-place edits (sed -i and replace scripts, pointed at sub).
3886
+ Checks a shell command against the rules: remote machines, git (stash, whole-tree add and commit, push, tags), destructive commands (reset --hard, force push, rebase, broad rm), commit messages, SQL writes, env files, package managers and in-place edits (sed -i and replace scripts, pointed at sub).
3588
3887
  Prints each broken rule with the route to take instead and exits 1, prints nothing and exits 0 when the command is clean.
3589
3888
  The command is read from stdin with - or when none is given; a rule may rewrite it instead (the pinned package manager, a noisy run through out), printed as \`runs as: <command>\`.
3590
3889
 
@@ -3614,7 +3913,7 @@ var MAX_READ = 1e6;
3614
3913
  function readText(path) {
3615
3914
  try {
3616
3915
  const stats = statSync(path, { throwIfNoEntry: false });
3617
- return stats?.isFile() === true && stats.size <= MAX_READ ? readFileSync(path, "utf8") : null;
3916
+ return stats?.isFile() === true && stats.size <= MAX_READ ? readFileSync3(path, "utf8") : null;
3618
3917
  } catch {
3619
3918
  return null;
3620
3919
  }
@@ -3633,14 +3932,14 @@ ${checkUsage}`);
3633
3932
  const given = positionals[0] ?? "-";
3634
3933
  const command = given === "-" ? await readInput("-", { noStdin: "give the command, or pipe it on stdin" }) : given;
3635
3934
  const context = {
3636
- cwd: values.cwd ?? process10.cwd(),
3935
+ cwd: values.cwd ?? process11.cwd(),
3637
3936
  home: homedir2(),
3638
3937
  isPushAsked: values["push-asked"] === true,
3639
3938
  canRewrite: true,
3640
3939
  canWrap: values["no-wrap"] !== true && Bun.which("out") !== null,
3641
3940
  canSub: Bun.which("sub") !== null,
3642
3941
  read: readText,
3643
- exists: existsSync
3942
+ exists: existsSync2
3644
3943
  };
3645
3944
  const verdict = await checkCommand(command, context);
3646
3945
  if (values.json === true)
@@ -3693,9 +3992,9 @@ function machine() {
3693
3992
  has: (bin) => Bun.which(bin) !== null,
3694
3993
  run: async (argv, cwd) => runCommand(argv, { cwd }),
3695
3994
  read: readText,
3696
- exists: existsSync,
3995
+ exists: existsSync2,
3697
3996
  write: (path, text) => {
3698
- mkdirSync2(dirname2(path), { recursive: true });
3997
+ mkdirSync2(dirname4(path), { recursive: true });
3699
3998
  writeFileSync(path, text);
3700
3999
  },
3701
4000
  remove: (path) => rmSync(path, { force: true }),
@@ -3719,9 +4018,8 @@ ${hookUsage}`, 1);
3719
4018
  console.log(JSON.stringify(reply));
3720
4019
  return 0;
3721
4020
  }
3722
- process10.exitCode = await runCli({
4021
+ process11.exitCode = await runCli({
3723
4022
  name: "guard",
3724
- version,
3725
4023
  usage: false,
3726
4024
  about: "the safety rules a Claude Code Bash call is held to, each refusal naming the route",
3727
4025
  replaces: "a hook script per rule, each wording its own refusal",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-guard",
3
3
  "type": "module",
4
- "version": "0.8.0",
4
+ "version": "0.9.1",
5
5
  "description": "guard: the safety rules a Claude Code Bash call is held to (git, remote machines, SQL writes, env files, package managers, commit messages), each refusal naming the route.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -36,12 +36,12 @@
36
36
  "guard": "$npm_execpath src/cli.ts"
37
37
  },
38
38
  "devDependencies": {
39
- "@kaynooo/cli-db": "0.9.1",
40
- "@kaynooo/cli-edit": "0.4.0",
41
- "@kaynooo/cli-env": "0.8.0",
42
- "@kaynooo/cli-git": "0.5.1",
43
- "@kaynooo/cli-kit": "0.20.0",
44
- "@kaynooo/cli-out": "0.7.0",
45
- "@kaynooo/cli-pkg": "0.7.0"
39
+ "@kaynooo/cli-db": "0.10.0",
40
+ "@kaynooo/cli-edit": "0.5.1",
41
+ "@kaynooo/cli-env": "0.9.1",
42
+ "@kaynooo/cli-git": "0.7.1",
43
+ "@kaynooo/cli-kit": "0.21.0",
44
+ "@kaynooo/cli-out": "0.8.0",
45
+ "@kaynooo/cli-pkg": "0.8.0"
46
46
  }
47
47
  }