@kaynooo/cli-edit 0.9.1 → 0.10.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 +73 -50
  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 readFileSync3, realpathSync as realpathSync2, renameSync, rmSync as rmSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
6
- import { normalize, resolve as resolve3 } from "path";
7
- import process14 from "process";
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";
6
+ import { normalize, resolve as resolve4 } from "path";
7
+ import process15 from "process";
8
8
  // ../kit/src/args.ts
9
9
  import process10 from "process";
10
10
  import { parseArgs } from "util";
@@ -367,18 +367,14 @@ var FULL_STOP = /\.$/;
367
367
  function usageLine(usage, colors = paint(process8.stdout)) {
368
368
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
369
369
  }
370
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
371
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
370
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
371
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
372
372
  `);
373
373
  }
374
374
  function exitRows(exits, colors = paint(process8.stdout)) {
375
375
  if (exits.length === 0)
376
376
  return [];
377
- const width = Math.max(...exits.map(([code]) => String(code).length));
378
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
379
- }
380
- function replacesRows(replaces, colors = paint(process8.stdout)) {
381
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
377
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
382
378
  }
383
379
  function wantsHelpJson(env = process8.env) {
384
380
  return env.KIT_HELP === "json";
@@ -675,21 +671,45 @@ function nearestOption(message, options, allowNegative) {
675
671
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
676
672
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
677
673
  }
674
+ // ../kit/src/argv.ts
675
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
676
+ import { resolve as resolve3 } from "path";
677
+ import process11 from "process";
678
+ function commandLine() {
679
+ try {
680
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
681
+ } catch {
682
+ return;
683
+ }
684
+ }
685
+ function realPath(word) {
686
+ try {
687
+ return realpathSync(resolve3(word));
688
+ } catch {
689
+ return;
690
+ }
691
+ }
692
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
693
+ const target = script === undefined ? undefined : realPath(script) ?? script;
694
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
695
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
696
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
697
+ }
678
698
  // ../kit/src/progress.ts
679
699
  var ESC = String.fromCharCode(27);
680
700
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
681
701
  var RESET_STYLE = `${ESC}[0m`;
682
702
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
683
703
  // ../kit/src/cli.ts
684
- import { readFileSync as readFileSync2, realpathSync } from "fs";
704
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
685
705
  import { dirname as dirname3, join as join5 } from "path";
686
- import process12 from "process";
706
+ import process13 from "process";
687
707
 
688
708
  // ../kit/src/usage.ts
689
709
  import { appendFileSync, mkdirSync } from "fs";
690
710
  import { homedir as homedir3 } from "os";
691
711
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
692
- import process11 from "process";
712
+ import process12 from "process";
693
713
 
694
714
  // ../kit/src/logs.ts
695
715
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -703,14 +723,14 @@ var usageError;
703
723
  function noteUsageError(message) {
704
724
  usageError = message;
705
725
  }
706
- function stateHome(env = process11.env) {
726
+ function stateHome(env = process12.env) {
707
727
  const dir = env.XDG_STATE_HOME;
708
728
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
709
729
  }
710
- function usagePath(env = process11.env) {
730
+ function usagePath(env = process12.env) {
711
731
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
712
732
  }
713
- function usageRecorded(env = process11.env) {
733
+ function usageRecorded(env = process12.env) {
714
734
  const off = env.KAYNOOO_CLI_NO_USAGE;
715
735
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
716
736
  }
@@ -724,7 +744,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
724
744
  usageError = undefined;
725
745
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
726
746
  }
727
- function recordUsage(entry, env = process11.env) {
747
+ function recordUsage(entry, env = process12.env) {
728
748
  if (!usageRecorded(env))
729
749
  return;
730
750
  try {
@@ -742,8 +762,8 @@ var LEVEL_OPTIONS = {
742
762
  };
743
763
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
744
764
  function printError(prefix, message, hint, cause) {
745
- const colors = paint(process12.stderr);
746
- const styled = takesControlCodes(process12.stderr);
765
+ const colors = paint(process13.stderr);
766
+ const styled = takesControlCodes(process13.stderr);
747
767
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
748
768
  const under = (label, text, tint) => text === undefined ? "" : `
749
769
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -787,24 +807,24 @@ function candidateLine(candidate) {
787
807
  }
788
808
  function positionalBeingTyped(before, { options, positionals }) {
789
809
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
790
- let index = 0;
810
+ const typed = [];
791
811
  let at = 0;
792
812
  while (at < before.length) {
793
813
  const word = before[at];
794
814
  if (word === "--") {
795
- index += before.length - at - 1;
815
+ typed.push(...before.slice(at + 1));
796
816
  break;
797
817
  }
798
818
  if (!word.startsWith("-"))
799
- index++;
819
+ typed.push(word);
800
820
  else if (takesValue(word))
801
821
  at++;
802
822
  at++;
803
823
  }
804
824
  const last = positionals.at(-1);
805
- if (index < positionals.length)
806
- return positionals[index];
807
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
825
+ if (typed.length < positionals.length)
826
+ return { name: positionals[typed.length], typed };
827
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
808
828
  }
809
829
  async function leafCandidates(run, words) {
810
830
  const completing = await completingOf(run);
@@ -812,12 +832,12 @@ async function leafCandidates(run, words) {
812
832
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
813
833
  const flag = words.at(-2);
814
834
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
835
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
815
836
  if (option?.type === "string") {
816
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
837
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
817
838
  return values === undefined ? [FILES] : values.map(candidateLine);
818
839
  }
819
- const name = positionalBeingTyped(words.slice(0, -1), completing);
820
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
840
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
821
841
  return values === undefined ? [FILES] : values.map(candidateLine);
822
842
  }
823
843
  async function printCandidates(found) {
@@ -826,9 +846,13 @@ async function printCandidates(found) {
826
846
  return 0;
827
847
  }
828
848
  function packageVersion(entry = Bun.main) {
829
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
849
+ let resolved = entry;
850
+ try {
851
+ resolved = realpathSync2(entry);
852
+ } catch {}
853
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
830
854
  try {
831
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
855
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
832
856
  if (typeof version === "string")
833
857
  return version;
834
858
  } catch {}
@@ -836,7 +860,7 @@ function packageVersion(entry = Bun.main) {
836
860
  return "0.0.0";
837
861
  }
838
862
  }
839
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
863
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
840
864
  if (argv[0] === COMPLETE)
841
865
  return printCandidates(leafCandidates(run, argv.slice(1)));
842
866
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1038,9 +1062,8 @@ new lines
1038
1062
  >>>>>>> REPLACE
1039
1063
  EOF
1040
1064
 
1041
- A line naming a file before a block makes it apply to that file alone, so one call edits several files (no file argument needed when every block names one). An empty REPLACE deletes the SEARCH text; to drop whole lines, put the neighbouring line in both. When the text holds a marker line itself (a Markdown '=======' underline), open with more characters, '<<<<<<<<<< SEARCH', and divide and close with as many '=' and '>' too.
1042
-
1043
- Exits 0 when it wrote every replacement, 1 when one did not match or a file cannot be written (nothing is written), 2 on a usage error.`;
1065
+ A line naming a file before a block makes it apply to that file alone, so one call edits several files (no file argument needed when every block names one). An empty REPLACE deletes the SEARCH text; to drop whole lines, put the neighbouring line in both. When the text holds a marker line itself (a Markdown '=======' underline), open with more characters, '<<<<<<<<<< SEARCH', and divide and close with as many '=' and '>' too.`;
1066
+ var EXITS = [[0, "it wrote every replacement"], [1, "one did not match or a file cannot be written (nothing is written)"], [2, "a usage error"]];
1044
1067
  var OPTIONS = {
1045
1068
  from: { type: "string", short: "f", description: "text to find, taken literally" },
1046
1069
  to: { type: "string", short: "t", description: "text to put in its place, empty to delete it" },
@@ -1107,16 +1130,16 @@ function writable(path) {
1107
1130
  var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
1108
1131
  function readUtf8(path) {
1109
1132
  try {
1110
- return UTF8.decode(readFileSync3(path));
1133
+ return UTF8.decode(readFileSync4(path));
1111
1134
  } catch {
1112
1135
  return;
1113
1136
  }
1114
1137
  }
1115
1138
  function canonical(path) {
1116
1139
  try {
1117
- return realpathSync2(path);
1140
+ return realpathSync3(path);
1118
1141
  } catch {
1119
- return resolve3(path);
1142
+ return resolve4(path);
1120
1143
  }
1121
1144
  }
1122
1145
  function dedupe(paths) {
@@ -1129,8 +1152,8 @@ function dedupe(paths) {
1129
1152
  return [...byFile.values()];
1130
1153
  }
1131
1154
  function writeAtomic(path, text) {
1132
- const target = realpathSync2(path);
1133
- const temp = `${target}.sub-${process14.pid}`;
1155
+ const target = realpathSync3(path);
1156
+ const temp = `${target}.sub-${process15.pid}`;
1134
1157
  try {
1135
1158
  writeFileSync2(temp, text);
1136
1159
  chmodSync(temp, (statSync2(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
@@ -1149,23 +1172,23 @@ async function blocksOnStdin(files) {
1149
1172
  const hint = `${strings}give --from and --to, or pipe SEARCH/REPLACE blocks on stdin from a heredoc
1150
1173
 
1151
1174
  ${USAGE}`;
1152
- if (process14.stdin.isTTY)
1175
+ if (process15.stdin.isTTY)
1153
1176
  fail(hint);
1154
1177
  return new Promise((resolve) => {
1155
1178
  const chunks = [];
1156
1179
  const timer = setTimeout(() => {
1157
1180
  console.error(`error: sub: ${hint}`);
1158
- process14.exit(2);
1181
+ process15.exit(2);
1159
1182
  }, STDIN_SILENCE_MS);
1160
- process14.stdin.on("data", (chunk) => {
1183
+ process15.stdin.on("data", (chunk) => {
1161
1184
  clearTimeout(timer);
1162
1185
  chunks.push(chunk);
1163
1186
  });
1164
- process14.stdin.on("end", () => {
1187
+ process15.stdin.on("end", () => {
1165
1188
  clearTimeout(timer);
1166
1189
  if (chunks.length === 0 && extra.length > 0) {
1167
1190
  console.error(`error: sub: ${hint}`);
1168
- process14.exit(2);
1191
+ process15.exit(2);
1169
1192
  }
1170
1193
  resolve(Buffer.concat(chunks).toString("utf8"));
1171
1194
  });
@@ -1218,7 +1241,7 @@ ${USAGE}`);
1218
1241
  return edits;
1219
1242
  }
1220
1243
  async function main(argv) {
1221
- const parsed = parse(argv, USAGE, OPTIONS, { 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"]] });
1244
+ 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"]] });
1222
1245
  const { values, positionals } = parsed;
1223
1246
  const files = dedupe(positionals.map((path) => normalize(path)));
1224
1247
  if (values.count !== undefined && values.all === true)
@@ -1248,7 +1271,7 @@ async function main(argv) {
1248
1271
  if (json)
1249
1272
  console.error(JSON.stringify({ error: "nothing written", failures: problems }));
1250
1273
  else
1251
- console.error(`sub: nothing written
1274
+ console.error(`${role("problem", process15.stderr)("sub: nothing written")}
1252
1275
  ${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
1253
1276
  `)}`);
1254
1277
  return 1;
@@ -1257,7 +1280,7 @@ ${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
1257
1280
  for (const change of changes)
1258
1281
  change.diff = await diffTexts(change.path, change.before, change.after);
1259
1282
  } catch (error) {
1260
- console.error(`sub: nothing written
1283
+ console.error(`${role("problem", process15.stderr)("sub: nothing written")}
1261
1284
  ${error instanceof Error ? error.message : String(error)}`);
1262
1285
  return 1;
1263
1286
  }
@@ -1272,9 +1295,9 @@ ${error instanceof Error ? error.message : String(error)}`);
1272
1295
  continue;
1273
1296
  }
1274
1297
  if (values.quiet !== true)
1275
- console.log(`${role("path", process14.stdout)(path)}: ${go(lines.length, "replacement")} on ${K("line", lines.length, { zero: "plural" })} ${listLines(lines)}, ${role(diff.added === 0 ? "label" : "ok", process14.stdout)(`+${diff.added}`)} ${role(diff.removed === 0 ? "label" : "problem", process14.stdout)(`-${diff.removed}`)}`);
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}`)}`);
1276
1299
  if (values.diff === true && diff.unified !== "")
1277
- process14.stdout.write(diff.unified);
1300
+ process15.stdout.write(diff.unified);
1278
1301
  }
1279
1302
  if (json)
1280
1303
  printJson({ dryRun: values["dry-run"] === true, files: done });
@@ -1282,4 +1305,4 @@ ${error instanceof Error ? error.message : String(error)}`);
1282
1305
  console.log("dry run: nothing written");
1283
1306
  return 0;
1284
1307
  }
1285
- process14.exitCode = await runMain({ name: "sub", run: main });
1308
+ process15.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.9.1",
4
+ "version": "0.10.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.36.0"
42
+ "@kaynooo/cli-kit": "0.38.2"
43
43
  }
44
44
  }