@kaynooo/cli-edit 0.4.1 → 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 +107 -56
- package/package.json +1 -1
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,16 +2,15 @@
|
|
|
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
15
|
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
17
16
|
function x(s) {
|
|
@@ -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,26 +295,35 @@ 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
|
+
}
|
|
299
301
|
|
|
300
302
|
// ../kit/src/help.ts
|
|
301
|
-
import
|
|
303
|
+
import process3 from "process";
|
|
302
304
|
var OPTIONAL = /\[[^\]]+\]/g;
|
|
303
305
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
304
306
|
var FULL_STOP = /\.$/;
|
|
305
|
-
function usageLine(usage, colors = paint(
|
|
307
|
+
function usageLine(usage, colors = paint(process3.stdout)) {
|
|
306
308
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
307
309
|
}
|
|
308
|
-
function helpText(usage, options, colors = paint(
|
|
309
|
-
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
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(`
|
|
310
312
|
`);
|
|
311
313
|
}
|
|
312
|
-
function
|
|
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)) {
|
|
313
321
|
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
314
322
|
}
|
|
315
|
-
function wantsHelpJson(env =
|
|
323
|
+
function wantsHelpJson(env = process3.env) {
|
|
316
324
|
return env.KIT_HELP === "json";
|
|
317
325
|
}
|
|
318
|
-
function description(usage, { examples = [], replaces } = {}) {
|
|
326
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
319
327
|
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
320
328
|
`);
|
|
321
329
|
const first = lines[0];
|
|
@@ -326,15 +334,17 @@ function description(usage, { examples = [], replaces } = {}) {
|
|
|
326
334
|
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
327
335
|
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
328
336
|
...replaces === undefined ? {} : { replaces },
|
|
329
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
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 } })) }
|
|
330
340
|
};
|
|
331
341
|
}
|
|
332
|
-
function exampleRows(examples, colors = paint(
|
|
342
|
+
function exampleRows(examples, colors = paint(process3.stdout)) {
|
|
333
343
|
if (examples.length === 0)
|
|
334
344
|
return [];
|
|
335
345
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
336
346
|
}
|
|
337
|
-
function optionRows(options, colors = paint(
|
|
347
|
+
function optionRows(options, colors = paint(process3.stdout)) {
|
|
338
348
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
339
349
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
340
350
|
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
@@ -366,7 +376,7 @@ function closest(name, names) {
|
|
|
366
376
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
367
377
|
}
|
|
368
378
|
// ../kit/src/input.ts
|
|
369
|
-
import
|
|
379
|
+
import process4 from "process";
|
|
370
380
|
var WHOLE = /^\d+$/;
|
|
371
381
|
function wholeNumber(value, name, fallback, min = 1) {
|
|
372
382
|
if (value === undefined)
|
|
@@ -378,7 +388,7 @@ function wholeNumber(value, name, fallback, min = 1) {
|
|
|
378
388
|
}
|
|
379
389
|
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
380
390
|
if (path === "-") {
|
|
381
|
-
if (
|
|
391
|
+
if (process4.stdin.isTTY)
|
|
382
392
|
fail(noStdin);
|
|
383
393
|
return Bun.stdin.text();
|
|
384
394
|
}
|
|
@@ -390,6 +400,10 @@ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
|
390
400
|
|
|
391
401
|
// ../kit/src/args.ts
|
|
392
402
|
var DASHES = /^-+/;
|
|
403
|
+
function jsonOption(holds) {
|
|
404
|
+
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
405
|
+
}
|
|
406
|
+
|
|
393
407
|
class Exit extends Error {
|
|
394
408
|
code;
|
|
395
409
|
hint;
|
|
@@ -433,7 +447,7 @@ var OUTPUT_OPTIONS = {
|
|
|
433
447
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
434
448
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
435
449
|
};
|
|
436
|
-
function applyOutput(color, plain, env =
|
|
450
|
+
function applyOutput(color, plain, env = process5.env) {
|
|
437
451
|
const when = plain === true ? "never" : color ?? "auto";
|
|
438
452
|
if (when === "auto")
|
|
439
453
|
return;
|
|
@@ -456,7 +470,7 @@ function parse(args, usage, options, settings = {}) {
|
|
|
456
470
|
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
457
471
|
let parsed;
|
|
458
472
|
try {
|
|
459
|
-
parsed = parseArgs({ args: joinDashValues(withBare(own, all), 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 });
|
|
460
474
|
} catch (error) {
|
|
461
475
|
const message = parseError(error);
|
|
462
476
|
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
@@ -464,7 +478,7 @@ function parse(args, usage, options, settings = {}) {
|
|
|
464
478
|
const values = parsed.values;
|
|
465
479
|
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
466
480
|
if (values.help === true) {
|
|
467
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
|
|
481
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
|
|
468
482
|
throw new HelpShown;
|
|
469
483
|
}
|
|
470
484
|
checkChoices(parsed.values, all);
|
|
@@ -506,6 +520,18 @@ function listed(options, allowNegative) {
|
|
|
506
520
|
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
507
521
|
}));
|
|
508
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
|
+
}
|
|
509
535
|
function withBare(args, options) {
|
|
510
536
|
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
511
537
|
if (bare.size === 0)
|
|
@@ -596,13 +622,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
596
622
|
var RESET_STYLE = `${ESC}[0m`;
|
|
597
623
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
598
624
|
// ../kit/src/cli.ts
|
|
599
|
-
import
|
|
625
|
+
import { readFileSync, realpathSync } from "fs";
|
|
626
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
627
|
+
import process7 from "process";
|
|
600
628
|
|
|
601
629
|
// ../kit/src/usage.ts
|
|
602
630
|
import { appendFileSync, mkdirSync } from "fs";
|
|
603
631
|
import { homedir } from "os";
|
|
604
632
|
import { dirname, isAbsolute, join } from "path";
|
|
605
|
-
import
|
|
633
|
+
import process6 from "process";
|
|
606
634
|
|
|
607
635
|
// ../kit/src/logs.ts
|
|
608
636
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -616,14 +644,14 @@ var usageError;
|
|
|
616
644
|
function noteUsageError(message) {
|
|
617
645
|
usageError = message;
|
|
618
646
|
}
|
|
619
|
-
function stateHome(env =
|
|
647
|
+
function stateHome(env = process6.env) {
|
|
620
648
|
const dir = env.XDG_STATE_HOME;
|
|
621
649
|
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
622
650
|
}
|
|
623
|
-
function usagePath(env =
|
|
651
|
+
function usagePath(env = process6.env) {
|
|
624
652
|
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
625
653
|
}
|
|
626
|
-
function usageRecorded(env =
|
|
654
|
+
function usageRecorded(env = process6.env) {
|
|
627
655
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
628
656
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
629
657
|
}
|
|
@@ -637,7 +665,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
637
665
|
usageError = undefined;
|
|
638
666
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
639
667
|
}
|
|
640
|
-
function recordUsage(entry, env =
|
|
668
|
+
function recordUsage(entry, env = process6.env) {
|
|
641
669
|
if (!usageRecorded(env))
|
|
642
670
|
return;
|
|
643
671
|
try {
|
|
@@ -655,8 +683,8 @@ var LEVEL_OPTIONS = {
|
|
|
655
683
|
};
|
|
656
684
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
657
685
|
function printError(prefix, message, hint, cause) {
|
|
658
|
-
const colors = paint(
|
|
659
|
-
const styled = takesControlCodes(
|
|
686
|
+
const colors = paint(process7.stderr);
|
|
687
|
+
const styled = takesControlCodes(process7.stderr);
|
|
660
688
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
661
689
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
662
690
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -738,11 +766,22 @@ async function printCandidates(found) {
|
|
|
738
766
|
console.log(line);
|
|
739
767
|
return 0;
|
|
740
768
|
}
|
|
741
|
-
|
|
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)) {
|
|
742
781
|
if (argv[0] === COMPLETE)
|
|
743
782
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
744
783
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
745
|
-
console.log(version);
|
|
784
|
+
console.log(version ?? packageVersion());
|
|
746
785
|
return 0;
|
|
747
786
|
}
|
|
748
787
|
let code;
|
|
@@ -751,8 +790,11 @@ async function runMain({ name, version, run, redact, usage }, argv = process6.ar
|
|
|
751
790
|
} catch (error) {
|
|
752
791
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
753
792
|
}
|
|
754
|
-
if (usage !== false)
|
|
755
|
-
|
|
793
|
+
if (usage !== false) {
|
|
794
|
+
try {
|
|
795
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
796
|
+
} catch {}
|
|
797
|
+
}
|
|
756
798
|
return code;
|
|
757
799
|
}
|
|
758
800
|
// ../kit/src/secrets.ts
|
|
@@ -761,9 +803,6 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
|
|
|
761
803
|
var {Glob } = globalThis.Bun;
|
|
762
804
|
var SESSION_FILES = new Glob("*.json");
|
|
763
805
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
764
|
-
// package.json
|
|
765
|
-
var version = "0.4.1";
|
|
766
|
-
|
|
767
806
|
// src/blocks.ts
|
|
768
807
|
var LINE_BREAK = /\r?\n/;
|
|
769
808
|
var OPENER = /^(<{7,}) SEARCH$/;
|
|
@@ -819,15 +858,15 @@ function parseBlocks(text) {
|
|
|
819
858
|
// src/diff.ts
|
|
820
859
|
import { mkdtempSync, rmSync, writeFileSync } from "fs";
|
|
821
860
|
import { tmpdir } from "os";
|
|
822
|
-
import { join as
|
|
861
|
+
import { join as join3 } from "path";
|
|
823
862
|
async function diffTexts(path, before, after) {
|
|
824
|
-
const dir = mkdtempSync(
|
|
863
|
+
const dir = mkdtempSync(join3(tmpdir(), "sub-"));
|
|
825
864
|
try {
|
|
826
|
-
writeFileSync(
|
|
827
|
-
writeFileSync(
|
|
865
|
+
writeFileSync(join3(dir, "before"), before);
|
|
866
|
+
writeFileSync(join3(dir, "after"), after);
|
|
828
867
|
let child;
|
|
829
868
|
try {
|
|
830
|
-
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" });
|
|
831
870
|
} catch {
|
|
832
871
|
throw new Error("diff is not installed, which sub needs to show its changes");
|
|
833
872
|
}
|
|
@@ -949,7 +988,8 @@ var OPTIONS = {
|
|
|
949
988
|
regex: { type: "boolean", short: "r", description: "--from is a regular expression (^ and $ match each line), --to may use $1, ${1}, $<name> and ${name}" },
|
|
950
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" },
|
|
951
990
|
diff: { type: "boolean", short: "d", description: "print each file's unified diff" },
|
|
952
|
-
"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")
|
|
953
993
|
};
|
|
954
994
|
var PAIR_KEYS = ["from", "to", "count", "all", "regex"];
|
|
955
995
|
function checkPattern(pair, label) {
|
|
@@ -1008,14 +1048,14 @@ function writable(path) {
|
|
|
1008
1048
|
var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
1009
1049
|
function readUtf8(path) {
|
|
1010
1050
|
try {
|
|
1011
|
-
return UTF8.decode(
|
|
1051
|
+
return UTF8.decode(readFileSync2(path));
|
|
1012
1052
|
} catch {
|
|
1013
1053
|
return;
|
|
1014
1054
|
}
|
|
1015
1055
|
}
|
|
1016
1056
|
function canonical(path) {
|
|
1017
1057
|
try {
|
|
1018
|
-
return
|
|
1058
|
+
return realpathSync2(path);
|
|
1019
1059
|
} catch {
|
|
1020
1060
|
return resolve(path);
|
|
1021
1061
|
}
|
|
@@ -1030,8 +1070,8 @@ function dedupe(paths) {
|
|
|
1030
1070
|
return [...byFile.values()];
|
|
1031
1071
|
}
|
|
1032
1072
|
function writeAtomic(path, text) {
|
|
1033
|
-
const target =
|
|
1034
|
-
const temp = `${target}.sub-${
|
|
1073
|
+
const target = realpathSync2(path);
|
|
1074
|
+
const temp = `${target}.sub-${process9.pid}`;
|
|
1035
1075
|
try {
|
|
1036
1076
|
writeFileSync2(temp, text);
|
|
1037
1077
|
chmodSync(temp, (statSync(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
|
|
@@ -1101,23 +1141,27 @@ async function main(argv) {
|
|
|
1101
1141
|
const problems = [];
|
|
1102
1142
|
for (const [path, pairs] of edits) {
|
|
1103
1143
|
if (!existsSync(path)) {
|
|
1104
|
-
problems.push(
|
|
1144
|
+
problems.push({ path, problem: "no such file" });
|
|
1105
1145
|
continue;
|
|
1106
1146
|
}
|
|
1107
1147
|
const before = readUtf8(path);
|
|
1108
1148
|
if (before === undefined) {
|
|
1109
|
-
problems.push(
|
|
1149
|
+
problems.push({ path, problem: "not valid UTF-8, left alone" });
|
|
1110
1150
|
continue;
|
|
1111
1151
|
}
|
|
1112
1152
|
const applied = applyPairs(before, pairs);
|
|
1113
|
-
problems.push(...applied.problems.map((problem) =>
|
|
1153
|
+
problems.push(...applied.problems.map((problem) => ({ path, problem })));
|
|
1114
1154
|
if (applied.problems.length === 0 && values["dry-run"] !== true && !writable(path))
|
|
1115
|
-
problems.push(
|
|
1155
|
+
problems.push({ path, problem: "not writable" });
|
|
1116
1156
|
changes.push({ path, before, after: applied.text, lines: applied.lines });
|
|
1117
1157
|
}
|
|
1158
|
+
const json = values.json === true;
|
|
1118
1159
|
if (problems.length > 0) {
|
|
1119
|
-
|
|
1120
|
-
|
|
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(`
|
|
1121
1165
|
`)}`);
|
|
1122
1166
|
return 1;
|
|
1123
1167
|
}
|
|
@@ -1129,17 +1173,24 @@ ${problems.join(`
|
|
|
1129
1173
|
${error instanceof Error ? error.message : String(error)}`);
|
|
1130
1174
|
return 1;
|
|
1131
1175
|
}
|
|
1176
|
+
const done = [];
|
|
1132
1177
|
for (const { path, before, after, lines, diff } of changes) {
|
|
1133
1178
|
if (diff === undefined)
|
|
1134
1179
|
continue;
|
|
1135
1180
|
if (values["dry-run"] !== true && after !== before)
|
|
1136
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
|
+
}
|
|
1137
1186
|
console.log(`${path}: ${plural(lines.length, "replacement")} on line${lines.length === 1 ? "" : "s"} ${listLines(lines)}, +${diff.added} -${diff.removed}`);
|
|
1138
1187
|
if (values.diff === true && diff.unified !== "")
|
|
1139
|
-
|
|
1188
|
+
process9.stdout.write(diff.unified);
|
|
1140
1189
|
}
|
|
1141
|
-
if (
|
|
1190
|
+
if (json)
|
|
1191
|
+
printJson({ dryRun: values["dry-run"] === true, files: done });
|
|
1192
|
+
else if (values["dry-run"] === true)
|
|
1142
1193
|
console.log("dry run: nothing written");
|
|
1143
1194
|
return 0;
|
|
1144
1195
|
}
|
|
1145
|
-
|
|
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",
|