@kaynooo/cli-edit 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +303 -61
  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));
@@ -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,129 @@ 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/notify.ts
706
846
  import process13 from "process";
847
+ var NOTIFY_AFTER_MS = 1e4;
848
+ var CANCELLED = 130;
849
+ function base64(text) {
850
+ return Buffer.from(text).toString("base64");
851
+ }
852
+ function notification(title, body, env = process13.env) {
853
+ const id = `kit${process13.pid}`;
854
+ 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\\`];
855
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
856
+ }
857
+ function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
858
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
859
+ return;
860
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
861
+ }
707
862
 
708
863
  // ../kit/src/usage.ts
709
864
  import { appendFileSync, mkdirSync } from "fs";
710
865
  import { homedir as homedir3 } from "os";
711
866
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
712
- import process12 from "process";
867
+ import process14 from "process";
713
868
 
714
869
  // ../kit/src/logs.ts
715
870
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -723,14 +878,14 @@ var usageError;
723
878
  function noteUsageError(message) {
724
879
  usageError = message;
725
880
  }
726
- function stateHome(env = process12.env) {
881
+ function stateHome(env = process14.env) {
727
882
  const dir = env.XDG_STATE_HOME;
728
883
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
729
884
  }
730
- function usagePath(env = process12.env) {
885
+ function usagePath(env = process14.env) {
731
886
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
732
887
  }
733
- function usageRecorded(env = process12.env) {
888
+ function usageRecorded(env = process14.env) {
734
889
  const off = env.KAYNOOO_CLI_NO_USAGE;
735
890
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
736
891
  }
@@ -744,7 +899,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
744
899
  usageError = undefined;
745
900
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
746
901
  }
747
- function recordUsage(entry, env = process12.env) {
902
+ function recordUsage(entry, env = process14.env) {
748
903
  if (!usageRecorded(env))
749
904
  return;
750
905
  try {
@@ -762,8 +917,8 @@ var LEVEL_OPTIONS = {
762
917
  };
763
918
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
764
919
  function printError(prefix, message, hint, cause) {
765
- const colors = paint(process13.stderr);
766
- const styled = takesControlCodes(process13.stderr);
920
+ const colors = paint(process15.stderr);
921
+ const styled = takesControlCodes(process15.stderr);
767
922
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
768
923
  const under = (label, text, tint) => text === undefined ? "" : `
769
924
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -852,7 +1007,7 @@ function packageVersion(entry = Bun.main) {
852
1007
  } catch {}
853
1008
  for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
854
1009
  try {
855
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1010
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
856
1011
  if (typeof version === "string")
857
1012
  return version;
858
1013
  } catch {}
@@ -868,11 +1023,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
868
1023
  return 0;
869
1024
  }
870
1025
  let code;
1026
+ const started = performance.now();
871
1027
  try {
872
1028
  code = await run(argv);
873
1029
  } catch (error) {
874
1030
  code = reportThrown(name, error, redact, wantsJson(argv));
875
1031
  }
1032
+ notifyEnd(name, code, performance.now() - started);
876
1033
  if (usage !== false) {
877
1034
  try {
878
1035
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -882,6 +1039,11 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
882
1039
  }
883
1040
  // ../kit/src/folders.ts
884
1041
  var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
1042
+ function ignoredFolders(extra = [], where = {}) {
1043
+ const configured = readUserConfig("config", where).ignore;
1044
+ const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
1045
+ return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
1046
+ }
885
1047
  // ../kit/src/secrets.ts
886
1048
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
887
1049
  // ../kit/src/sessions.ts
@@ -973,6 +1135,7 @@ async function diffTexts(path, before, after) {
973
1135
  var CRLF = /\r?\n/g;
974
1136
  var BRACED_GROUP = /\$\$|\$\{(\w+)\}/g;
975
1137
  var DIGITS = /^\d+$/;
1138
+ var ESCAPE2 = /\\\\|\\([nt])/g;
976
1139
  var LONGEST_LIST = 8;
977
1140
  function linesOf(text, indexes) {
978
1141
  const lines = [];
@@ -1007,8 +1170,16 @@ function firstLineHint(text, from) {
1007
1170
  `).flatMap((line, i) => line.includes(first) ? [i + 1] : []);
1008
1171
  return lines.length === 0 ? "" : ` (its first line is on ${K("line", lines.length)} ${listLines(lines)})`;
1009
1172
  }
1010
- function compile(source) {
1011
- return new RegExp(source, "gm");
1173
+ function compile(source, { ignoreCase, dotAll } = {}) {
1174
+ return new RegExp(source, `gm${ignoreCase === true ? "i" : ""}${dotAll === true ? "s" : ""}`);
1175
+ }
1176
+ function escapes(to) {
1177
+ return to.replace(ESCAPE2, (whole, letter) => {
1178
+ if (letter === undefined)
1179
+ return whole;
1180
+ return letter === "n" ? `
1181
+ ` : "\t";
1182
+ });
1012
1183
  }
1013
1184
  function bracedGroups(to) {
1014
1185
  return to.replace(BRACED_GROUP, (whole, group) => {
@@ -1024,16 +1195,19 @@ function applyPairs(original, pairs) {
1024
1195
  `);
1025
1196
  const lines = [];
1026
1197
  const problems = [];
1198
+ let matched = 0;
1027
1199
  let text = original;
1028
1200
  for (const [i, pair] of pairs.entries()) {
1029
1201
  const label = pairs.length > 1 ? `pair ${i + 1}: ` : "";
1030
1202
  const from = crlf && pair.regex !== true ? pair.from.replace(CRLF, `\r
1031
1203
  `) : 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;
1204
+ const typed = pair.regex === true ? escapes(pair.to) : pair.to;
1205
+ const to = crlf ? typed.replace(CRLF, `\r
1206
+ `) : typed;
1207
+ const pattern = pair.regex === true ? compile(from, pair) : undefined;
1035
1208
  const indexes = pattern === undefined ? literalIndexes(text, from) : [...text.matchAll(pattern)].map((match) => match.index);
1036
1209
  const found = linesOf(text, indexes);
1210
+ matched += indexes.length;
1037
1211
  const expected = pair.count ?? 1;
1038
1212
  if (pair.all === true ? indexes.length === 0 : indexes.length !== expected) {
1039
1213
  const wanted = pair.all === true ? "at least 1" : String(expected);
@@ -1046,12 +1220,48 @@ function applyPairs(original, pairs) {
1046
1220
  lines.push(...found);
1047
1221
  text = pattern === undefined ? text.split(from).join(to) : text.replace(pattern, bracedGroups(to));
1048
1222
  }
1049
- return { text, lines, problems };
1223
+ return { text, lines, problems, matched };
1224
+ }
1225
+
1226
+ // src/walk.ts
1227
+ import { closeSync, existsSync as existsSync4, openSync, readdirSync, readSync } from "fs";
1228
+ import { join as join7 } from "path";
1229
+ var SNIFF_BYTES = 8000;
1230
+ function isBinary(path) {
1231
+ try {
1232
+ const fd = openSync(path, "r");
1233
+ try {
1234
+ const buffer = Buffer.alloc(SNIFF_BYTES);
1235
+ return buffer.subarray(0, readSync(fd, buffer, 0, SNIFF_BYTES, 0)).includes(0);
1236
+ } finally {
1237
+ closeSync(fd);
1238
+ }
1239
+ } catch {
1240
+ return true;
1241
+ }
1242
+ }
1243
+ function walk(dir, found, ignored) {
1244
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1245
+ if (entry.name.startsWith(".") || ignored.has(entry.name))
1246
+ continue;
1247
+ if (entry.isDirectory())
1248
+ walk(join7(dir, entry.name), found, ignored);
1249
+ else if (entry.isFile())
1250
+ found.push(join7(dir, entry.name));
1251
+ }
1252
+ return found;
1253
+ }
1254
+ async function filesIn(dir) {
1255
+ const listed = await runCommand(["git", "--literal-pathspecs", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", dir]);
1256
+ const paths = listed.code === 0 ? [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync4(path)) : walk(dir, [], ignoredFolders());
1257
+ return paths.filter((path) => !isBinary(path)).sort();
1050
1258
  }
1051
1259
 
1052
1260
  // src/cli.ts
1053
1261
  var USAGE = `sub [options] <file>...: replaces text in files, writing nothing unless every replacement matches as often as expected
1054
1262
 
1263
+ 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.
1264
+
1055
1265
  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
1266
 
1057
1267
  sub src/a.php <<'EOF'
@@ -1069,30 +1279,36 @@ var OPTIONS = {
1069
1279
  to: { type: "string", short: "t", description: "text to put in its place, empty to delete it" },
1070
1280
  count: { type: "string", short: "n", description: "matches expected in each file (default 1)" },
1071
1281
  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" },
1282
+ "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" },
1283
+ 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" },
1284
+ "ignore-case": { type: "boolean", short: "i", description: "with --regex, match without regard to case" },
1285
+ dotall: { type: "boolean", short: "s", description: "with --regex, let . match a newline too" },
1286
+ 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
1287
  diff: { type: "boolean", short: "d", description: "print each file's unified diff" },
1075
1288
  "dry-run": { type: "boolean", description: "show what would change without writing" },
1076
1289
  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")
1290
+ 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
1291
  };
1079
- var PAIR_KEYS = ["from", "to", "count", "all", "regex"];
1292
+ var PAIR_KEYS = ["from", "to", "count", "all", "regex", "ignoreCase", "dotAll"];
1080
1293
  function checkPattern(pair, label) {
1081
1294
  if (pair.from === "")
1082
1295
  fail(`${label}--from is empty`);
1083
1296
  if (pair.regex !== true)
1084
1297
  return;
1085
1298
  try {
1086
- compile(pair.from);
1299
+ compile(pair.from, pair);
1087
1300
  } catch (error) {
1088
1301
  fail(`${label}--from is no valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
1089
1302
  }
1090
1303
  }
1304
+ function isFlag(value) {
1305
+ return value === undefined || typeof value === "boolean";
1306
+ }
1091
1307
  function pairFrom(item, i, defaults) {
1092
1308
  const label = `pair ${i + 1}: `;
1093
1309
  if (typeof item !== "object" || item === null || Array.isArray(item))
1094
1310
  fail(`${label}give an object {from, to}`);
1095
- const { from, to, count, all, regex, ...rest } = item;
1311
+ const { from, to, count, all, regex, ignoreCase, dotAll, ...rest } = item;
1096
1312
  const unknown = Object.keys(rest);
1097
1313
  if (unknown.length > 0)
1098
1314
  fail(`${label}unknown ${K("key", unknown.length)} ${unknown.join(", ")}, known: ${PAIR_KEYS.join(", ")}`);
@@ -1100,9 +1316,11 @@ function pairFrom(item, i, defaults) {
1100
1316
  fail(`${label}from and to must both be strings`);
1101
1317
  if (count !== undefined && (typeof count !== "number" || !Number.isInteger(count) || count < 1))
1102
1318
  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 };
1319
+ if (!isFlag(all) || !isFlag(regex) || !isFlag(ignoreCase) || !isFlag(dotAll))
1320
+ fail(`${label}all, regex, ignoreCase and dotAll take true or false`);
1321
+ 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 };
1322
+ if ((pair.ignoreCase === true || pair.dotAll === true) && pair.regex !== true)
1323
+ fail(`${label}ignoreCase and dotAll need regex`);
1106
1324
  checkPattern(pair, label);
1107
1325
  return pair;
1108
1326
  }
@@ -1121,7 +1339,7 @@ async function readPairs(path, defaults) {
1121
1339
  }
1122
1340
  function writable(path) {
1123
1341
  try {
1124
- accessSync(path, constants.W_OK);
1342
+ accessSync(path, constants2.W_OK);
1125
1343
  return true;
1126
1344
  } catch {
1127
1345
  return false;
@@ -1130,7 +1348,7 @@ function writable(path) {
1130
1348
  var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
1131
1349
  function readUtf8(path) {
1132
1350
  try {
1133
- return UTF8.decode(readFileSync4(path));
1351
+ return UTF8.decode(readFileSync5(path));
1134
1352
  } catch {
1135
1353
  return;
1136
1354
  }
@@ -1153,7 +1371,7 @@ function dedupe(paths) {
1153
1371
  }
1154
1372
  function writeAtomic(path, text) {
1155
1373
  const target = realpathSync3(path);
1156
- const temp = `${target}.sub-${process15.pid}`;
1374
+ const temp = `${target}.sub-${process17.pid}`;
1157
1375
  try {
1158
1376
  writeFileSync2(temp, text);
1159
1377
  chmodSync(temp, (statSync2(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
@@ -1165,30 +1383,30 @@ function writeAtomic(path, text) {
1165
1383
  }
1166
1384
  var STDIN_SILENCE_MS = 3000;
1167
1385
  async function blocksOnStdin(files) {
1168
- const extra = files.slice(1).filter((path) => !existsSync3(path));
1386
+ const extra = files.slice(1).filter((path) => !existsSync5(path));
1169
1387
  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
1388
 
1171
1389
  `;
1172
1390
  const hint = `${strings}give --from and --to, or pipe SEARCH/REPLACE blocks on stdin from a heredoc
1173
1391
 
1174
1392
  ${USAGE}`;
1175
- if (process15.stdin.isTTY)
1393
+ if (process17.stdin.isTTY)
1176
1394
  fail(hint);
1177
1395
  return new Promise((resolve) => {
1178
1396
  const chunks = [];
1179
1397
  const timer = setTimeout(() => {
1180
1398
  console.error(`error: sub: ${hint}`);
1181
- process15.exit(2);
1399
+ process17.exit(2);
1182
1400
  }, STDIN_SILENCE_MS);
1183
- process15.stdin.on("data", (chunk) => {
1401
+ process17.stdin.on("data", (chunk) => {
1184
1402
  clearTimeout(timer);
1185
1403
  chunks.push(chunk);
1186
1404
  });
1187
- process15.stdin.on("end", () => {
1405
+ process17.stdin.on("end", () => {
1188
1406
  clearTimeout(timer);
1189
1407
  if (chunks.length === 0 && extra.length > 0) {
1190
1408
  console.error(`error: sub: ${hint}`);
1191
- process15.exit(2);
1409
+ process17.exit(2);
1192
1410
  }
1193
1411
  resolve(Buffer.concat(chunks).toString("utf8"));
1194
1412
  });
@@ -1212,7 +1430,7 @@ ${USAGE}`);
1212
1430
  fail(`give --from and --to (--to '' deletes), or --pairs
1213
1431
 
1214
1432
  ${USAGE}`);
1215
- pairs = [{ from: values.from, to: values.to, count: defaults.count ?? 1, all: defaults.all, regex: defaults.regex }];
1433
+ pairs = [{ from: values.from, to: values.to, count: defaults.count ?? 1, all: defaults.all, regex: defaults.regex, ignoreCase: defaults.ignoreCase, dotAll: defaults.dotAll }];
1216
1434
  checkPattern(pairs[0], "");
1217
1435
  }
1218
1436
  for (const path of files)
@@ -1223,7 +1441,7 @@ ${USAGE}`);
1223
1441
  if (typeof blocks === "string")
1224
1442
  fail(`blocks: ${blocks}`);
1225
1443
  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 };
1444
+ 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
1445
  const named = block.file === undefined ? undefined : normalize(block.file);
1228
1446
  const targets = named === undefined ? files : [spellings.get(canonical(named)) ?? named];
1229
1447
  if (named !== undefined && !spellings.has(canonical(named)))
@@ -1243,35 +1461,57 @@ ${USAGE}`);
1243
1461
  async function main(argv) {
1244
1462
  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
1463
  const { values, positionals } = parsed;
1246
- const files = dedupe(positionals.map((path) => normalize(path)));
1464
+ const walked = new Set;
1465
+ const given = await Promise.all(positionals.map(async (path) => {
1466
+ if (statSync2(path, { throwIfNoEntry: false })?.isDirectory() !== true)
1467
+ return [normalize(path)];
1468
+ const inside = (await filesIn(path)).map(normalize);
1469
+ for (const file of inside)
1470
+ walked.add(file);
1471
+ return inside;
1472
+ }));
1473
+ const files = dedupe(given.flat());
1247
1474
  if (values.count !== undefined && values.all === true)
1248
1475
  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 };
1476
+ if (values["skip-missing"] === true && values.all !== true)
1477
+ fail("--skip-missing needs --all");
1478
+ if ((values["ignore-case"] === true || values.dotall === true) && values.regex !== true)
1479
+ fail("--ignore-case and --dotall need --regex");
1480
+ 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
1481
  const edits = await plan(values, files, defaults);
1251
1482
  const changes = [];
1252
1483
  const problems = [];
1484
+ const skipped = [];
1253
1485
  for (const [path, pairs] of edits) {
1254
- if (!existsSync3(path)) {
1486
+ if (!existsSync5(path)) {
1255
1487
  problems.push({ path, problem: "no such file" });
1256
1488
  continue;
1257
1489
  }
1258
1490
  const before = readUtf8(path);
1491
+ if (before === undefined && walked.has(path))
1492
+ continue;
1259
1493
  if (before === undefined) {
1260
1494
  problems.push({ path, problem: "not valid UTF-8, left alone" });
1261
1495
  continue;
1262
1496
  }
1263
1497
  const applied = applyPairs(before, pairs);
1498
+ if ((values["skip-missing"] === true || walked.has(path)) && applied.matched === 0) {
1499
+ skipped.push(path);
1500
+ continue;
1501
+ }
1264
1502
  problems.push(...applied.problems.map((problem) => ({ path, problem })));
1265
1503
  if (applied.problems.length === 0 && values["dry-run"] !== true && !writable(path))
1266
1504
  problems.push({ path, problem: "not writable" });
1267
1505
  changes.push({ path, before, after: applied.text, lines: applied.lines });
1268
1506
  }
1269
1507
  const json = values.json === true;
1508
+ if (skipped.length > 0 && changes.length === 0 && problems.length === 0)
1509
+ problems.push({ path: skipped.join(", "), problem: "no match in any file" });
1270
1510
  if (problems.length > 0) {
1271
1511
  if (json)
1272
1512
  console.error(JSON.stringify({ error: "nothing written", failures: problems }));
1273
1513
  else
1274
- console.error(`${role("problem", process15.stderr)("sub: nothing written")}
1514
+ console.error(`${role("problem", process17.stderr)("sub: nothing written")}
1275
1515
  ${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
1276
1516
  `)}`);
1277
1517
  return 1;
@@ -1280,7 +1520,7 @@ ${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
1280
1520
  for (const change of changes)
1281
1521
  change.diff = await diffTexts(change.path, change.before, change.after);
1282
1522
  } catch (error) {
1283
- console.error(`${role("problem", process15.stderr)("sub: nothing written")}
1523
+ console.error(`${role("problem", process17.stderr)("sub: nothing written")}
1284
1524
  ${error instanceof Error ? error.message : String(error)}`);
1285
1525
  return 1;
1286
1526
  }
@@ -1295,14 +1535,16 @@ ${error instanceof Error ? error.message : String(error)}`);
1295
1535
  continue;
1296
1536
  }
1297
1537
  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}`)}`);
1538
+ 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
1539
  if (values.diff === true && diff.unified !== "")
1300
- process15.stdout.write(diff.unified);
1540
+ process17.stdout.write(diff.unified);
1301
1541
  }
1302
1542
  if (json)
1303
- printJson({ dryRun: values["dry-run"] === true, files: done });
1304
- else if (values["dry-run"] === true && values.quiet !== true)
1543
+ printJson({ dryRun: values["dry-run"] === true, files: done, ...values["skip-missing"] === true ? { skipped } : {} });
1544
+ else if (values.quiet !== true && skipped.length > 0)
1545
+ console.log(`skipped ${go(skipped.length, "file")} with no match: ${skipped.join(", ")}`);
1546
+ if (!json && values["dry-run"] === true && values.quiet !== true)
1305
1547
  console.log("dry run: nothing written");
1306
1548
  return 0;
1307
1549
  }
1308
- process15.exitCode = await runMain({ name: "sub", run: main });
1550
+ 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.0",
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.39.0"
43
43
  }
44
44
  }