@kaynooo/cli-edit 0.10.1 → 0.11.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 (2) hide show
  1. package/dist/cli.js +384 -63
  2. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -2,9 +2,9 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import { accessSync, chmodSync, constants, existsSync as existsSync3, readFileSync as readFileSync4, realpathSync as realpathSync3, renameSync, rmSync as rmSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
5
+ import { accessSync, chmodSync, constants as constants2, existsSync as existsSync5, readFileSync as readFileSync5, realpathSync as realpathSync3, renameSync, rmSync as rmSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
6
6
  import { normalize, resolve as resolve4 } from "path";
7
- import process15 from "process";
7
+ import process17 from "process";
8
8
  // ../kit/src/args.ts
9
9
  import process10 from "process";
10
10
  import { parseArgs } from "util";
@@ -113,7 +113,7 @@ function Fe(r = {}) {
113
113
  var o = Fe();
114
114
 
115
115
  // ../kit/src/theme.ts
116
- import { existsSync as existsSync2, readFileSync, statSync } from "fs";
116
+ import { existsSync as existsSync3, readFileSync as readFileSync2, statSync } from "fs";
117
117
  import { homedir as homedir2 } from "os";
118
118
  import { join as join3, resolve as resolve2 } from "path";
119
119
  import process5 from "process";
@@ -134,6 +134,7 @@ function findUp(names, from = process3.cwd(), stop = () => false) {
134
134
  }
135
135
 
136
136
  // ../kit/src/user-config.ts
137
+ import { existsSync as existsSync2, readFileSync } from "fs";
137
138
  import { homedir } from "os";
138
139
  import { join as join2 } from "path";
139
140
  import process4 from "process";
@@ -144,6 +145,24 @@ function configBase(where = {}) {
144
145
  function userConfigPath(bin, where = {}) {
145
146
  return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
146
147
  }
148
+ function userConfigReadPath(bin, legacy = [], where = {}) {
149
+ const current = userConfigPath(bin, where);
150
+ if (existsSync2(current))
151
+ return current;
152
+ const base = configBase(where);
153
+ return legacy.map((parts) => join2(base, ...parts)).find((path) => existsSync2(path)) ?? current;
154
+ }
155
+ function readUserConfig(bin, where = {}, legacy = []) {
156
+ const path = userConfigReadPath(bin, legacy, where);
157
+ if (!existsSync2(path))
158
+ return {};
159
+ try {
160
+ const parsed = Bun.JSONC.parse(readFileSync(path, "utf8"));
161
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
162
+ } catch {
163
+ return {};
164
+ }
165
+ }
147
166
 
148
167
  // ../kit/src/theme.ts
149
168
  var ENDS = new Map;
@@ -210,7 +229,7 @@ function readThemeFile(path, warn) {
210
229
  warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
211
230
  return;
212
231
  }
213
- const parsed = JSON.parse(readFileSync(path, "utf8"));
232
+ const parsed = JSON.parse(readFileSync2(path, "utf8"));
214
233
  if (isRecord(parsed))
215
234
  return parsed;
216
235
  warn(`${path} is not a JSON object, theme ignored`);
@@ -276,7 +295,7 @@ function applyFile(theme, file, where, warn) {
276
295
  }
277
296
  }
278
297
  function endsWalk(home) {
279
- return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
298
+ return (dir) => dir === resolve2(home) || existsSync3(join3(dir, ".git"));
280
299
  }
281
300
  var warned = new Set;
282
301
  function warnOnce(message) {
@@ -347,6 +366,23 @@ var STATUS_WORDS = {
347
366
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
348
367
 
349
368
  // ../kit/src/format.ts
369
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
370
+ function formatSeconds(total) {
371
+ let rest = Math.max(0, Math.round(total));
372
+ const amounts = UNITS.map(([unit, size]) => {
373
+ const amount = Math.floor(rest / size);
374
+ rest -= amount * size;
375
+ return `${amount}${unit}`;
376
+ });
377
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
378
+ if (first === -1)
379
+ return "0s";
380
+ const next = amounts[first + 1];
381
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
382
+ }
383
+ function formatDuration(ms) {
384
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
385
+ }
350
386
  function upTo(text, separator) {
351
387
  const end = text.indexOf(separator);
352
388
  return end === -1 ? text : text.slice(0, end);
@@ -361,7 +397,7 @@ function printJson(value) {
361
397
 
362
398
  // ../kit/src/help.ts
363
399
  import process8 from "process";
364
- var OPTIONAL = /\[[^\]]+\]/g;
400
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
365
401
  var USAGE_PREFIX = /^usage:\s*/i;
366
402
  var FULL_STOP = /\.$/;
367
403
  function usageLine(usage, colors = paint(process8.stdout)) {
@@ -400,29 +436,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
400
436
  return [];
401
437
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
402
438
  }
439
+ var MAX_INLINE_CHOICES = 24;
403
440
  function optionRows(options, colors = paint(process8.stdout)) {
404
441
  const rows = Object.entries(options).map(([name, option]) => {
405
442
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
406
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
443
+ const choices = option.choices?.join("|");
444
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
445
+ const named = inline ? `<${choices}>` : "<value>";
407
446
  const placeholder = option.optional === undefined ? named : `[${named}]`;
408
447
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
409
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
448
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
449
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
410
450
  });
411
451
  const width = Math.max(0, ...rows.map((row) => row.width));
412
452
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
413
453
  }
414
454
 
415
455
  // ../kit/src/text.ts
416
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
417
456
  function distance(a, b) {
418
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
419
- for (const [i, left] of [...a].entries()) {
457
+ const left = [...a];
458
+ const right = [...b];
459
+ let before = [];
460
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
461
+ for (const [i, x] of left.entries()) {
420
462
  const current = [i + 1];
421
- for (const [j, right] of [...b].entries())
422
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
463
+ for (const [j, y] of right.entries()) {
464
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
465
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
466
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
467
+ current.push(cost);
468
+ }
469
+ before = previous;
423
470
  previous = current;
424
471
  }
425
- return previous[b.length] ?? 0;
472
+ return previous[right.length] ?? 0;
426
473
  }
427
474
  function closest(name, names) {
428
475
  const started = names.find((known) => known.startsWith(name));
@@ -499,7 +546,7 @@ class Completing {
499
546
  }
500
547
  var completion = { active: false };
501
548
  var OUTPUT_OPTIONS = {
502
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
549
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
503
550
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
504
551
  };
505
552
  function applyOutput(color, plain, env = process10.env) {
@@ -672,12 +719,12 @@ function nearestOption(message, options, allowNegative) {
672
719
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
673
720
  }
674
721
  // ../kit/src/argv.ts
675
- import { readFileSync as readFileSync2, realpathSync } from "fs";
722
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
676
723
  import { resolve as resolve3 } from "path";
677
724
  import process11 from "process";
678
725
  function commandLine() {
679
726
  try {
680
- return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
727
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
681
728
  } catch {
682
729
  return;
683
730
  }
@@ -695,21 +742,189 @@ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), scr
695
742
  const after = at === -1 ? [] : cmdline.slice(at + 1);
696
743
  return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
697
744
  }
745
+ // ../kit/src/process.ts
746
+ import { constants } from "os";
747
+ import process12 from "process";
748
+ var KILL_GRACE_MS = 2000;
749
+ function exitCodeOf(code, signal) {
750
+ if (code !== null)
751
+ return code;
752
+ if (typeof signal === "number")
753
+ return 128 + signal;
754
+ return signal === null ? 129 : 128 + constants.signals[signal];
755
+ }
756
+ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal, maxBytes = Infinity, onChunk, onStart } = {}) {
757
+ const chunks = [];
758
+ const grouped = timeoutMs !== undefined || signal !== undefined || onStart !== undefined || onChunk !== undefined;
759
+ const proc = Bun.spawn(argv, { ...cwd === undefined ? {} : { cwd }, ...env === undefined ? {} : { env }, stdin, stdout: "pipe", stderr: "pipe", ...grouped ? { detached: true } : {} });
760
+ const state = { kept: 0, truncated: false, timedOut: false, failure: undefined, done: false };
761
+ const timers = [];
762
+ const killGroup = (killing) => {
763
+ if (state.done)
764
+ return;
765
+ try {
766
+ if (grouped)
767
+ process12.kill(-proc.pid, killing);
768
+ else
769
+ proc.kill(killing);
770
+ } catch {}
771
+ };
772
+ const stop = () => {
773
+ killGroup("SIGTERM");
774
+ timers.push(setTimeout(killGroup, KILL_GRACE_MS, "SIGKILL"));
775
+ };
776
+ const onAbort = () => stop();
777
+ if (timeoutMs !== undefined) {
778
+ timers.push(setTimeout(() => {
779
+ state.timedOut = true;
780
+ stop();
781
+ }, timeoutMs));
782
+ }
783
+ if (signal?.aborted === true)
784
+ onAbort();
785
+ else
786
+ signal?.addEventListener("abort", onAbort, { once: true });
787
+ onStart?.({ kill: (killing) => killGroup(killing) });
788
+ const drain = async (stream, name) => {
789
+ for await (const data of stream) {
790
+ if (state.failure !== undefined)
791
+ continue;
792
+ try {
793
+ onChunk?.({ stream: name, data });
794
+ } catch (error) {
795
+ state.failure = error;
796
+ stop();
797
+ continue;
798
+ }
799
+ if (state.kept + data.length > maxBytes) {
800
+ state.truncated = true;
801
+ continue;
802
+ }
803
+ state.kept += data.length;
804
+ chunks.push({ stream: name, data });
805
+ }
806
+ };
807
+ try {
808
+ await Promise.all([drain(proc.stdout, "stdout"), drain(proc.stderr, "stderr")]);
809
+ await proc.exited;
810
+ } finally {
811
+ state.done = true;
812
+ for (const timer of timers)
813
+ clearTimeout(timer);
814
+ signal?.removeEventListener("abort", onAbort);
815
+ }
816
+ if (state.failure !== undefined)
817
+ throw state.failure;
818
+ const joined = () => Buffer.concat(chunks.map(({ data }) => data));
819
+ let output;
820
+ let text;
821
+ return {
822
+ code: exitCodeOf(proc.exitCode, proc.signalCode),
823
+ chunks,
824
+ timedOut: state.timedOut,
825
+ truncated: state.truncated,
826
+ get output() {
827
+ return output ??= joined();
828
+ },
829
+ get text() {
830
+ return text ??= (output ??= joined()).toString();
831
+ }
832
+ };
833
+ }
834
+
698
835
  // ../kit/src/progress.ts
699
836
  var ESC = String.fromCharCode(27);
700
837
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
701
838
  var RESET_STYLE = `${ESC}[0m`;
702
839
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
703
840
  // ../kit/src/cli.ts
704
- import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
841
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
705
842
  import { dirname as dirname3, join as join5 } from "path";
843
+ import process15 from "process";
844
+
845
+ // ../kit/src/completions.ts
846
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
847
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
848
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
849
+ set -l current (commandline -ct)
850
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
851
+ if test "$line" = __files__
852
+ __fish_complete_path $current
853
+ else
854
+ echo $line
855
+ end
856
+ end
857
+ end`;
858
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
859
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
860
+ local -a lines
861
+ COMPREPLY=()
862
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
863
+ for line in "\${lines[@]}"; do
864
+ if [[ $line == __files__ ]]; then
865
+ COMPREPLY+=($(compgen -f -- "$cur"))
866
+ else
867
+ words+="\${line%%$'\\t'*}"$'\\n'
868
+ fi
869
+ done
870
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
871
+ }`;
872
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
873
+ local line
874
+ local -a described plain
875
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
876
+ if [[ $line == __files__ ]]; then
877
+ _files
878
+ elif [[ $line == *$'\\t'* ]]; then
879
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
880
+ else
881
+ plain+=("$line")
882
+ fi
883
+ done
884
+ (( \${#described} )) && _describe -V value described
885
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
886
+ return 0
887
+ }`;
888
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
889
+ if (shell === "fish")
890
+ return `${header}
891
+ ${FISH_FUNCTION}
892
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
893
+ `).join("")}`;
894
+ if (shell === "bash")
895
+ return `${header}
896
+ ${BASH_FUNCTION}
897
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
898
+ `;
899
+ return `${header}
900
+ ${ZSH_FUNCTION}
901
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
902
+ `;
903
+ }
904
+
905
+ // ../kit/src/notify.ts
706
906
  import process13 from "process";
907
+ var NOTIFY_AFTER_MS = 1e4;
908
+ var CANCELLED = 130;
909
+ function base64(text) {
910
+ return Buffer.from(text).toString("base64");
911
+ }
912
+ function notification(title, body, env = process13.env) {
913
+ const id = `kit${process13.pid}`;
914
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
915
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
916
+ }
917
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
918
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
919
+ return;
920
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
921
+ }
707
922
 
708
923
  // ../kit/src/usage.ts
709
924
  import { appendFileSync, mkdirSync } from "fs";
710
925
  import { homedir as homedir3 } from "os";
711
926
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
712
- import process12 from "process";
927
+ import process14 from "process";
713
928
 
714
929
  // ../kit/src/logs.ts
715
930
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -723,14 +938,14 @@ var usageError;
723
938
  function noteUsageError(message) {
724
939
  usageError = message;
725
940
  }
726
- function stateHome(env = process12.env) {
941
+ function stateHome(env = process14.env) {
727
942
  const dir = env.XDG_STATE_HOME;
728
943
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
729
944
  }
730
- function usagePath(env = process12.env) {
945
+ function usagePath(env = process14.env) {
731
946
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
732
947
  }
733
- function usageRecorded(env = process12.env) {
948
+ function usageRecorded(env = process14.env) {
734
949
  const off = env.KAYNOOO_CLI_NO_USAGE;
735
950
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
736
951
  }
@@ -744,7 +959,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
744
959
  usageError = undefined;
745
960
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
746
961
  }
747
- function recordUsage(entry, env = process12.env) {
962
+ function recordUsage(entry, env = process14.env) {
748
963
  if (!usageRecorded(env))
749
964
  return;
750
965
  try {
@@ -760,10 +975,14 @@ var LEVEL_OPTIONS = {
760
975
  ...OUTPUT_OPTIONS,
761
976
  help: { type: "boolean", short: "h", description: "show this help" }
762
977
  };
763
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
978
+ var TOP_OPTIONS = {
979
+ ...LEVEL_OPTIONS,
980
+ version: { type: "boolean", short: "v", description: "print the version" },
981
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
982
+ };
764
983
  function printError(prefix, message, hint, cause) {
765
- const colors = paint(process13.stderr);
766
- const styled = takesControlCodes(process13.stderr);
984
+ const colors = paint(process15.stderr);
985
+ const styled = takesControlCodes(process15.stderr);
767
986
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
768
987
  const under = (label, text, tint) => text === undefined ? "" : `
769
988
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -840,6 +1059,19 @@ async function leafCandidates(run, words) {
840
1059
  const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
841
1060
  return values === undefined ? [FILES] : values.map(candidateLine);
842
1061
  }
1062
+ var COMPLETIONS = "--completions";
1063
+ function flagValue([flag = "", ...rest]) {
1064
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1065
+ }
1066
+ function printCompletionScript(name, args) {
1067
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1068
+ if (shell === undefined || args.length !== 1) {
1069
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1070
+ return 2;
1071
+ }
1072
+ console.log(completionScript(shell, [name]).trimEnd());
1073
+ return 0;
1074
+ }
843
1075
  async function printCandidates(found) {
844
1076
  for (const line of await found)
845
1077
  console.log(line);
@@ -852,7 +1084,7 @@ function packageVersion(entry = Bun.main) {
852
1084
  } catch {}
853
1085
  for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
854
1086
  try {
855
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1087
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
856
1088
  if (typeof version === "string")
857
1089
  return version;
858
1090
  } catch {}
@@ -863,16 +1095,20 @@ function packageVersion(entry = Bun.main) {
863
1095
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
864
1096
  if (argv[0] === COMPLETE)
865
1097
  return printCandidates(leafCandidates(run, argv.slice(1)));
1098
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1099
+ return printCompletionScript(name, flagValue(argv));
866
1100
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
867
1101
  console.log(version ?? packageVersion());
868
1102
  return 0;
869
1103
  }
870
1104
  let code;
1105
+ const started = performance.now();
871
1106
  try {
872
1107
  code = await run(argv);
873
1108
  } catch (error) {
874
1109
  code = reportThrown(name, error, redact, wantsJson(argv));
875
1110
  }
1111
+ notifyEnd(name, code, performance.now() - started);
876
1112
  if (usage !== false) {
877
1113
  try {
878
1114
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -882,6 +1118,11 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
882
1118
  }
883
1119
  // ../kit/src/folders.ts
884
1120
  var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1121
+ function ignoredFolders(extra = [], where = {}) {
1122
+ const configured = readUserConfig("config", where).ignore;
1123
+ const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1124
+ return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1125
+ }
885
1126
  // ../kit/src/secrets.ts
886
1127
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
887
1128
  // ../kit/src/sessions.ts
@@ -973,6 +1214,7 @@ async function diffTexts(path, before, after) {
973
1214
  var CRLF = /\r?\n/g;
974
1215
  var BRACED_GROUP = /\$\$|\$\{(\w+)\}/g;
975
1216
  var DIGITS = /^\d+$/;
1217
+ var ESCAPE2 = /\\\\|\\([nt])/g;
976
1218
  var LONGEST_LIST = 8;
977
1219
  function linesOf(text, indexes) {
978
1220
  const lines = [];
@@ -1007,8 +1249,16 @@ function firstLineHint(text, from) {
1007
1249
  `).flatMap((line, i) => line.includes(first) ? [i + 1] : []);
1008
1250
  return lines.length === 0 ? "" : ` (its first line is on ${K("line", lines.length)} ${listLines(lines)})`;
1009
1251
  }
1010
- function compile(source) {
1011
- return new RegExp(source, "gm");
1252
+ function compile(source, { ignoreCase, dotAll } = {}) {
1253
+ return new RegExp(source, `gm${ignoreCase === true ? "i" : ""}${dotAll === true ? "s" : ""}`);
1254
+ }
1255
+ function escapes(to) {
1256
+ return to.replace(ESCAPE2, (whole, letter) => {
1257
+ if (letter === undefined)
1258
+ return whole;
1259
+ return letter === "n" ? `
1260
+ ` : "\t";
1261
+ });
1012
1262
  }
1013
1263
  function bracedGroups(to) {
1014
1264
  return to.replace(BRACED_GROUP, (whole, group) => {
@@ -1024,16 +1274,19 @@ function applyPairs(original, pairs) {
1024
1274
  `);
1025
1275
  const lines = [];
1026
1276
  const problems = [];
1277
+ let matched = 0;
1027
1278
  let text = original;
1028
1279
  for (const [i, pair] of pairs.entries()) {
1029
1280
  const label = pairs.length > 1 ? `pair ${i + 1}: ` : "";
1030
1281
  const from = crlf && pair.regex !== true ? pair.from.replace(CRLF, `\r
1031
1282
  `) : pair.from;
1032
- const to = crlf && pair.regex !== true ? pair.to.replace(CRLF, `\r
1033
- `) : pair.to;
1034
- const pattern = pair.regex === true ? compile(from) : undefined;
1283
+ const typed = pair.regex === true ? escapes(pair.to) : pair.to;
1284
+ const to = crlf ? typed.replace(CRLF, `\r
1285
+ `) : typed;
1286
+ const pattern = pair.regex === true ? compile(from, pair) : undefined;
1035
1287
  const indexes = pattern === undefined ? literalIndexes(text, from) : [...text.matchAll(pattern)].map((match) => match.index);
1036
1288
  const found = linesOf(text, indexes);
1289
+ matched += indexes.length;
1037
1290
  const expected = pair.count ?? 1;
1038
1291
  if (pair.all === true ? indexes.length === 0 : indexes.length !== expected) {
1039
1292
  const wanted = pair.all === true ? "at least 1" : String(expected);
@@ -1046,12 +1299,48 @@ function applyPairs(original, pairs) {
1046
1299
  lines.push(...found);
1047
1300
  text = pattern === undefined ? text.split(from).join(to) : text.replace(pattern, bracedGroups(to));
1048
1301
  }
1049
- return { text, lines, problems };
1302
+ return { text, lines, problems, matched };
1303
+ }
1304
+
1305
+ // src/walk.ts
1306
+ import { closeSync, existsSync as existsSync4, openSync, readdirSync, readSync } from "fs";
1307
+ import { join as join7 } from "path";
1308
+ var SNIFF_BYTES = 8000;
1309
+ function isBinary(path) {
1310
+ try {
1311
+ const fd = openSync(path, "r");
1312
+ try {
1313
+ const buffer = Buffer.alloc(SNIFF_BYTES);
1314
+ return buffer.subarray(0, readSync(fd, buffer, 0, SNIFF_BYTES, 0)).includes(0);
1315
+ } finally {
1316
+ closeSync(fd);
1317
+ }
1318
+ } catch {
1319
+ return true;
1320
+ }
1321
+ }
1322
+ function walk(dir, found, ignored) {
1323
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1324
+ if (entry.name.startsWith(".") || ignored.has(entry.name))
1325
+ continue;
1326
+ if (entry.isDirectory())
1327
+ walk(join7(dir, entry.name), found, ignored);
1328
+ else if (entry.isFile())
1329
+ found.push(join7(dir, entry.name));
1330
+ }
1331
+ return found;
1332
+ }
1333
+ async function filesIn(dir) {
1334
+ const listed = await runCommand(["git", "--literal-pathspecs", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", dir]);
1335
+ const paths = listed.code === 0 ? [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync4(path)) : walk(dir, [], ignoredFolders());
1336
+ return paths.filter((path) => !isBinary(path)).sort();
1050
1337
  }
1051
1338
 
1052
1339
  // src/cli.ts
1053
1340
  var USAGE = `sub [options] <file>...: replaces text in files, writing nothing unless every replacement matches as often as expected
1054
1341
 
1342
+ A folder given as a file is walked, .gitignore respected and binary files left out; a file in it where nothing matches is skipped and listed, the count checks holding for the others.
1343
+
1055
1344
  Multi-line text: give no --from, --to or --pairs and pipe SEARCH/REPLACE blocks on stdin from a quoted heredoc, which needs no escaping; a producer silent for 3 s is taken for no heredoc at all, so write a slow one to a file first. The blocks apply in order to the files on the command line, each matching exactly once unless --count or --all says otherwise:
1056
1345
 
1057
1346
  sub src/a.php <<'EOF'
@@ -1069,30 +1358,36 @@ var OPTIONS = {
1069
1358
  to: { type: "string", short: "t", description: "text to put in its place, empty to delete it" },
1070
1359
  count: { type: "string", short: "n", description: "matches expected in each file (default 1)" },
1071
1360
  all: { type: "boolean", short: "a", description: "replace every match, expecting at least one in each file" },
1072
- regex: { type: "boolean", short: "r", description: "--from is a regular expression (^ and $ match each line), --to may use $1, ${1}, $<name> and ${name}" },
1073
- pairs: { type: "string", short: "p", description: "JSON array of {from, to, count?, all?, regex?} applied in order: inline when it starts with [, else a file or - for stdin" },
1361
+ "skip-missing": { type: "boolean", description: "with --all, leave a file where no pair matches alone and list it, instead of failing; the counts still hold for the files that match" },
1362
+ regex: { type: "boolean", short: "r", description: "--from is a regular expression (^ and $ match each line), --to may use $1, ${1}, $<name> and ${name}, and a \n or \t in it is a newline or a tab" },
1363
+ "ignore-case": { type: "boolean", short: "i", description: "with --regex, match without regard to case" },
1364
+ dotall: { type: "boolean", short: "s", description: "with --regex, let . match a newline too" },
1365
+ pairs: { type: "string", short: "p", description: "JSON array of {from, to, count?, all?, regex?, ignoreCase?, dotAll?} applied in order: inline when it starts with [, else a file or - for stdin" },
1074
1366
  diff: { type: "boolean", short: "d", description: "print each file's unified diff" },
1075
1367
  "dry-run": { type: "boolean", description: "show what would change without writing" },
1076
1368
  quiet: { type: "boolean", short: "q", description: "print nothing on success, the diff aside" },
1077
- json: jsonOption("{dryRun, files: [{path, replacements, lines, added, removed, diff?}]}, or {error, failures: [{path, problem}]} on stderr when nothing is written")
1369
+ json: jsonOption("{dryRun, files: [{path, replacements, lines, added, removed, diff?}], skipped? (the files --skip-missing left alone)}, or {error, failures: [{path, problem}]} on stderr when nothing is written")
1078
1370
  };
1079
- var PAIR_KEYS = ["from", "to", "count", "all", "regex"];
1371
+ var PAIR_KEYS = ["from", "to", "count", "all", "regex", "ignoreCase", "dotAll"];
1080
1372
  function checkPattern(pair, label) {
1081
1373
  if (pair.from === "")
1082
1374
  fail(`${label}--from is empty`);
1083
1375
  if (pair.regex !== true)
1084
1376
  return;
1085
1377
  try {
1086
- compile(pair.from);
1378
+ compile(pair.from, pair);
1087
1379
  } catch (error) {
1088
1380
  fail(`${label}--from is no valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
1089
1381
  }
1090
1382
  }
1383
+ function isFlag(value) {
1384
+ return value === undefined || typeof value === "boolean";
1385
+ }
1091
1386
  function pairFrom(item, i, defaults) {
1092
1387
  const label = `pair ${i + 1}: `;
1093
1388
  if (typeof item !== "object" || item === null || Array.isArray(item))
1094
1389
  fail(`${label}give an object {from, to}`);
1095
- const { from, to, count, all, regex, ...rest } = item;
1390
+ const { from, to, count, all, regex, ignoreCase, dotAll, ...rest } = item;
1096
1391
  const unknown = Object.keys(rest);
1097
1392
  if (unknown.length > 0)
1098
1393
  fail(`${label}unknown ${K("key", unknown.length)} ${unknown.join(", ")}, known: ${PAIR_KEYS.join(", ")}`);
@@ -1100,9 +1395,11 @@ function pairFrom(item, i, defaults) {
1100
1395
  fail(`${label}from and to must both be strings`);
1101
1396
  if (count !== undefined && (typeof count !== "number" || !Number.isInteger(count) || count < 1))
1102
1397
  fail(`${label}count takes a whole number from 1`);
1103
- if (all !== undefined && typeof all !== "boolean" || regex !== undefined && typeof regex !== "boolean")
1104
- fail(`${label}all and regex take true or false`);
1105
- const pair = { from, to, count: count ?? defaults.count ?? 1, all: all ?? defaults.all, regex: regex ?? defaults.regex };
1398
+ if (!isFlag(all) || !isFlag(regex) || !isFlag(ignoreCase) || !isFlag(dotAll))
1399
+ fail(`${label}all, regex, ignoreCase and dotAll take true or false`);
1400
+ const pair = { from, to, count: count ?? defaults.count ?? 1, all: all ?? defaults.all, regex: regex ?? defaults.regex, ignoreCase: ignoreCase ?? defaults.ignoreCase, dotAll: dotAll ?? defaults.dotAll };
1401
+ if ((pair.ignoreCase === true || pair.dotAll === true) && pair.regex !== true)
1402
+ fail(`${label}ignoreCase and dotAll need regex`);
1106
1403
  checkPattern(pair, label);
1107
1404
  return pair;
1108
1405
  }
@@ -1121,7 +1418,7 @@ async function readPairs(path, defaults) {
1121
1418
  }
1122
1419
  function writable(path) {
1123
1420
  try {
1124
- accessSync(path, constants.W_OK);
1421
+ accessSync(path, constants2.W_OK);
1125
1422
  return true;
1126
1423
  } catch {
1127
1424
  return false;
@@ -1130,7 +1427,7 @@ function writable(path) {
1130
1427
  var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
1131
1428
  function readUtf8(path) {
1132
1429
  try {
1133
- return UTF8.decode(readFileSync4(path));
1430
+ return UTF8.decode(readFileSync5(path));
1134
1431
  } catch {
1135
1432
  return;
1136
1433
  }
@@ -1153,7 +1450,7 @@ function dedupe(paths) {
1153
1450
  }
1154
1451
  function writeAtomic(path, text) {
1155
1452
  const target = realpathSync3(path);
1156
- const temp = `${target}.sub-${process15.pid}`;
1453
+ const temp = `${target}.sub-${process17.pid}`;
1157
1454
  try {
1158
1455
  writeFileSync2(temp, text);
1159
1456
  chmodSync(temp, (statSync2(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
@@ -1165,30 +1462,30 @@ function writeAtomic(path, text) {
1165
1462
  }
1166
1463
  var STDIN_SILENCE_MS = 3000;
1167
1464
  async function blocksOnStdin(files) {
1168
- const extra = files.slice(1).filter((path) => !existsSync3(path));
1465
+ const extra = files.slice(1).filter((path) => !existsSync5(path));
1169
1466
  const strings = extra.length === 0 ? "" : `${extra.map((path) => `no file ${path}`).join(", ")}: with several strings on the command line use --from and --to, as in sub --from old --to new ${files[0]}
1170
1467
 
1171
1468
  `;
1172
1469
  const hint = `${strings}give --from and --to, or pipe SEARCH/REPLACE blocks on stdin from a heredoc
1173
1470
 
1174
1471
  ${USAGE}`;
1175
- if (process15.stdin.isTTY)
1472
+ if (process17.stdin.isTTY)
1176
1473
  fail(hint);
1177
1474
  return new Promise((resolve) => {
1178
1475
  const chunks = [];
1179
1476
  const timer = setTimeout(() => {
1180
1477
  console.error(`error: sub: ${hint}`);
1181
- process15.exit(2);
1478
+ process17.exit(2);
1182
1479
  }, STDIN_SILENCE_MS);
1183
- process15.stdin.on("data", (chunk) => {
1480
+ process17.stdin.on("data", (chunk) => {
1184
1481
  clearTimeout(timer);
1185
1482
  chunks.push(chunk);
1186
1483
  });
1187
- process15.stdin.on("end", () => {
1484
+ process17.stdin.on("end", () => {
1188
1485
  clearTimeout(timer);
1189
1486
  if (chunks.length === 0 && extra.length > 0) {
1190
1487
  console.error(`error: sub: ${hint}`);
1191
- process15.exit(2);
1488
+ process17.exit(2);
1192
1489
  }
1193
1490
  resolve(Buffer.concat(chunks).toString("utf8"));
1194
1491
  });
@@ -1212,7 +1509,7 @@ ${USAGE}`);
1212
1509
  fail(`give --from and --to (--to '' deletes), or --pairs
1213
1510
 
1214
1511
  ${USAGE}`);
1215
- pairs = [{ from: values.from, to: values.to, count: defaults.count ?? 1, all: defaults.all, regex: defaults.regex }];
1512
+ pairs = [{ from: values.from, to: values.to, count: defaults.count ?? 1, all: defaults.all, regex: defaults.regex, ignoreCase: defaults.ignoreCase, dotAll: defaults.dotAll }];
1216
1513
  checkPattern(pairs[0], "");
1217
1514
  }
1218
1515
  for (const path of files)
@@ -1223,7 +1520,7 @@ ${USAGE}`);
1223
1520
  if (typeof blocks === "string")
1224
1521
  fail(`blocks: ${blocks}`);
1225
1522
  for (const [i, block] of blocks.entries()) {
1226
- const pair = { from: block.from, to: block.to, count: defaults.count ?? 1, all: defaults.all, regex: defaults.regex };
1523
+ const pair = { from: block.from, to: block.to, count: defaults.count ?? 1, all: defaults.all, regex: defaults.regex, ignoreCase: defaults.ignoreCase, dotAll: defaults.dotAll };
1227
1524
  const named = block.file === undefined ? undefined : normalize(block.file);
1228
1525
  const targets = named === undefined ? files : [spellings.get(canonical(named)) ?? named];
1229
1526
  if (named !== undefined && !spellings.has(canonical(named)))
@@ -1243,35 +1540,57 @@ ${USAGE}`);
1243
1540
  async function main(argv) {
1244
1541
  const parsed = parse(argv, USAGE, OPTIONS, { exits: EXITS, replaces: "sed -i and one-off bun -e or python editors", examples: [["sub src/a.php <<'EOF' (SEARCH/REPLACE blocks, see above)", "multi-line text, no escaping"], ["sub --from oldName --to newName --all src/a.ts src/b.ts", "every match in two files"], ['sub --regex --from "v(\\d+)" --to "v$1.0" --dry-run --diff README.md', "the diff, nothing written"]] });
1245
1542
  const { values, positionals } = parsed;
1246
- const files = dedupe(positionals.map((path) => normalize(path)));
1543
+ const walked = new Set;
1544
+ const given = await Promise.all(positionals.map(async (path) => {
1545
+ if (statSync2(path, { throwIfNoEntry: false })?.isDirectory() !== true)
1546
+ return [normalize(path)];
1547
+ const inside = (await filesIn(path)).map(normalize);
1548
+ for (const file of inside)
1549
+ walked.add(file);
1550
+ return inside;
1551
+ }));
1552
+ const files = dedupe(given.flat());
1247
1553
  if (values.count !== undefined && values.all === true)
1248
1554
  fail("--count and --all exclude each other");
1249
- const defaults = { count: values.count === undefined ? undefined : wholeNumber(values.count, "count", 1), all: values.all === true, regex: values.regex === true };
1555
+ if (values["skip-missing"] === true && values.all !== true)
1556
+ fail("--skip-missing needs --all");
1557
+ if ((values["ignore-case"] === true || values.dotall === true) && values.regex !== true)
1558
+ fail("--ignore-case and --dotall need --regex");
1559
+ const defaults = { count: values.count === undefined ? undefined : wholeNumber(values.count, "count", 1), all: values.all === true, regex: values.regex === true, ignoreCase: values["ignore-case"] === true, dotAll: values.dotall === true };
1250
1560
  const edits = await plan(values, files, defaults);
1251
1561
  const changes = [];
1252
1562
  const problems = [];
1563
+ const skipped = [];
1253
1564
  for (const [path, pairs] of edits) {
1254
- if (!existsSync3(path)) {
1565
+ if (!existsSync5(path)) {
1255
1566
  problems.push({ path, problem: "no such file" });
1256
1567
  continue;
1257
1568
  }
1258
1569
  const before = readUtf8(path);
1570
+ if (before === undefined && walked.has(path))
1571
+ continue;
1259
1572
  if (before === undefined) {
1260
1573
  problems.push({ path, problem: "not valid UTF-8, left alone" });
1261
1574
  continue;
1262
1575
  }
1263
1576
  const applied = applyPairs(before, pairs);
1577
+ if ((values["skip-missing"] === true || walked.has(path)) && applied.matched === 0) {
1578
+ skipped.push(path);
1579
+ continue;
1580
+ }
1264
1581
  problems.push(...applied.problems.map((problem) => ({ path, problem })));
1265
1582
  if (applied.problems.length === 0 && values["dry-run"] !== true && !writable(path))
1266
1583
  problems.push({ path, problem: "not writable" });
1267
1584
  changes.push({ path, before, after: applied.text, lines: applied.lines });
1268
1585
  }
1269
1586
  const json = values.json === true;
1587
+ if (skipped.length > 0 && changes.length === 0 && problems.length === 0)
1588
+ problems.push({ path: skipped.join(", "), problem: "no match in any file" });
1270
1589
  if (problems.length > 0) {
1271
1590
  if (json)
1272
1591
  console.error(JSON.stringify({ error: "nothing written", failures: problems }));
1273
1592
  else
1274
- console.error(`${role("problem", process15.stderr)("sub: nothing written")}
1593
+ console.error(`${role("problem", process17.stderr)("sub: nothing written")}
1275
1594
  ${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
1276
1595
  `)}`);
1277
1596
  return 1;
@@ -1280,7 +1599,7 @@ ${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
1280
1599
  for (const change of changes)
1281
1600
  change.diff = await diffTexts(change.path, change.before, change.after);
1282
1601
  } catch (error) {
1283
- console.error(`${role("problem", process15.stderr)("sub: nothing written")}
1602
+ console.error(`${role("problem", process17.stderr)("sub: nothing written")}
1284
1603
  ${error instanceof Error ? error.message : String(error)}`);
1285
1604
  return 1;
1286
1605
  }
@@ -1295,14 +1614,16 @@ ${error instanceof Error ? error.message : String(error)}`);
1295
1614
  continue;
1296
1615
  }
1297
1616
  if (values.quiet !== true)
1298
- console.log(`${role("path", process15.stdout)(path)}: ${go(lines.length, "replacement")} on ${K("line", lines.length, { zero: "plural" })} ${listLines(lines)}, ${role(diff.added === 0 ? "label" : "ok", process15.stdout)(`+${diff.added}`)} ${role(diff.removed === 0 ? "label" : "problem", process15.stdout)(`-${diff.removed}`)}`);
1617
+ console.log(`${role("path", process17.stdout)(path)}: ${go(lines.length, "replacement")} on ${K("line", lines.length, { zero: "plural" })} ${listLines(lines)}, ${role(diff.added === 0 ? "label" : "ok", process17.stdout)(`+${diff.added}`)} ${role(diff.removed === 0 ? "label" : "problem", process17.stdout)(`-${diff.removed}`)}`);
1299
1618
  if (values.diff === true && diff.unified !== "")
1300
- process15.stdout.write(diff.unified);
1619
+ process17.stdout.write(diff.unified);
1301
1620
  }
1302
1621
  if (json)
1303
- printJson({ dryRun: values["dry-run"] === true, files: done });
1304
- else if (values["dry-run"] === true && values.quiet !== true)
1622
+ printJson({ dryRun: values["dry-run"] === true, files: done, ...values["skip-missing"] === true ? { skipped } : {} });
1623
+ else if (values.quiet !== true && skipped.length > 0)
1624
+ console.log(`skipped ${go(skipped.length, "file")} with no match: ${skipped.join(", ")}`);
1625
+ if (!json && values["dry-run"] === true && values.quiet !== true)
1305
1626
  console.log("dry run: nothing written");
1306
1627
  return 0;
1307
1628
  }
1308
- process15.exitCode = await runMain({ name: "sub", run: main });
1629
+ process17.exitCode = await runMain({ name: "sub", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-edit",
3
3
  "type": "module",
4
- "version": "0.10.1",
4
+ "version": "0.11.1",
5
5
  "description": "sub: text replaced in files for Claude Code, written only when every replacement matches as often as expected.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -39,6 +39,6 @@
39
39
  "@kaynooo/utils": "3.0.0"
40
40
  },
41
41
  "devDependencies": {
42
- "@kaynooo/cli-kit": "0.38.2"
42
+ "@kaynooo/cli-kit": "0.41.0"
43
43
  }
44
44
  }