@kaynooo/cli-edit 0.4.0 → 0.5.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.
- package/README.md +1 -0
- package/dist/cli.js +342 -120
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -25,6 +25,7 @@ EOF
|
|
|
25
25
|
- `--to ''` deletes the match. A value starting with a dash goes as `--from=-x`.
|
|
26
26
|
- Several files at once (the shell's globs, or `rg -l X | xargs sub ...`): each is checked on its own, and one failing file leaves every file untouched.
|
|
27
27
|
- On a failure nothing is written, stderr lists each file and pair that failed, with the lines matched or, for a multiline `--from` found nowhere, the lines its first line is on (usually an indentation mismatch), and the exit code is 1.
|
|
28
|
+
- `--json` prints `{dryRun, files: [{path, replacements, lines, added, removed, diff?}]}` (`diff` under `--diff`), and on a failure `{error, failures: [{path, problem}]}` on stderr.
|
|
28
29
|
- `--regex` makes `--from` a regular expression (`^` and `$` match each line), `--to` taking `$1` and `$<name>`, or `${1}` and `${name}` when digits or letters follow the reference.
|
|
29
30
|
- Without `--from`, `--to` or `--pairs`, `sub` reads SEARCH/REPLACE blocks on stdin and applies them in order, each on the previous one's result, all or nothing, each checked like a `--from` (once, or as `--count`/`--all` say; `--regex` makes every SEARCH a regular expression). The text between the markers is taken as is, joined by newlines with none after the last line, so a SEARCH ending in a line break takes an empty line before `=======`. An empty REPLACE deletes the SEARCH text; to drop whole lines, put the neighbouring line in both.
|
|
30
31
|
- A line naming a file before a block makes it apply to that file alone, so one call edits several files and needs no file argument; a block without one applies to the file arguments. A file listed but named by no block and given no file-less block is refused.
|
package/dist/cli.js
CHANGED
|
@@ -2,18 +2,17 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/cli.ts
|
|
5
|
-
import { accessSync, chmodSync, constants, existsSync, readFileSync, realpathSync, renameSync, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
|
|
5
|
+
import { accessSync, chmodSync, constants, existsSync, readFileSync as readFileSync2, realpathSync as realpathSync2, renameSync, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
|
|
6
6
|
import { normalize, resolve } from "path";
|
|
7
|
-
import
|
|
8
|
-
|
|
7
|
+
import process9 from "process";
|
|
9
8
|
// ../kit/src/args.ts
|
|
10
|
-
import
|
|
9
|
+
import process5 from "process";
|
|
11
10
|
import { parseArgs } from "util";
|
|
12
11
|
|
|
13
12
|
// ../kit/src/style.ts
|
|
14
|
-
import
|
|
13
|
+
import process2 from "process";
|
|
15
14
|
|
|
16
|
-
// ../../node_modules/.bun/@kaynooo+utils@2.31.
|
|
15
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
17
16
|
function x(s) {
|
|
18
17
|
let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
|
|
19
18
|
if (!/^[a-f0-9]+$/.test(r))
|
|
@@ -233,7 +232,7 @@ class e {
|
|
|
233
232
|
}
|
|
234
233
|
}
|
|
235
234
|
|
|
236
|
-
// ../../node_modules/.bun/@kaynooo+utils@2.31.
|
|
235
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
|
|
237
236
|
var r = 39;
|
|
238
237
|
var o = 49;
|
|
239
238
|
var f2 = "\x1B[";
|
|
@@ -275,10 +274,10 @@ function le(i = {}) {
|
|
|
275
274
|
var t = le();
|
|
276
275
|
|
|
277
276
|
// ../kit/src/style.ts
|
|
278
|
-
function takesControlCodes(stream, env =
|
|
277
|
+
function takesControlCodes(stream, env = process2.env) {
|
|
279
278
|
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
280
279
|
}
|
|
281
|
-
function paint(stream, env =
|
|
280
|
+
function paint(stream, env = process2.env) {
|
|
282
281
|
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
283
282
|
}
|
|
284
283
|
var STATUSES = {
|
|
@@ -296,6 +295,66 @@ function upTo(text, separator) {
|
|
|
296
295
|
return end === -1 ? text : text.slice(0, end);
|
|
297
296
|
}
|
|
298
297
|
var ESCAPE = String.fromCharCode(27);
|
|
298
|
+
function printJson(value) {
|
|
299
|
+
console.log(JSON.stringify(value, undefined, 2));
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// ../kit/src/help.ts
|
|
303
|
+
import process3 from "process";
|
|
304
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
305
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
306
|
+
var FULL_STOP = /\.$/;
|
|
307
|
+
function usageLine(usage, colors = paint(process3.stdout)) {
|
|
308
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
309
|
+
}
|
|
310
|
+
function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
311
|
+
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
312
|
+
`);
|
|
313
|
+
}
|
|
314
|
+
function exitRows(exits, colors = paint(process3.stdout)) {
|
|
315
|
+
if (exits.length === 0)
|
|
316
|
+
return [];
|
|
317
|
+
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
318
|
+
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
319
|
+
}
|
|
320
|
+
function replacesRows(replaces, colors = paint(process3.stdout)) {
|
|
321
|
+
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
322
|
+
}
|
|
323
|
+
function wantsHelpJson(env = process3.env) {
|
|
324
|
+
return env.KIT_HELP === "json";
|
|
325
|
+
}
|
|
326
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
327
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
328
|
+
`);
|
|
329
|
+
const first = lines[0];
|
|
330
|
+
const colon = first.indexOf(": ");
|
|
331
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
332
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
333
|
+
return {
|
|
334
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
335
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
336
|
+
...replaces === undefined ? {} : { replaces },
|
|
337
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
|
|
338
|
+
...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
|
|
339
|
+
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
340
|
+
};
|
|
341
|
+
}
|
|
342
|
+
function exampleRows(examples, colors = paint(process3.stdout)) {
|
|
343
|
+
if (examples.length === 0)
|
|
344
|
+
return [];
|
|
345
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
346
|
+
}
|
|
347
|
+
function optionRows(options, colors = paint(process3.stdout)) {
|
|
348
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
349
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
350
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
351
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
352
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
353
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
354
|
+
});
|
|
355
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
356
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
357
|
+
}
|
|
299
358
|
|
|
300
359
|
// ../kit/src/text.ts
|
|
301
360
|
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
@@ -316,8 +375,35 @@ function closest(name, names) {
|
|
|
316
375
|
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
317
376
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
318
377
|
}
|
|
378
|
+
// ../kit/src/input.ts
|
|
379
|
+
import process4 from "process";
|
|
380
|
+
var WHOLE = /^\d+$/;
|
|
381
|
+
function wholeNumber(value, name, fallback, min = 1) {
|
|
382
|
+
if (value === undefined)
|
|
383
|
+
return fallback;
|
|
384
|
+
const number = Number(value);
|
|
385
|
+
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
386
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
387
|
+
return number;
|
|
388
|
+
}
|
|
389
|
+
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
390
|
+
if (path === "-") {
|
|
391
|
+
if (process4.stdin.isTTY)
|
|
392
|
+
fail(noStdin);
|
|
393
|
+
return Bun.stdin.text();
|
|
394
|
+
}
|
|
395
|
+
const file = Bun.file(path);
|
|
396
|
+
if (!await file.exists())
|
|
397
|
+
fail(`no file ${path}`);
|
|
398
|
+
return file.text();
|
|
399
|
+
}
|
|
319
400
|
|
|
320
401
|
// ../kit/src/args.ts
|
|
402
|
+
var DASHES = /^-+/;
|
|
403
|
+
function jsonOption(holds) {
|
|
404
|
+
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
405
|
+
}
|
|
406
|
+
|
|
321
407
|
class Exit extends Error {
|
|
322
408
|
code;
|
|
323
409
|
hint;
|
|
@@ -348,61 +434,20 @@ class HelpShown extends Exit {
|
|
|
348
434
|
|
|
349
435
|
class Completing {
|
|
350
436
|
options;
|
|
351
|
-
|
|
437
|
+
positionals;
|
|
438
|
+
candidates;
|
|
439
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
352
440
|
this.options = options;
|
|
441
|
+
this.positionals = positionals;
|
|
442
|
+
this.candidates = candidates;
|
|
353
443
|
}
|
|
354
444
|
}
|
|
355
445
|
var completion = { active: false };
|
|
356
|
-
var OPTIONAL = /\[[^\]]+\]/g;
|
|
357
|
-
var USAGE_PREFIX = /^usage:\s*/i;
|
|
358
|
-
var FULL_STOP = /\.$/;
|
|
359
|
-
var DASHES = /^-+/;
|
|
360
|
-
function usageLine(usage, colors = paint(process2.stdout)) {
|
|
361
|
-
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
362
|
-
}
|
|
363
|
-
function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
|
|
364
|
-
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
365
|
-
`);
|
|
366
|
-
}
|
|
367
|
-
function replacesRows(replaces, colors = paint(process2.stdout)) {
|
|
368
|
-
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
369
|
-
}
|
|
370
|
-
function wantsHelpJson(env = process2.env) {
|
|
371
|
-
return env.KIT_HELP === "json";
|
|
372
|
-
}
|
|
373
|
-
function description(usage, { examples = [], replaces } = {}) {
|
|
374
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
375
|
-
`);
|
|
376
|
-
const first = lines[0];
|
|
377
|
-
const colon = first.indexOf(": ");
|
|
378
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
379
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
380
|
-
return {
|
|
381
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
382
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
383
|
-
...replaces === undefined ? {} : { replaces },
|
|
384
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
385
|
-
};
|
|
386
|
-
}
|
|
387
|
-
function exampleRows(examples, colors = paint(process2.stdout)) {
|
|
388
|
-
if (examples.length === 0)
|
|
389
|
-
return [];
|
|
390
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
391
|
-
}
|
|
392
|
-
function optionRows(options, colors = paint(process2.stdout)) {
|
|
393
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
394
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
395
|
-
const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
|
|
396
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
|
|
397
|
-
});
|
|
398
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
399
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
400
|
-
}
|
|
401
446
|
var OUTPUT_OPTIONS = {
|
|
402
447
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
403
448
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
404
449
|
};
|
|
405
|
-
function applyOutput(color, plain, env =
|
|
450
|
+
function applyOutput(color, plain, env = process5.env) {
|
|
406
451
|
const when = plain === true ? "never" : color ?? "auto";
|
|
407
452
|
if (when === "auto")
|
|
408
453
|
return;
|
|
@@ -419,14 +464,13 @@ function applyOutput(color, plain, env = process2.env) {
|
|
|
419
464
|
function parse(args, usage, options, settings = {}) {
|
|
420
465
|
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
421
466
|
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
467
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
422
468
|
if (completion.active)
|
|
423
|
-
throw new Completing(
|
|
424
|
-
const
|
|
425
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
426
|
-
const rest = separator === -1 ? undefined : args.slice(separator + 1);
|
|
469
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
470
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
427
471
|
let parsed;
|
|
428
472
|
try {
|
|
429
|
-
parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
473
|
+
parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
430
474
|
} catch (error) {
|
|
431
475
|
const message = parseError(error);
|
|
432
476
|
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
@@ -434,12 +478,96 @@ function parse(args, usage, options, settings = {}) {
|
|
|
434
478
|
const values = parsed.values;
|
|
435
479
|
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
436
480
|
if (values.help === true) {
|
|
437
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage,
|
|
481
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
438
482
|
throw new HelpShown;
|
|
439
483
|
}
|
|
484
|
+
checkChoices(parsed.values, all);
|
|
485
|
+
checkConflicts(parsed.values, all);
|
|
440
486
|
if (settings.positionals !== undefined)
|
|
441
487
|
checkPositionals(parsed.positionals, settings.positionals);
|
|
442
|
-
return { ...parsed, positionals: parsed.positionals, rest };
|
|
488
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
489
|
+
}
|
|
490
|
+
function splitRest(args, passes) {
|
|
491
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
492
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
493
|
+
}
|
|
494
|
+
function splitTrailing(args, options, count) {
|
|
495
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
496
|
+
let seen = 0;
|
|
497
|
+
if (count === 0)
|
|
498
|
+
return { own: args, rest: undefined };
|
|
499
|
+
for (let at = 0;at < args.length; at++) {
|
|
500
|
+
const word = args[at];
|
|
501
|
+
if (word === "--")
|
|
502
|
+
break;
|
|
503
|
+
if (word.startsWith("-")) {
|
|
504
|
+
if (takesValue(word))
|
|
505
|
+
at++;
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
seen++;
|
|
509
|
+
if (seen === count)
|
|
510
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
511
|
+
}
|
|
512
|
+
return { own: args, rest: undefined };
|
|
513
|
+
}
|
|
514
|
+
function listed(options, allowNegative) {
|
|
515
|
+
if (!allowNegative)
|
|
516
|
+
return options;
|
|
517
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
518
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
519
|
+
return [[name, option]];
|
|
520
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
521
|
+
}));
|
|
522
|
+
}
|
|
523
|
+
function withAliases(args, options) {
|
|
524
|
+
const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
|
|
525
|
+
if (named.size === 0)
|
|
526
|
+
return args;
|
|
527
|
+
const separator = args.indexOf("--");
|
|
528
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
529
|
+
return [...own.map((arg) => {
|
|
530
|
+
const at = arg.indexOf("=");
|
|
531
|
+
const current = named.get(at === -1 ? arg : arg.slice(0, at));
|
|
532
|
+
return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
|
|
533
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
534
|
+
}
|
|
535
|
+
function withBare(args, options) {
|
|
536
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
537
|
+
if (bare.size === 0)
|
|
538
|
+
return args;
|
|
539
|
+
const separator = args.indexOf("--");
|
|
540
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
541
|
+
return [...own.flatMap((arg, index) => {
|
|
542
|
+
const optional = bare.get(arg);
|
|
543
|
+
const next = own[index + 1];
|
|
544
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
545
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
546
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
547
|
+
}
|
|
548
|
+
function checkConflicts(values, options) {
|
|
549
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
550
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
551
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
552
|
+
if (other !== undefined)
|
|
553
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
function checkChoices(values, options) {
|
|
557
|
+
for (const [name, option] of Object.entries(options)) {
|
|
558
|
+
if (option.choices === undefined)
|
|
559
|
+
continue;
|
|
560
|
+
const given = values[name];
|
|
561
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
562
|
+
if (typeof value === "string")
|
|
563
|
+
oneOf(value, name, option.choices);
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
function oneOf(value, name, choices) {
|
|
568
|
+
if (!choices.includes(value))
|
|
569
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
570
|
+
return value;
|
|
443
571
|
}
|
|
444
572
|
function checkPositionals(given, names) {
|
|
445
573
|
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
@@ -488,41 +616,75 @@ function nearestOption(message, options, allowNegative) {
|
|
|
488
616
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
489
617
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
490
618
|
}
|
|
491
|
-
var WHOLE = /^\d+$/;
|
|
492
|
-
function wholeNumber(value, name, fallback, min = 1) {
|
|
493
|
-
if (value === undefined)
|
|
494
|
-
return fallback;
|
|
495
|
-
const number = Number(value);
|
|
496
|
-
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
497
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
498
|
-
return number;
|
|
499
|
-
}
|
|
500
|
-
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
501
|
-
if (path === "-") {
|
|
502
|
-
if (process2.stdin.isTTY)
|
|
503
|
-
fail(noStdin);
|
|
504
|
-
return Bun.stdin.text();
|
|
505
|
-
}
|
|
506
|
-
const file = Bun.file(path);
|
|
507
|
-
if (!await file.exists())
|
|
508
|
-
fail(`no file ${path}`);
|
|
509
|
-
return file.text();
|
|
510
|
-
}
|
|
511
619
|
// ../kit/src/progress.ts
|
|
512
620
|
var ESC = String.fromCharCode(27);
|
|
513
621
|
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
514
622
|
var RESET_STYLE = `${ESC}[0m`;
|
|
515
623
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
516
624
|
// ../kit/src/cli.ts
|
|
517
|
-
import
|
|
625
|
+
import { readFileSync, realpathSync } from "fs";
|
|
626
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
627
|
+
import process7 from "process";
|
|
628
|
+
|
|
629
|
+
// ../kit/src/usage.ts
|
|
630
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
631
|
+
import { homedir } from "os";
|
|
632
|
+
import { dirname, isAbsolute, join } from "path";
|
|
633
|
+
import process6 from "process";
|
|
634
|
+
|
|
635
|
+
// ../kit/src/logs.ts
|
|
636
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
637
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
638
|
+
|
|
639
|
+
// ../kit/src/usage.ts
|
|
640
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
641
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
642
|
+
var LONGEST_NAME = 40;
|
|
643
|
+
var usageError;
|
|
644
|
+
function noteUsageError(message) {
|
|
645
|
+
usageError = message;
|
|
646
|
+
}
|
|
647
|
+
function stateHome(env = process6.env) {
|
|
648
|
+
const dir = env.XDG_STATE_HOME;
|
|
649
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
650
|
+
}
|
|
651
|
+
function usagePath(env = process6.env) {
|
|
652
|
+
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
653
|
+
}
|
|
654
|
+
function usageRecorded(env = process6.env) {
|
|
655
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
656
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
657
|
+
}
|
|
658
|
+
function flagNames(argv) {
|
|
659
|
+
const end = argv.indexOf("--");
|
|
660
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
661
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
662
|
+
}
|
|
663
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
664
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
665
|
+
usageError = undefined;
|
|
666
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
667
|
+
}
|
|
668
|
+
function recordUsage(entry, env = process6.env) {
|
|
669
|
+
if (!usageRecorded(env))
|
|
670
|
+
return;
|
|
671
|
+
try {
|
|
672
|
+
const path = usagePath(env);
|
|
673
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
674
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
675
|
+
`, { mode: 384 });
|
|
676
|
+
} catch {}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// ../kit/src/cli.ts
|
|
518
680
|
var LEVEL_OPTIONS = {
|
|
519
681
|
...OUTPUT_OPTIONS,
|
|
520
682
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
521
683
|
};
|
|
522
684
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
523
685
|
function printError(prefix, message, hint, cause) {
|
|
524
|
-
const colors = paint(
|
|
525
|
-
const styled = takesControlCodes(
|
|
686
|
+
const colors = paint(process7.stderr);
|
|
687
|
+
const styled = takesControlCodes(process7.stderr);
|
|
526
688
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
527
689
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
528
690
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -541,58 +703,106 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
541
703
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
542
704
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
543
705
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
706
|
+
if (error instanceof UsageError)
|
|
707
|
+
noteUsageError(error.message);
|
|
544
708
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
545
709
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
546
710
|
return error instanceof Exit ? error.code : 1;
|
|
547
711
|
}
|
|
548
712
|
var COMPLETE = "__complete";
|
|
549
713
|
var FILES = "__files__";
|
|
550
|
-
async function
|
|
714
|
+
async function completingOf(run) {
|
|
551
715
|
completion.active = true;
|
|
552
716
|
try {
|
|
553
717
|
await run([]);
|
|
554
718
|
} catch (error) {
|
|
555
719
|
if (error instanceof Completing)
|
|
556
|
-
return error
|
|
720
|
+
return error;
|
|
557
721
|
} finally {
|
|
558
722
|
completion.active = false;
|
|
559
723
|
}
|
|
560
|
-
return {};
|
|
724
|
+
return new Completing({});
|
|
725
|
+
}
|
|
726
|
+
function candidateLine(candidate) {
|
|
727
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
728
|
+
}
|
|
729
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
730
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
731
|
+
let index = 0;
|
|
732
|
+
let at = 0;
|
|
733
|
+
while (at < before.length) {
|
|
734
|
+
const word = before[at];
|
|
735
|
+
if (word === "--") {
|
|
736
|
+
index += before.length - at - 1;
|
|
737
|
+
break;
|
|
738
|
+
}
|
|
739
|
+
if (!word.startsWith("-"))
|
|
740
|
+
index++;
|
|
741
|
+
else if (takesValue(word))
|
|
742
|
+
at++;
|
|
743
|
+
at++;
|
|
744
|
+
}
|
|
745
|
+
const last = positionals.at(-1);
|
|
746
|
+
if (index < positionals.length)
|
|
747
|
+
return positionals[index];
|
|
748
|
+
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
561
749
|
}
|
|
562
750
|
async function leafCandidates(run, words) {
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
751
|
+
const completing = await completingOf(run);
|
|
752
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
753
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
754
|
+
const flag = words.at(-2);
|
|
755
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
756
|
+
if (option?.type === "string") {
|
|
757
|
+
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
758
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
759
|
+
}
|
|
760
|
+
const name = positionalBeingTyped(words.slice(0, -1), completing);
|
|
761
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
762
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
566
763
|
}
|
|
567
764
|
async function printCandidates(found) {
|
|
568
765
|
for (const line of await found)
|
|
569
766
|
console.log(line);
|
|
570
767
|
return 0;
|
|
571
768
|
}
|
|
572
|
-
|
|
769
|
+
function packageVersion(entry = Bun.main) {
|
|
770
|
+
for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
|
|
771
|
+
try {
|
|
772
|
+
const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
|
|
773
|
+
if (typeof version === "string")
|
|
774
|
+
return version;
|
|
775
|
+
} catch {}
|
|
776
|
+
if (dirname2(dir) === dir)
|
|
777
|
+
return "0.0.0";
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
|
|
573
781
|
if (argv[0] === COMPLETE)
|
|
574
782
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
575
783
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
576
|
-
console.log(version);
|
|
784
|
+
console.log(version ?? packageVersion());
|
|
577
785
|
return 0;
|
|
578
786
|
}
|
|
787
|
+
let code;
|
|
579
788
|
try {
|
|
580
|
-
|
|
789
|
+
code = await run(argv);
|
|
581
790
|
} catch (error) {
|
|
582
|
-
|
|
791
|
+
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
792
|
+
}
|
|
793
|
+
if (usage !== false) {
|
|
794
|
+
try {
|
|
795
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
796
|
+
} catch {}
|
|
583
797
|
}
|
|
798
|
+
return code;
|
|
584
799
|
}
|
|
585
|
-
// ../kit/src/logs.ts
|
|
586
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
587
800
|
// ../kit/src/secrets.ts
|
|
588
801
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
589
802
|
// ../kit/src/sessions.ts
|
|
590
803
|
var {Glob } = globalThis.Bun;
|
|
591
804
|
var SESSION_FILES = new Glob("*.json");
|
|
592
805
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
593
|
-
// package.json
|
|
594
|
-
var version = "0.4.0";
|
|
595
|
-
|
|
596
806
|
// src/blocks.ts
|
|
597
807
|
var LINE_BREAK = /\r?\n/;
|
|
598
808
|
var OPENER = /^(<{7,}) SEARCH$/;
|
|
@@ -648,15 +858,15 @@ function parseBlocks(text) {
|
|
|
648
858
|
// src/diff.ts
|
|
649
859
|
import { mkdtempSync, rmSync, writeFileSync } from "fs";
|
|
650
860
|
import { tmpdir } from "os";
|
|
651
|
-
import { join } from "path";
|
|
861
|
+
import { join as join3 } from "path";
|
|
652
862
|
async function diffTexts(path, before, after) {
|
|
653
|
-
const dir = mkdtempSync(
|
|
863
|
+
const dir = mkdtempSync(join3(tmpdir(), "sub-"));
|
|
654
864
|
try {
|
|
655
|
-
writeFileSync(
|
|
656
|
-
writeFileSync(
|
|
865
|
+
writeFileSync(join3(dir, "before"), before);
|
|
866
|
+
writeFileSync(join3(dir, "after"), after);
|
|
657
867
|
let child;
|
|
658
868
|
try {
|
|
659
|
-
child = Bun.spawn(["diff", "-u", "--label", `a/${path}`, "--label", `b/${path}`,
|
|
869
|
+
child = Bun.spawn(["diff", "-u", "--label", `a/${path}`, "--label", `b/${path}`, join3(dir, "before"), join3(dir, "after")], { stdout: "pipe", stderr: "pipe" });
|
|
660
870
|
} catch {
|
|
661
871
|
throw new Error("diff is not installed, which sub needs to show its changes");
|
|
662
872
|
}
|
|
@@ -778,7 +988,8 @@ var OPTIONS = {
|
|
|
778
988
|
regex: { type: "boolean", short: "r", description: "--from is a regular expression (^ and $ match each line), --to may use $1, ${1}, $<name> and ${name}" },
|
|
779
989
|
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" },
|
|
780
990
|
diff: { type: "boolean", short: "d", description: "print each file's unified diff" },
|
|
781
|
-
"dry-run": { type: "boolean", description: "show what would change without writing" }
|
|
991
|
+
"dry-run": { type: "boolean", description: "show what would change without writing" },
|
|
992
|
+
json: jsonOption("{dryRun, files: [{path, replacements, lines, added, removed, diff?}]}, or {error, failures: [{path, problem}]} on stderr when nothing is written")
|
|
782
993
|
};
|
|
783
994
|
var PAIR_KEYS = ["from", "to", "count", "all", "regex"];
|
|
784
995
|
function checkPattern(pair, label) {
|
|
@@ -837,14 +1048,14 @@ function writable(path) {
|
|
|
837
1048
|
var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
838
1049
|
function readUtf8(path) {
|
|
839
1050
|
try {
|
|
840
|
-
return UTF8.decode(
|
|
1051
|
+
return UTF8.decode(readFileSync2(path));
|
|
841
1052
|
} catch {
|
|
842
1053
|
return;
|
|
843
1054
|
}
|
|
844
1055
|
}
|
|
845
1056
|
function canonical(path) {
|
|
846
1057
|
try {
|
|
847
|
-
return
|
|
1058
|
+
return realpathSync2(path);
|
|
848
1059
|
} catch {
|
|
849
1060
|
return resolve(path);
|
|
850
1061
|
}
|
|
@@ -859,8 +1070,8 @@ function dedupe(paths) {
|
|
|
859
1070
|
return [...byFile.values()];
|
|
860
1071
|
}
|
|
861
1072
|
function writeAtomic(path, text) {
|
|
862
|
-
const target =
|
|
863
|
-
const temp = `${target}.sub-${
|
|
1073
|
+
const target = realpathSync2(path);
|
|
1074
|
+
const temp = `${target}.sub-${process9.pid}`;
|
|
864
1075
|
try {
|
|
865
1076
|
writeFileSync2(temp, text);
|
|
866
1077
|
chmodSync(temp, (statSync(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
|
|
@@ -930,23 +1141,27 @@ async function main(argv) {
|
|
|
930
1141
|
const problems = [];
|
|
931
1142
|
for (const [path, pairs] of edits) {
|
|
932
1143
|
if (!existsSync(path)) {
|
|
933
|
-
problems.push(
|
|
1144
|
+
problems.push({ path, problem: "no such file" });
|
|
934
1145
|
continue;
|
|
935
1146
|
}
|
|
936
1147
|
const before = readUtf8(path);
|
|
937
1148
|
if (before === undefined) {
|
|
938
|
-
problems.push(
|
|
1149
|
+
problems.push({ path, problem: "not valid UTF-8, left alone" });
|
|
939
1150
|
continue;
|
|
940
1151
|
}
|
|
941
1152
|
const applied = applyPairs(before, pairs);
|
|
942
|
-
problems.push(...applied.problems.map((problem) =>
|
|
1153
|
+
problems.push(...applied.problems.map((problem) => ({ path, problem })));
|
|
943
1154
|
if (applied.problems.length === 0 && values["dry-run"] !== true && !writable(path))
|
|
944
|
-
problems.push(
|
|
1155
|
+
problems.push({ path, problem: "not writable" });
|
|
945
1156
|
changes.push({ path, before, after: applied.text, lines: applied.lines });
|
|
946
1157
|
}
|
|
1158
|
+
const json = values.json === true;
|
|
947
1159
|
if (problems.length > 0) {
|
|
948
|
-
|
|
949
|
-
|
|
1160
|
+
if (json)
|
|
1161
|
+
console.error(JSON.stringify({ error: "nothing written", failures: problems }));
|
|
1162
|
+
else
|
|
1163
|
+
console.error(`sub: nothing written
|
|
1164
|
+
${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
|
|
950
1165
|
`)}`);
|
|
951
1166
|
return 1;
|
|
952
1167
|
}
|
|
@@ -958,17 +1173,24 @@ ${problems.join(`
|
|
|
958
1173
|
${error instanceof Error ? error.message : String(error)}`);
|
|
959
1174
|
return 1;
|
|
960
1175
|
}
|
|
1176
|
+
const done = [];
|
|
961
1177
|
for (const { path, before, after, lines, diff } of changes) {
|
|
962
1178
|
if (diff === undefined)
|
|
963
1179
|
continue;
|
|
964
1180
|
if (values["dry-run"] !== true && after !== before)
|
|
965
1181
|
writeAtomic(path, after);
|
|
1182
|
+
if (json) {
|
|
1183
|
+
done.push({ path, replacements: lines.length, lines, added: diff.added, removed: diff.removed, ...values.diff === true ? { diff: diff.unified } : {} });
|
|
1184
|
+
continue;
|
|
1185
|
+
}
|
|
966
1186
|
console.log(`${path}: ${plural(lines.length, "replacement")} on line${lines.length === 1 ? "" : "s"} ${listLines(lines)}, +${diff.added} -${diff.removed}`);
|
|
967
1187
|
if (values.diff === true && diff.unified !== "")
|
|
968
|
-
|
|
1188
|
+
process9.stdout.write(diff.unified);
|
|
969
1189
|
}
|
|
970
|
-
if (
|
|
1190
|
+
if (json)
|
|
1191
|
+
printJson({ dryRun: values["dry-run"] === true, files: done });
|
|
1192
|
+
else if (values["dry-run"] === true)
|
|
971
1193
|
console.log("dry run: nothing written");
|
|
972
1194
|
return 0;
|
|
973
1195
|
}
|
|
974
|
-
|
|
1196
|
+
process9.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.
|
|
4
|
+
"version": "0.5.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",
|
|
@@ -36,6 +36,6 @@
|
|
|
36
36
|
"sub": "$npm_execpath src/cli.ts"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
|
-
"@kaynooo/cli-kit": "0.
|
|
39
|
+
"@kaynooo/cli-kit": "0.20.0"
|
|
40
40
|
}
|
|
41
41
|
}
|