@kaynooo/cli-edit 0.10.0 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +390 -74
- 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));
|
|
@@ -503,7 +546,7 @@ class Completing {
|
|
|
503
546
|
}
|
|
504
547
|
var completion = { active: false };
|
|
505
548
|
var OUTPUT_OPTIONS = {
|
|
506
|
-
color: { type: "string", description: "auto (on a terminal alone
|
|
549
|
+
color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
|
|
507
550
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
508
551
|
};
|
|
509
552
|
function applyOutput(color, plain, env = process10.env) {
|
|
@@ -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,189 @@ 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/completions.ts
|
|
846
|
+
var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
|
|
847
|
+
var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
|
|
848
|
+
set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
|
|
849
|
+
set -l current (commandline -ct)
|
|
850
|
+
for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
|
|
851
|
+
if test "$line" = __files__
|
|
852
|
+
__fish_complete_path $current
|
|
853
|
+
else
|
|
854
|
+
echo $line
|
|
855
|
+
end
|
|
856
|
+
end
|
|
857
|
+
end`;
|
|
858
|
+
var BASH_FUNCTION = `__kaynooo_cli_complete() {
|
|
859
|
+
local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
|
|
860
|
+
local -a lines
|
|
861
|
+
COMPREPLY=()
|
|
862
|
+
lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
|
|
863
|
+
for line in "\${lines[@]}"; do
|
|
864
|
+
if [[ $line == __files__ ]]; then
|
|
865
|
+
COMPREPLY+=($(compgen -f -- "$cur"))
|
|
866
|
+
else
|
|
867
|
+
words+="\${line%%$'\\t'*}"$'\\n'
|
|
868
|
+
fi
|
|
869
|
+
done
|
|
870
|
+
COMPREPLY+=($(compgen -W "$words" -- "$cur"))
|
|
871
|
+
}`;
|
|
872
|
+
var ZSH_FUNCTION = `__kaynooo_cli_complete() {
|
|
873
|
+
local line
|
|
874
|
+
local -a described plain
|
|
875
|
+
for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
|
|
876
|
+
if [[ $line == __files__ ]]; then
|
|
877
|
+
_files
|
|
878
|
+
elif [[ $line == *$'\\t'* ]]; then
|
|
879
|
+
described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
|
|
880
|
+
else
|
|
881
|
+
plain+=("$line")
|
|
882
|
+
fi
|
|
883
|
+
done
|
|
884
|
+
(( \${#described} )) && _describe -V value described
|
|
885
|
+
(( \${#plain} )) && compadd -- "\${plain[@]}"
|
|
886
|
+
return 0
|
|
887
|
+
}`;
|
|
888
|
+
function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
|
|
889
|
+
if (shell === "fish")
|
|
890
|
+
return `${header}
|
|
891
|
+
${FISH_FUNCTION}
|
|
892
|
+
${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
|
|
893
|
+
`).join("")}`;
|
|
894
|
+
if (shell === "bash")
|
|
895
|
+
return `${header}
|
|
896
|
+
${BASH_FUNCTION}
|
|
897
|
+
complete -F __kaynooo_cli_complete ${bins.join(" ")}
|
|
898
|
+
`;
|
|
899
|
+
return `${header}
|
|
900
|
+
${ZSH_FUNCTION}
|
|
901
|
+
compdef __kaynooo_cli_complete ${bins.join(" ")}
|
|
902
|
+
`;
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// ../kit/src/notify.ts
|
|
710
906
|
import process13 from "process";
|
|
907
|
+
var NOTIFY_AFTER_MS = 1e4;
|
|
908
|
+
var CANCELLED = 130;
|
|
909
|
+
function base64(text) {
|
|
910
|
+
return Buffer.from(text).toString("base64");
|
|
911
|
+
}
|
|
912
|
+
function notification(title, body, env = process13.env) {
|
|
913
|
+
const id = `kit${process13.pid}`;
|
|
914
|
+
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\\`];
|
|
915
|
+
return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
|
|
916
|
+
}
|
|
917
|
+
function notifyEnd(command, code, ms, { stream = process13.stderr, env = process13.env } = {}) {
|
|
918
|
+
if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
|
|
919
|
+
return;
|
|
920
|
+
stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
|
|
921
|
+
}
|
|
711
922
|
|
|
712
923
|
// ../kit/src/usage.ts
|
|
713
924
|
import { appendFileSync, mkdirSync } from "fs";
|
|
714
925
|
import { homedir as homedir3 } from "os";
|
|
715
926
|
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
716
|
-
import
|
|
927
|
+
import process14 from "process";
|
|
717
928
|
|
|
718
929
|
// ../kit/src/logs.ts
|
|
719
930
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -727,14 +938,14 @@ var usageError;
|
|
|
727
938
|
function noteUsageError(message) {
|
|
728
939
|
usageError = message;
|
|
729
940
|
}
|
|
730
|
-
function stateHome(env =
|
|
941
|
+
function stateHome(env = process14.env) {
|
|
731
942
|
const dir = env.XDG_STATE_HOME;
|
|
732
943
|
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
733
944
|
}
|
|
734
|
-
function usagePath(env =
|
|
945
|
+
function usagePath(env = process14.env) {
|
|
735
946
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
736
947
|
}
|
|
737
|
-
function usageRecorded(env =
|
|
948
|
+
function usageRecorded(env = process14.env) {
|
|
738
949
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
739
950
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
740
951
|
}
|
|
@@ -748,7 +959,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
748
959
|
usageError = undefined;
|
|
749
960
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
750
961
|
}
|
|
751
|
-
function recordUsage(entry, env =
|
|
962
|
+
function recordUsage(entry, env = process14.env) {
|
|
752
963
|
if (!usageRecorded(env))
|
|
753
964
|
return;
|
|
754
965
|
try {
|
|
@@ -764,10 +975,14 @@ var LEVEL_OPTIONS = {
|
|
|
764
975
|
...OUTPUT_OPTIONS,
|
|
765
976
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
766
977
|
};
|
|
767
|
-
var TOP_OPTIONS = {
|
|
978
|
+
var TOP_OPTIONS = {
|
|
979
|
+
...LEVEL_OPTIONS,
|
|
980
|
+
version: { type: "boolean", short: "v", description: "print the version" },
|
|
981
|
+
completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
|
|
982
|
+
};
|
|
768
983
|
function printError(prefix, message, hint, cause) {
|
|
769
|
-
const colors = paint(
|
|
770
|
-
const styled = takesControlCodes(
|
|
984
|
+
const colors = paint(process15.stderr);
|
|
985
|
+
const styled = takesControlCodes(process15.stderr);
|
|
771
986
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
772
987
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
773
988
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -844,6 +1059,19 @@ async function leafCandidates(run, words) {
|
|
|
844
1059
|
const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
|
|
845
1060
|
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
846
1061
|
}
|
|
1062
|
+
var COMPLETIONS = "--completions";
|
|
1063
|
+
function flagValue([flag = "", ...rest]) {
|
|
1064
|
+
return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
|
|
1065
|
+
}
|
|
1066
|
+
function printCompletionScript(name, args) {
|
|
1067
|
+
const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
|
|
1068
|
+
if (shell === undefined || args.length !== 1) {
|
|
1069
|
+
printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
|
|
1070
|
+
return 2;
|
|
1071
|
+
}
|
|
1072
|
+
console.log(completionScript(shell, [name]).trimEnd());
|
|
1073
|
+
return 0;
|
|
1074
|
+
}
|
|
847
1075
|
async function printCandidates(found) {
|
|
848
1076
|
for (const line of await found)
|
|
849
1077
|
console.log(line);
|
|
@@ -856,7 +1084,7 @@ function packageVersion(entry = Bun.main) {
|
|
|
856
1084
|
} catch {}
|
|
857
1085
|
for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
|
|
858
1086
|
try {
|
|
859
|
-
const { version } = JSON.parse(
|
|
1087
|
+
const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
|
|
860
1088
|
if (typeof version === "string")
|
|
861
1089
|
return version;
|
|
862
1090
|
} catch {}
|
|
@@ -867,16 +1095,20 @@ function packageVersion(entry = Bun.main) {
|
|
|
867
1095
|
async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
|
|
868
1096
|
if (argv[0] === COMPLETE)
|
|
869
1097
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
1098
|
+
if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
|
|
1099
|
+
return printCompletionScript(name, flagValue(argv));
|
|
870
1100
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
871
1101
|
console.log(version ?? packageVersion());
|
|
872
1102
|
return 0;
|
|
873
1103
|
}
|
|
874
1104
|
let code;
|
|
1105
|
+
const started = performance.now();
|
|
875
1106
|
try {
|
|
876
1107
|
code = await run(argv);
|
|
877
1108
|
} catch (error) {
|
|
878
1109
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
879
1110
|
}
|
|
1111
|
+
notifyEnd(name, code, performance.now() - started);
|
|
880
1112
|
if (usage !== false) {
|
|
881
1113
|
try {
|
|
882
1114
|
recordUsage(usageEntry(name, undefined, argv, code));
|
|
@@ -886,6 +1118,11 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
|
|
|
886
1118
|
}
|
|
887
1119
|
// ../kit/src/folders.ts
|
|
888
1120
|
var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
1121
|
+
function ignoredFolders(extra = [], where = {}) {
|
|
1122
|
+
const configured = readUserConfig("config", where).ignore;
|
|
1123
|
+
const names = Array.isArray(configured) ? configured.filter((name) => typeof name === "string" && name !== "") : [];
|
|
1124
|
+
return new Set([...SKIPPED_FOLDERS, ...extra, ...names]);
|
|
1125
|
+
}
|
|
889
1126
|
// ../kit/src/secrets.ts
|
|
890
1127
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
891
1128
|
// ../kit/src/sessions.ts
|
|
@@ -977,6 +1214,7 @@ async function diffTexts(path, before, after) {
|
|
|
977
1214
|
var CRLF = /\r?\n/g;
|
|
978
1215
|
var BRACED_GROUP = /\$\$|\$\{(\w+)\}/g;
|
|
979
1216
|
var DIGITS = /^\d+$/;
|
|
1217
|
+
var ESCAPE2 = /\\\\|\\([nt])/g;
|
|
980
1218
|
var LONGEST_LIST = 8;
|
|
981
1219
|
function linesOf(text, indexes) {
|
|
982
1220
|
const lines = [];
|
|
@@ -1011,8 +1249,16 @@ function firstLineHint(text, from) {
|
|
|
1011
1249
|
`).flatMap((line, i) => line.includes(first) ? [i + 1] : []);
|
|
1012
1250
|
return lines.length === 0 ? "" : ` (its first line is on ${K("line", lines.length)} ${listLines(lines)})`;
|
|
1013
1251
|
}
|
|
1014
|
-
function compile(source) {
|
|
1015
|
-
return new RegExp(source,
|
|
1252
|
+
function compile(source, { ignoreCase, dotAll } = {}) {
|
|
1253
|
+
return new RegExp(source, `gm${ignoreCase === true ? "i" : ""}${dotAll === true ? "s" : ""}`);
|
|
1254
|
+
}
|
|
1255
|
+
function escapes(to) {
|
|
1256
|
+
return to.replace(ESCAPE2, (whole, letter) => {
|
|
1257
|
+
if (letter === undefined)
|
|
1258
|
+
return whole;
|
|
1259
|
+
return letter === "n" ? `
|
|
1260
|
+
` : "\t";
|
|
1261
|
+
});
|
|
1016
1262
|
}
|
|
1017
1263
|
function bracedGroups(to) {
|
|
1018
1264
|
return to.replace(BRACED_GROUP, (whole, group) => {
|
|
@@ -1028,16 +1274,19 @@ function applyPairs(original, pairs) {
|
|
|
1028
1274
|
`);
|
|
1029
1275
|
const lines = [];
|
|
1030
1276
|
const problems = [];
|
|
1277
|
+
let matched = 0;
|
|
1031
1278
|
let text = original;
|
|
1032
1279
|
for (const [i, pair] of pairs.entries()) {
|
|
1033
1280
|
const label = pairs.length > 1 ? `pair ${i + 1}: ` : "";
|
|
1034
1281
|
const from = crlf && pair.regex !== true ? pair.from.replace(CRLF, `\r
|
|
1035
1282
|
`) : pair.from;
|
|
1036
|
-
const
|
|
1037
|
-
|
|
1038
|
-
|
|
1283
|
+
const typed = pair.regex === true ? escapes(pair.to) : pair.to;
|
|
1284
|
+
const to = crlf ? typed.replace(CRLF, `\r
|
|
1285
|
+
`) : typed;
|
|
1286
|
+
const pattern = pair.regex === true ? compile(from, pair) : undefined;
|
|
1039
1287
|
const indexes = pattern === undefined ? literalIndexes(text, from) : [...text.matchAll(pattern)].map((match) => match.index);
|
|
1040
1288
|
const found = linesOf(text, indexes);
|
|
1289
|
+
matched += indexes.length;
|
|
1041
1290
|
const expected = pair.count ?? 1;
|
|
1042
1291
|
if (pair.all === true ? indexes.length === 0 : indexes.length !== expected) {
|
|
1043
1292
|
const wanted = pair.all === true ? "at least 1" : String(expected);
|
|
@@ -1050,12 +1299,48 @@ function applyPairs(original, pairs) {
|
|
|
1050
1299
|
lines.push(...found);
|
|
1051
1300
|
text = pattern === undefined ? text.split(from).join(to) : text.replace(pattern, bracedGroups(to));
|
|
1052
1301
|
}
|
|
1053
|
-
return { text, lines, problems };
|
|
1302
|
+
return { text, lines, problems, matched };
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
// src/walk.ts
|
|
1306
|
+
import { closeSync, existsSync as existsSync4, openSync, readdirSync, readSync } from "fs";
|
|
1307
|
+
import { join as join7 } from "path";
|
|
1308
|
+
var SNIFF_BYTES = 8000;
|
|
1309
|
+
function isBinary(path) {
|
|
1310
|
+
try {
|
|
1311
|
+
const fd = openSync(path, "r");
|
|
1312
|
+
try {
|
|
1313
|
+
const buffer = Buffer.alloc(SNIFF_BYTES);
|
|
1314
|
+
return buffer.subarray(0, readSync(fd, buffer, 0, SNIFF_BYTES, 0)).includes(0);
|
|
1315
|
+
} finally {
|
|
1316
|
+
closeSync(fd);
|
|
1317
|
+
}
|
|
1318
|
+
} catch {
|
|
1319
|
+
return true;
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
function walk(dir, found, ignored) {
|
|
1323
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
1324
|
+
if (entry.name.startsWith(".") || ignored.has(entry.name))
|
|
1325
|
+
continue;
|
|
1326
|
+
if (entry.isDirectory())
|
|
1327
|
+
walk(join7(dir, entry.name), found, ignored);
|
|
1328
|
+
else if (entry.isFile())
|
|
1329
|
+
found.push(join7(dir, entry.name));
|
|
1330
|
+
}
|
|
1331
|
+
return found;
|
|
1332
|
+
}
|
|
1333
|
+
async function filesIn(dir) {
|
|
1334
|
+
const listed = await runCommand(["git", "--literal-pathspecs", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", dir]);
|
|
1335
|
+
const paths = listed.code === 0 ? [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync4(path)) : walk(dir, [], ignoredFolders());
|
|
1336
|
+
return paths.filter((path) => !isBinary(path)).sort();
|
|
1054
1337
|
}
|
|
1055
1338
|
|
|
1056
1339
|
// src/cli.ts
|
|
1057
1340
|
var USAGE = `sub [options] <file>...: replaces text in files, writing nothing unless every replacement matches as often as expected
|
|
1058
1341
|
|
|
1342
|
+
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.
|
|
1343
|
+
|
|
1059
1344
|
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
1345
|
|
|
1061
1346
|
sub src/a.php <<'EOF'
|
|
@@ -1066,38 +1351,43 @@ new lines
|
|
|
1066
1351
|
>>>>>>> REPLACE
|
|
1067
1352
|
EOF
|
|
1068
1353
|
|
|
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.`;
|
|
1354
|
+
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.`;
|
|
1355
|
+
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
1356
|
var OPTIONS = {
|
|
1073
1357
|
from: { type: "string", short: "f", description: "text to find, taken literally" },
|
|
1074
1358
|
to: { type: "string", short: "t", description: "text to put in its place, empty to delete it" },
|
|
1075
1359
|
count: { type: "string", short: "n", description: "matches expected in each file (default 1)" },
|
|
1076
1360
|
all: { type: "boolean", short: "a", description: "replace every match, expecting at least one in each file" },
|
|
1077
|
-
|
|
1078
|
-
|
|
1361
|
+
"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" },
|
|
1362
|
+
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" },
|
|
1363
|
+
"ignore-case": { type: "boolean", short: "i", description: "with --regex, match without regard to case" },
|
|
1364
|
+
dotall: { type: "boolean", short: "s", description: "with --regex, let . match a newline too" },
|
|
1365
|
+
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
1366
|
diff: { type: "boolean", short: "d", description: "print each file's unified diff" },
|
|
1080
1367
|
"dry-run": { type: "boolean", description: "show what would change without writing" },
|
|
1081
1368
|
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")
|
|
1369
|
+
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
1370
|
};
|
|
1084
|
-
var PAIR_KEYS = ["from", "to", "count", "all", "regex"];
|
|
1371
|
+
var PAIR_KEYS = ["from", "to", "count", "all", "regex", "ignoreCase", "dotAll"];
|
|
1085
1372
|
function checkPattern(pair, label) {
|
|
1086
1373
|
if (pair.from === "")
|
|
1087
1374
|
fail(`${label}--from is empty`);
|
|
1088
1375
|
if (pair.regex !== true)
|
|
1089
1376
|
return;
|
|
1090
1377
|
try {
|
|
1091
|
-
compile(pair.from);
|
|
1378
|
+
compile(pair.from, pair);
|
|
1092
1379
|
} catch (error) {
|
|
1093
1380
|
fail(`${label}--from is no valid regular expression: ${error instanceof Error ? error.message : String(error)}`);
|
|
1094
1381
|
}
|
|
1095
1382
|
}
|
|
1383
|
+
function isFlag(value) {
|
|
1384
|
+
return value === undefined || typeof value === "boolean";
|
|
1385
|
+
}
|
|
1096
1386
|
function pairFrom(item, i, defaults) {
|
|
1097
1387
|
const label = `pair ${i + 1}: `;
|
|
1098
1388
|
if (typeof item !== "object" || item === null || Array.isArray(item))
|
|
1099
1389
|
fail(`${label}give an object {from, to}`);
|
|
1100
|
-
const { from, to, count, all, regex, ...rest } = item;
|
|
1390
|
+
const { from, to, count, all, regex, ignoreCase, dotAll, ...rest } = item;
|
|
1101
1391
|
const unknown = Object.keys(rest);
|
|
1102
1392
|
if (unknown.length > 0)
|
|
1103
1393
|
fail(`${label}unknown ${K("key", unknown.length)} ${unknown.join(", ")}, known: ${PAIR_KEYS.join(", ")}`);
|
|
@@ -1105,9 +1395,11 @@ function pairFrom(item, i, defaults) {
|
|
|
1105
1395
|
fail(`${label}from and to must both be strings`);
|
|
1106
1396
|
if (count !== undefined && (typeof count !== "number" || !Number.isInteger(count) || count < 1))
|
|
1107
1397
|
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 };
|
|
1398
|
+
if (!isFlag(all) || !isFlag(regex) || !isFlag(ignoreCase) || !isFlag(dotAll))
|
|
1399
|
+
fail(`${label}all, regex, ignoreCase and dotAll take true or false`);
|
|
1400
|
+
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 };
|
|
1401
|
+
if ((pair.ignoreCase === true || pair.dotAll === true) && pair.regex !== true)
|
|
1402
|
+
fail(`${label}ignoreCase and dotAll need regex`);
|
|
1111
1403
|
checkPattern(pair, label);
|
|
1112
1404
|
return pair;
|
|
1113
1405
|
}
|
|
@@ -1126,7 +1418,7 @@ async function readPairs(path, defaults) {
|
|
|
1126
1418
|
}
|
|
1127
1419
|
function writable(path) {
|
|
1128
1420
|
try {
|
|
1129
|
-
accessSync(path,
|
|
1421
|
+
accessSync(path, constants2.W_OK);
|
|
1130
1422
|
return true;
|
|
1131
1423
|
} catch {
|
|
1132
1424
|
return false;
|
|
@@ -1135,7 +1427,7 @@ function writable(path) {
|
|
|
1135
1427
|
var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
1136
1428
|
function readUtf8(path) {
|
|
1137
1429
|
try {
|
|
1138
|
-
return UTF8.decode(
|
|
1430
|
+
return UTF8.decode(readFileSync5(path));
|
|
1139
1431
|
} catch {
|
|
1140
1432
|
return;
|
|
1141
1433
|
}
|
|
@@ -1158,7 +1450,7 @@ function dedupe(paths) {
|
|
|
1158
1450
|
}
|
|
1159
1451
|
function writeAtomic(path, text) {
|
|
1160
1452
|
const target = realpathSync3(path);
|
|
1161
|
-
const temp = `${target}.sub-${
|
|
1453
|
+
const temp = `${target}.sub-${process17.pid}`;
|
|
1162
1454
|
try {
|
|
1163
1455
|
writeFileSync2(temp, text);
|
|
1164
1456
|
chmodSync(temp, (statSync2(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
|
|
@@ -1170,30 +1462,30 @@ function writeAtomic(path, text) {
|
|
|
1170
1462
|
}
|
|
1171
1463
|
var STDIN_SILENCE_MS = 3000;
|
|
1172
1464
|
async function blocksOnStdin(files) {
|
|
1173
|
-
const extra = files.slice(1).filter((path) => !
|
|
1465
|
+
const extra = files.slice(1).filter((path) => !existsSync5(path));
|
|
1174
1466
|
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
1467
|
|
|
1176
1468
|
`;
|
|
1177
1469
|
const hint = `${strings}give --from and --to, or pipe SEARCH/REPLACE blocks on stdin from a heredoc
|
|
1178
1470
|
|
|
1179
1471
|
${USAGE}`;
|
|
1180
|
-
if (
|
|
1472
|
+
if (process17.stdin.isTTY)
|
|
1181
1473
|
fail(hint);
|
|
1182
1474
|
return new Promise((resolve) => {
|
|
1183
1475
|
const chunks = [];
|
|
1184
1476
|
const timer = setTimeout(() => {
|
|
1185
1477
|
console.error(`error: sub: ${hint}`);
|
|
1186
|
-
|
|
1478
|
+
process17.exit(2);
|
|
1187
1479
|
}, STDIN_SILENCE_MS);
|
|
1188
|
-
|
|
1480
|
+
process17.stdin.on("data", (chunk) => {
|
|
1189
1481
|
clearTimeout(timer);
|
|
1190
1482
|
chunks.push(chunk);
|
|
1191
1483
|
});
|
|
1192
|
-
|
|
1484
|
+
process17.stdin.on("end", () => {
|
|
1193
1485
|
clearTimeout(timer);
|
|
1194
1486
|
if (chunks.length === 0 && extra.length > 0) {
|
|
1195
1487
|
console.error(`error: sub: ${hint}`);
|
|
1196
|
-
|
|
1488
|
+
process17.exit(2);
|
|
1197
1489
|
}
|
|
1198
1490
|
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
1199
1491
|
});
|
|
@@ -1217,7 +1509,7 @@ ${USAGE}`);
|
|
|
1217
1509
|
fail(`give --from and --to (--to '' deletes), or --pairs
|
|
1218
1510
|
|
|
1219
1511
|
${USAGE}`);
|
|
1220
|
-
pairs = [{ from: values.from, to: values.to, count: defaults.count ?? 1, all: defaults.all, regex: defaults.regex }];
|
|
1512
|
+
pairs = [{ from: values.from, to: values.to, count: defaults.count ?? 1, all: defaults.all, regex: defaults.regex, ignoreCase: defaults.ignoreCase, dotAll: defaults.dotAll }];
|
|
1221
1513
|
checkPattern(pairs[0], "");
|
|
1222
1514
|
}
|
|
1223
1515
|
for (const path of files)
|
|
@@ -1228,7 +1520,7 @@ ${USAGE}`);
|
|
|
1228
1520
|
if (typeof blocks === "string")
|
|
1229
1521
|
fail(`blocks: ${blocks}`);
|
|
1230
1522
|
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 };
|
|
1523
|
+
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
1524
|
const named = block.file === undefined ? undefined : normalize(block.file);
|
|
1233
1525
|
const targets = named === undefined ? files : [spellings.get(canonical(named)) ?? named];
|
|
1234
1526
|
if (named !== undefined && !spellings.has(canonical(named)))
|
|
@@ -1246,37 +1538,59 @@ ${USAGE}`);
|
|
|
1246
1538
|
return edits;
|
|
1247
1539
|
}
|
|
1248
1540
|
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"]] });
|
|
1541
|
+
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
1542
|
const { values, positionals } = parsed;
|
|
1251
|
-
const
|
|
1543
|
+
const walked = new Set;
|
|
1544
|
+
const given = await Promise.all(positionals.map(async (path) => {
|
|
1545
|
+
if (statSync2(path, { throwIfNoEntry: false })?.isDirectory() !== true)
|
|
1546
|
+
return [normalize(path)];
|
|
1547
|
+
const inside = (await filesIn(path)).map(normalize);
|
|
1548
|
+
for (const file of inside)
|
|
1549
|
+
walked.add(file);
|
|
1550
|
+
return inside;
|
|
1551
|
+
}));
|
|
1552
|
+
const files = dedupe(given.flat());
|
|
1252
1553
|
if (values.count !== undefined && values.all === true)
|
|
1253
1554
|
fail("--count and --all exclude each other");
|
|
1254
|
-
|
|
1555
|
+
if (values["skip-missing"] === true && values.all !== true)
|
|
1556
|
+
fail("--skip-missing needs --all");
|
|
1557
|
+
if ((values["ignore-case"] === true || values.dotall === true) && values.regex !== true)
|
|
1558
|
+
fail("--ignore-case and --dotall need --regex");
|
|
1559
|
+
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
1560
|
const edits = await plan(values, files, defaults);
|
|
1256
1561
|
const changes = [];
|
|
1257
1562
|
const problems = [];
|
|
1563
|
+
const skipped = [];
|
|
1258
1564
|
for (const [path, pairs] of edits) {
|
|
1259
|
-
if (!
|
|
1565
|
+
if (!existsSync5(path)) {
|
|
1260
1566
|
problems.push({ path, problem: "no such file" });
|
|
1261
1567
|
continue;
|
|
1262
1568
|
}
|
|
1263
1569
|
const before = readUtf8(path);
|
|
1570
|
+
if (before === undefined && walked.has(path))
|
|
1571
|
+
continue;
|
|
1264
1572
|
if (before === undefined) {
|
|
1265
1573
|
problems.push({ path, problem: "not valid UTF-8, left alone" });
|
|
1266
1574
|
continue;
|
|
1267
1575
|
}
|
|
1268
1576
|
const applied = applyPairs(before, pairs);
|
|
1577
|
+
if ((values["skip-missing"] === true || walked.has(path)) && applied.matched === 0) {
|
|
1578
|
+
skipped.push(path);
|
|
1579
|
+
continue;
|
|
1580
|
+
}
|
|
1269
1581
|
problems.push(...applied.problems.map((problem) => ({ path, problem })));
|
|
1270
1582
|
if (applied.problems.length === 0 && values["dry-run"] !== true && !writable(path))
|
|
1271
1583
|
problems.push({ path, problem: "not writable" });
|
|
1272
1584
|
changes.push({ path, before, after: applied.text, lines: applied.lines });
|
|
1273
1585
|
}
|
|
1274
1586
|
const json = values.json === true;
|
|
1587
|
+
if (skipped.length > 0 && changes.length === 0 && problems.length === 0)
|
|
1588
|
+
problems.push({ path: skipped.join(", "), problem: "no match in any file" });
|
|
1275
1589
|
if (problems.length > 0) {
|
|
1276
1590
|
if (json)
|
|
1277
1591
|
console.error(JSON.stringify({ error: "nothing written", failures: problems }));
|
|
1278
1592
|
else
|
|
1279
|
-
console.error(`${role("problem",
|
|
1593
|
+
console.error(`${role("problem", process17.stderr)("sub: nothing written")}
|
|
1280
1594
|
${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
|
|
1281
1595
|
`)}`);
|
|
1282
1596
|
return 1;
|
|
@@ -1285,7 +1599,7 @@ ${problems.map(({ path, problem }) => `${path}: ${problem}`).join(`
|
|
|
1285
1599
|
for (const change of changes)
|
|
1286
1600
|
change.diff = await diffTexts(change.path, change.before, change.after);
|
|
1287
1601
|
} catch (error) {
|
|
1288
|
-
console.error(`${role("problem",
|
|
1602
|
+
console.error(`${role("problem", process17.stderr)("sub: nothing written")}
|
|
1289
1603
|
${error instanceof Error ? error.message : String(error)}`);
|
|
1290
1604
|
return 1;
|
|
1291
1605
|
}
|
|
@@ -1300,14 +1614,16 @@ ${error instanceof Error ? error.message : String(error)}`);
|
|
|
1300
1614
|
continue;
|
|
1301
1615
|
}
|
|
1302
1616
|
if (values.quiet !== true)
|
|
1303
|
-
console.log(`${role("path",
|
|
1617
|
+
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
1618
|
if (values.diff === true && diff.unified !== "")
|
|
1305
|
-
|
|
1619
|
+
process17.stdout.write(diff.unified);
|
|
1306
1620
|
}
|
|
1307
1621
|
if (json)
|
|
1308
|
-
printJson({ dryRun: values["dry-run"] === true, files: done });
|
|
1309
|
-
else if (values
|
|
1622
|
+
printJson({ dryRun: values["dry-run"] === true, files: done, ...values["skip-missing"] === true ? { skipped } : {} });
|
|
1623
|
+
else if (values.quiet !== true && skipped.length > 0)
|
|
1624
|
+
console.log(`skipped ${go(skipped.length, "file")} with no match: ${skipped.join(", ")}`);
|
|
1625
|
+
if (!json && values["dry-run"] === true && values.quiet !== true)
|
|
1310
1626
|
console.log("dry run: nothing written");
|
|
1311
1627
|
return 0;
|
|
1312
1628
|
}
|
|
1313
|
-
|
|
1629
|
+
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.1",
|
|
5
5
|
"description": "sub: text replaced in files for Claude Code, written only when every replacement matches as often as expected.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -39,6 +39,6 @@
|
|
|
39
39
|
"@kaynooo/utils": "3.0.0"
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
|
-
"@kaynooo/cli-kit": "0.
|
|
42
|
+
"@kaynooo/cli-kit": "0.41.0"
|
|
43
43
|
}
|
|
44
44
|
}
|