@kaynooo/cli-edit 0.10.0 → 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.
- package/dist/cli.js +309 -72
- 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
|
|
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
|
|
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
|
|
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(
|
|
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) ||
|
|
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,24 +397,20 @@ function printJson(value) {
|
|
|
361
397
|
|
|
362
398
|
// ../kit/src/help.ts
|
|
363
399
|
import process8 from "process";
|
|
364
|
-
var OPTIONAL =
|
|
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)) {
|
|
368
404
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
369
405
|
}
|
|
370
|
-
function helpText(usage, options, colors = paint(process8.stdout), { examples = [],
|
|
371
|
-
return [usageLine(usage, colors),
|
|
406
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
|
|
407
|
+
return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
372
408
|
`);
|
|
373
409
|
}
|
|
374
410
|
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
375
411
|
if (exits.length === 0)
|
|
376
412
|
return [];
|
|
377
|
-
|
|
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}`];
|
|
413
|
+
return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
|
|
382
414
|
}
|
|
383
415
|
function wantsHelpJson(env = process8.env) {
|
|
384
416
|
return env.KIT_HELP === "json";
|
|
@@ -404,29 +436,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
|
404
436
|
return [];
|
|
405
437
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
406
438
|
}
|
|
439
|
+
var MAX_INLINE_CHOICES = 24;
|
|
407
440
|
function optionRows(options, colors = paint(process8.stdout)) {
|
|
408
441
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
409
442
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
410
|
-
const
|
|
443
|
+
const choices = option.choices?.join("|");
|
|
444
|
+
const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
|
|
445
|
+
const named = inline ? `<${choices}>` : "<value>";
|
|
411
446
|
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
412
447
|
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
413
|
-
|
|
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 };
|
|
414
450
|
});
|
|
415
451
|
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
416
452
|
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
417
453
|
}
|
|
418
454
|
|
|
419
455
|
// ../kit/src/text.ts
|
|
420
|
-
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
421
456
|
function distance(a, b) {
|
|
422
|
-
|
|
423
|
-
|
|
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()) {
|
|
424
462
|
const current = [i + 1];
|
|
425
|
-
for (const [j,
|
|
426
|
-
|
|
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;
|
|
427
470
|
previous = current;
|
|
428
471
|
}
|
|
429
|
-
return previous[
|
|
472
|
+
return previous[right.length] ?? 0;
|
|
430
473
|
}
|
|
431
474
|
function closest(name, names) {
|
|
432
475
|
const started = names.find((known) => known.startsWith(name));
|
|
@@ -676,12 +719,12 @@ function nearestOption(message, options, allowNegative) {
|
|
|
676
719
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
677
720
|
}
|
|
678
721
|
// ../kit/src/argv.ts
|
|
679
|
-
import { readFileSync as
|
|
722
|
+
import { readFileSync as readFileSync3, realpathSync } from "fs";
|
|
680
723
|
import { resolve as resolve3 } from "path";
|
|
681
724
|
import process11 from "process";
|
|
682
725
|
function commandLine() {
|
|
683
726
|
try {
|
|
684
|
-
return
|
|
727
|
+
return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
|
|
685
728
|
} catch {
|
|
686
729
|
return;
|
|
687
730
|
}
|
|
@@ -699,21 +742,129 @@ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), scr
|
|
|
699
742
|
const after = at === -1 ? [] : cmdline.slice(at + 1);
|
|
700
743
|
return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
|
|
701
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
|
+
|
|
702
835
|
// ../kit/src/progress.ts
|
|
703
836
|
var ESC = String.fromCharCode(27);
|
|
704
837
|
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
705
838
|
var RESET_STYLE = `${ESC}[0m`;
|
|
706
839
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
707
840
|
// ../kit/src/cli.ts
|
|
708
|
-
import { readFileSync as
|
|
841
|
+
import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
|
|
709
842
|
import { dirname as dirname3, join as join5 } from "path";
|
|
843
|
+
import process15 from "process";
|
|
844
|
+
|
|
845
|
+
// ../kit/src/notify.ts
|
|
710
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
|
+
}
|
|
711
862
|
|
|
712
863
|
// ../kit/src/usage.ts
|
|
713
864
|
import { appendFileSync, mkdirSync } from "fs";
|
|
714
865
|
import { homedir as homedir3 } from "os";
|
|
715
866
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
716
|
-
import
|
|
867
|
+
import process14 from "process";
|
|
717
868
|
|
|
718
869
|
// ../kit/src/logs.ts
|
|
719
870
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -727,14 +878,14 @@ var usageError;
|
|
|
727
878
|
function noteUsageError(message) {
|
|
728
879
|
usageError = message;
|
|
729
880
|
}
|
|
730
|
-
function stateHome(env =
|
|
881
|
+
function stateHome(env = process14.env) {
|
|
731
882
|
const dir = env.XDG_STATE_HOME;
|
|
732
883
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
733
884
|
}
|
|
734
|
-
function usagePath(env =
|
|
885
|
+
function usagePath(env = process14.env) {
|
|
735
886
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
736
887
|
}
|
|
737
|
-
function usageRecorded(env =
|
|
888
|
+
function usageRecorded(env = process14.env) {
|
|
738
889
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
739
890
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
740
891
|
}
|
|
@@ -748,7 +899,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
748
899
|
usageError = undefined;
|
|
749
900
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
750
901
|
}
|
|
751
|
-
function recordUsage(entry, env =
|
|
902
|
+
function recordUsage(entry, env = process14.env) {
|
|
752
903
|
if (!usageRecorded(env))
|
|
753
904
|
return;
|
|
754
905
|
try {
|
|
@@ -766,8 +917,8 @@ var LEVEL_OPTIONS = {
|
|
|
766
917
|
};
|
|
767
918
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
768
919
|
function printError(prefix, message, hint, cause) {
|
|
769
|
-
const colors = paint(
|
|
770
|
-
const styled = takesControlCodes(
|
|
920
|
+
const colors = paint(process15.stderr);
|
|
921
|
+
const styled = takesControlCodes(process15.stderr);
|
|
771
922
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
772
923
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
773
924
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -856,7 +1007,7 @@ function packageVersion(entry = Bun.main) {
|
|
|
856
1007
|
} catch {}
|
|
857
1008
|
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
858
1009
|
try {
|
|
859
|
-
const { version } = JSON.parse(
|
|
1010
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
860
1011
|
if (typeof version === "string")
|
|
861
1012
|
return version;
|
|
862
1013
|
} catch {}
|
|
@@ -872,11 +1023,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
|
|
|
872
1023
|
return 0;
|
|
873
1024
|
}
|
|
874
1025
|
let code;
|
|
1026
|
+
const started = performance.now();
|
|
875
1027
|
try {
|
|
876
1028
|
code = await run(argv);
|
|
877
1029
|
} catch (error) {
|
|
878
1030
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
879
1031
|
}
|
|
1032
|
+
notifyEnd(name, code, performance.now() - started);
|
|
880
1033
|
if (usage !== false) {
|
|
881
1034
|
try {
|
|
882
1035
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -886,6 +1039,11 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
|
|
|
886
1039
|
}
|
|
887
1040
|
// ../kit/src/folders.ts
|
|
888
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
|
+
}
|
|
889
1047
|
// ../kit/src/secrets.ts
|
|
890
1048
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
891
1049
|
// ../kit/src/sessions.ts
|
|
@@ -977,6 +1135,7 @@ async function diffTexts(path, before, after) {
|
|
|
977
1135
|
var CRLF = /\r?\n/g;
|
|
978
1136
|
var BRACED_GROUP = /\$\$|\$\{(\w+)\}/g;
|
|
979
1137
|
var DIGITS = /^\d+$/;
|
|
1138
|
+
var ESCAPE2 = /\\\\|\\([nt])/g;
|
|
980
1139
|
var LONGEST_LIST = 8;
|
|
981
1140
|
function linesOf(text, indexes) {
|
|
982
1141
|
const lines = [];
|
|
@@ -1011,8 +1170,16 @@ function firstLineHint(text, from) {
|
|
|
1011
1170
|
`).flatMap((line, i) => line.includes(first) ? [i + 1] : []);
|
|
1012
1171
|
return lines.length === 0 ? "" : ` (its first line is on ${K("line", lines.length)} ${listLines(lines)})`;
|
|
1013
1172
|
}
|
|
1014
|
-
function compile(source) {
|
|
1015
|
-
return new RegExp(source,
|
|
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
|
+
});
|
|
1016
1183
|
}
|
|
1017
1184
|
function bracedGroups(to) {
|
|
1018
1185
|
return to.replace(BRACED_GROUP, (whole, group) => {
|
|
@@ -1028,16 +1195,19 @@ function applyPairs(original, pairs) {
|
|
|
1028
1195
|
`);
|
|
1029
1196
|
const lines = [];
|
|
1030
1197
|
const problems = [];
|
|
1198
|
+
let matched = 0;
|
|
1031
1199
|
let text = original;
|
|
1032
1200
|
for (const [i, pair] of pairs.entries()) {
|
|
1033
1201
|
const label = pairs.length > 1 ? `pair ${i + 1}: ` : "";
|
|
1034
1202
|
const from = crlf && pair.regex !== true ? pair.from.replace(CRLF, `\r
|
|
1035
1203
|
`) : pair.from;
|
|
1036
|
-
const
|
|
1037
|
-
|
|
1038
|
-
|
|
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;
|
|
1039
1208
|
const indexes = pattern === undefined ? literalIndexes(text, from) : [...text.matchAll(pattern)].map((match) => match.index);
|
|
1040
1209
|
const found = linesOf(text, indexes);
|
|
1210
|
+
matched += indexes.length;
|
|
1041
1211
|
const expected = pair.count ?? 1;
|
|
1042
1212
|
if (pair.all === true ? indexes.length === 0 : indexes.length !== expected) {
|
|
1043
1213
|
const wanted = pair.all === true ? "at least 1" : String(expected);
|
|
@@ -1050,12 +1220,48 @@ function applyPairs(original, pairs) {
|
|
|
1050
1220
|
lines.push(...found);
|
|
1051
1221
|
text = pattern === undefined ? text.split(from).join(to) : text.replace(pattern, bracedGroups(to));
|
|
1052
1222
|
}
|
|
1053
|
-
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();
|
|
1054
1258
|
}
|
|
1055
1259
|
|
|
1056
1260
|
// src/cli.ts
|
|
1057
1261
|
var USAGE = `sub [options] <file>...: replaces text in files, writing nothing unless every replacement matches as often as expected
|
|
1058
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
|
+
|
|
1059
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:
|
|
1060
1266
|
|
|
1061
1267
|
sub src/a.php <<'EOF'
|
|
@@ -1066,38 +1272,43 @@ new lines
|
|
|
1066
1272
|
>>>>>>> REPLACE
|
|
1067
1273
|
EOF
|
|
1068
1274
|
|
|
1069
|
-
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
|
|
1070
|
-
|
|
1071
|
-
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.`;
|
|
1275
|
+
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.`;
|
|
1276
|
+
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"]];
|
|
1072
1277
|
var OPTIONS = {
|
|
1073
1278
|
from: { type: "string", short: "f", description: "text to find, taken literally" },
|
|
1074
1279
|
to: { type: "string", short: "t", description: "text to put in its place, empty to delete it" },
|
|
1075
1280
|
count: { type: "string", short: "n", description: "matches expected in each file (default 1)" },
|
|
1076
1281
|
all: { type: "boolean", short: "a", description: "replace every match, expecting at least one in each file" },
|
|
1077
|
-
|
|
1078
|
-
|
|
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" },
|
|
1079
1287
|
diff: { type: "boolean", short: "d", description: "print each file's unified diff" },
|
|
1080
1288
|
"dry-run": { type: "boolean", description: "show what would change without writing" },
|
|
1081
1289
|
quiet: { type: "boolean", short: "q", description: "print nothing on success, the diff aside" },
|
|
1082
|
-
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")
|
|
1083
1291
|
};
|
|
1084
|
-
var PAIR_KEYS = ["from", "to", "count", "all", "regex"];
|
|
1292
|
+
var PAIR_KEYS = ["from", "to", "count", "all", "regex", "ignoreCase", "dotAll"];
|
|
1085
1293
|
function checkPattern(pair, label) {
|
|
1086
1294
|
if (pair.from === "")
|
|
1087
1295
|
fail(`${label}--from is empty`);
|
|
1088
1296
|
if (pair.regex !== true)
|
|
1089
1297
|
return;
|
|
1090
1298
|
try {
|
|
1091
|
-
compile(pair.from);
|
|
1299
|
+
compile(pair.from, pair);
|
|
1092
1300
|
} catch (error) {
|
|
1093
1301
|
fail(`${label}--from is no valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
|
|
1094
1302
|
}
|
|
1095
1303
|
}
|
|
1304
|
+
function isFlag(value) {
|
|
1305
|
+
return value === undefined || typeof value === "boolean";
|
|
1306
|
+
}
|
|
1096
1307
|
function pairFrom(item, i, defaults) {
|
|
1097
1308
|
const label = `pair ${i + 1}: `;
|
|
1098
1309
|
if (typeof item !== "object" || item === null || Array.isArray(item))
|
|
1099
1310
|
fail(`${label}give an object {from, to}`);
|
|
1100
|
-
const { from, to, count, all, regex, ...rest } = item;
|
|
1311
|
+
const { from, to, count, all, regex, ignoreCase, dotAll, ...rest } = item;
|
|
1101
1312
|
const unknown = Object.keys(rest);
|
|
1102
1313
|
if (unknown.length > 0)
|
|
1103
1314
|
fail(`${label}unknown ${K("key", unknown.length)} ${unknown.join(", ")}, known: ${PAIR_KEYS.join(", ")}`);
|
|
@@ -1105,9 +1316,11 @@ function pairFrom(item, i, defaults) {
|
|
|
1105
1316
|
fail(`${label}from and to must both be strings`);
|
|
1106
1317
|
if (count !== undefined && (typeof count !== "number" || !Number.isInteger(count) || count < 1))
|
|
1107
1318
|
fail(`${label}count takes a whole number from 1`);
|
|
1108
|
-
if (all
|
|
1109
|
-
fail(`${label}all and
|
|
1110
|
-
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`);
|
|
1111
1324
|
checkPattern(pair, label);
|
|
1112
1325
|
return pair;
|
|
1113
1326
|
}
|
|
@@ -1126,7 +1339,7 @@ async function readPairs(path, defaults) {
|
|
|
1126
1339
|
}
|
|
1127
1340
|
function writable(path) {
|
|
1128
1341
|
try {
|
|
1129
|
-
accessSync(path,
|
|
1342
|
+
accessSync(path, constants2.W_OK);
|
|
1130
1343
|
return true;
|
|
1131
1344
|
} catch {
|
|
1132
1345
|
return false;
|
|
@@ -1135,7 +1348,7 @@ function writable(path) {
|
|
|
1135
1348
|
var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
1136
1349
|
function readUtf8(path) {
|
|
1137
1350
|
try {
|
|
1138
|
-
return UTF8.decode(
|
|
1351
|
+
return UTF8.decode(readFileSync5(path));
|
|
1139
1352
|
} catch {
|
|
1140
1353
|
return;
|
|
1141
1354
|
}
|
|
@@ -1158,7 +1371,7 @@ function dedupe(paths) {
|
|
|
1158
1371
|
}
|
|
1159
1372
|
function writeAtomic(path, text) {
|
|
1160
1373
|
const target = realpathSync3(path);
|
|
1161
|
-
const temp = `${target}.sub-${
|
|
1374
|
+
const temp = `${target}.sub-${process17.pid}`;
|
|
1162
1375
|
try {
|
|
1163
1376
|
writeFileSync2(temp, text);
|
|
1164
1377
|
chmodSync(temp, (statSync2(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
|
|
@@ -1170,30 +1383,30 @@ function writeAtomic(path, text) {
|
|
|
1170
1383
|
}
|
|
1171
1384
|
var STDIN_SILENCE_MS = 3000;
|
|
1172
1385
|
async function blocksOnStdin(files) {
|
|
1173
|
-
const extra = files.slice(1).filter((path) => !
|
|
1386
|
+
const extra = files.slice(1).filter((path) => !existsSync5(path));
|
|
1174
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]}
|
|
1175
1388
|
|
|
1176
1389
|
`;
|
|
1177
1390
|
const hint = `${strings}give --from and --to, or pipe SEARCH/REPLACE blocks on stdin from a heredoc
|
|
1178
1391
|
|
|
1179
1392
|
${USAGE}`;
|
|
1180
|
-
if (
|
|
1393
|
+
if (process17.stdin.isTTY)
|
|
1181
1394
|
fail(hint);
|
|
1182
1395
|
return new Promise((resolve) => {
|
|
1183
1396
|
const chunks = [];
|
|
1184
1397
|
const timer = setTimeout(() => {
|
|
1185
1398
|
console.error(`error: sub: ${hint}`);
|
|
1186
|
-
|
|
1399
|
+
process17.exit(2);
|
|
1187
1400
|
}, STDIN_SILENCE_MS);
|
|
1188
|
-
|
|
1401
|
+
process17.stdin.on("data", (chunk) => {
|
|
1189
1402
|
clearTimeout(timer);
|
|
1190
1403
|
chunks.push(chunk);
|
|
1191
1404
|
});
|
|
1192
|
-
|
|
1405
|
+
process17.stdin.on("end", () => {
|
|
1193
1406
|
clearTimeout(timer);
|
|
1194
1407
|
if (chunks.length === 0 && extra.length > 0) {
|
|
1195
1408
|
console.error(`error: sub: ${hint}`);
|
|
1196
|
-
|
|
1409
|
+
process17.exit(2);
|
|
1197
1410
|
}
|
|
1198
1411
|
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
1199
1412
|
});
|
|
@@ -1217,7 +1430,7 @@ ${USAGE}`);
|
|
|
1217
1430
|
fail(`give --from and --to (--to '' deletes), or --pairs
|
|
1218
1431
|
|
|
1219
1432
|
${USAGE}`);
|
|
1220
|
-
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 }];
|
|
1221
1434
|
checkPattern(pairs[0], "");
|
|
1222
1435
|
}
|
|
1223
1436
|
for (const path of files)
|
|
@@ -1228,7 +1441,7 @@ ${USAGE}`);
|
|
|
1228
1441
|
if (typeof blocks === "string")
|
|
1229
1442
|
fail(`blocks: ${blocks}`);
|
|
1230
1443
|
for (const [i, block] of blocks.entries()) {
|
|
1231
|
-
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 };
|
|
1232
1445
|
const named = block.file === undefined ? undefined : normalize(block.file);
|
|
1233
1446
|
const targets = named === undefined ? files : [spellings.get(canonical(named)) ?? named];
|
|
1234
1447
|
if (named !== undefined && !spellings.has(canonical(named)))
|
|
@@ -1246,37 +1459,59 @@ ${USAGE}`);
|
|
|
1246
1459
|
return edits;
|
|
1247
1460
|
}
|
|
1248
1461
|
async function main(argv) {
|
|
1249
|
-
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"]] });
|
|
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"]] });
|
|
1250
1463
|
const { values, positionals } = parsed;
|
|
1251
|
-
const
|
|
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());
|
|
1252
1474
|
if (values.count !== undefined && values.all === true)
|
|
1253
1475
|
fail("--count and --all exclude each other");
|
|
1254
|
-
|
|
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 };
|
|
1255
1481
|
const edits = await plan(values, files, defaults);
|
|
1256
1482
|
const changes = [];
|
|
1257
1483
|
const problems = [];
|
|
1484
|
+
const skipped = [];
|
|
1258
1485
|
for (const [path, pairs] of edits) {
|
|
1259
|
-
if (!
|
|
1486
|
+
if (!existsSync5(path)) {
|
|
1260
1487
|
problems.push({ path, problem: "no such file" });
|
|
1261
1488
|
continue;
|
|
1262
1489
|
}
|
|
1263
1490
|
const before = readUtf8(path);
|
|
1491
|
+
if (before === undefined && walked.has(path))
|
|
1492
|
+
continue;
|
|
1264
1493
|
if (before === undefined) {
|
|
1265
1494
|
problems.push({ path, problem: "not valid UTF-8, left alone" });
|
|
1266
1495
|
continue;
|
|
1267
1496
|
}
|
|
1268
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
|
+
}
|
|
1269
1502
|
problems.push(...applied.problems.map((problem) => ({ path, problem })));
|
|
1270
1503
|
if (applied.problems.length === 0 && values["dry-run"] !== true && !writable(path))
|
|
1271
1504
|
problems.push({ path, problem: "not writable" });
|
|
1272
1505
|
changes.push({ path, before, after: applied.text, lines: applied.lines });
|
|
1273
1506
|
}
|
|
1274
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" });
|
|
1275
1510
|
if (problems.length > 0) {
|
|
1276
1511
|
if (json)
|
|
1277
1512
|
console.error(JSON.stringify({ error: "nothing written", failures: problems }));
|
|
1278
1513
|
else
|
|
1279
|
-
console.error(`${role("problem",
|
|
1514
|
+
console.error(`${role("problem", process17.stderr)("sub: nothing written")}
|
|
1280
1515
|
${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
|
|
1281
1516
|
`)}`);
|
|
1282
1517
|
return 1;
|
|
@@ -1285,7 +1520,7 @@ ${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
|
|
|
1285
1520
|
for (const change of changes)
|
|
1286
1521
|
change.diff = await diffTexts(change.path, change.before, change.after);
|
|
1287
1522
|
} catch (error) {
|
|
1288
|
-
console.error(`${role("problem",
|
|
1523
|
+
console.error(`${role("problem", process17.stderr)("sub: nothing written")}
|
|
1289
1524
|
${error instanceof Error ? error.message : String(error)}`);
|
|
1290
1525
|
return 1;
|
|
1291
1526
|
}
|
|
@@ -1300,14 +1535,16 @@ ${error instanceof Error ? error.message : String(error)}`);
|
|
|
1300
1535
|
continue;
|
|
1301
1536
|
}
|
|
1302
1537
|
if (values.quiet !== true)
|
|
1303
|
-
console.log(`${role("path",
|
|
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}`)}`);
|
|
1304
1539
|
if (values.diff === true && diff.unified !== "")
|
|
1305
|
-
|
|
1540
|
+
process17.stdout.write(diff.unified);
|
|
1306
1541
|
}
|
|
1307
1542
|
if (json)
|
|
1308
|
-
printJson({ dryRun: values["dry-run"] === true, files: done });
|
|
1309
|
-
else if (values
|
|
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)
|
|
1310
1547
|
console.log("dry run: nothing written");
|
|
1311
1548
|
return 0;
|
|
1312
1549
|
}
|
|
1313
|
-
|
|
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.
|
|
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.
|
|
42
|
+
"@kaynooo/cli-kit": "0.39.0"
|
|
43
43
|
}
|
|
44
44
|
}
|