@kaynooo/cli-edit 0.4.0 → 0.4.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 +272 -101
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -4,16 +4,16 @@
|
|
|
4
4
|
// src/cli.ts
|
|
5
5
|
import { accessSync, chmodSync, constants, existsSync, readFileSync, realpathSync, renameSync, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
|
|
6
6
|
import { normalize, resolve } from "path";
|
|
7
|
-
import
|
|
7
|
+
import process8 from "process";
|
|
8
8
|
|
|
9
9
|
// ../kit/src/args.ts
|
|
10
|
-
import
|
|
10
|
+
import process4 from "process";
|
|
11
11
|
import { parseArgs } from "util";
|
|
12
12
|
|
|
13
13
|
// ../kit/src/style.ts
|
|
14
14
|
import process from "process";
|
|
15
15
|
|
|
16
|
-
// ../../node_modules/.bun/@kaynooo+utils@2.31.
|
|
16
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
17
17
|
function x(s) {
|
|
18
18
|
let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
|
|
19
19
|
if (!/^[a-f0-9]+$/.test(r))
|
|
@@ -233,7 +233,7 @@ class e {
|
|
|
233
233
|
}
|
|
234
234
|
}
|
|
235
235
|
|
|
236
|
-
// ../../node_modules/.bun/@kaynooo+utils@2.31.
|
|
236
|
+
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
|
|
237
237
|
var r = 39;
|
|
238
238
|
var o = 49;
|
|
239
239
|
var f2 = "\x1B[";
|
|
@@ -297,6 +297,55 @@ function upTo(text, separator) {
|
|
|
297
297
|
}
|
|
298
298
|
var ESCAPE = String.fromCharCode(27);
|
|
299
299
|
|
|
300
|
+
// ../kit/src/help.ts
|
|
301
|
+
import process2 from "process";
|
|
302
|
+
var OPTIONAL = /\[[^\]]+\]/g;
|
|
303
|
+
var USAGE_PREFIX = /^usage:\s*/i;
|
|
304
|
+
var FULL_STOP = /\.$/;
|
|
305
|
+
function usageLine(usage, colors = paint(process2.stdout)) {
|
|
306
|
+
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
307
|
+
}
|
|
308
|
+
function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
|
|
309
|
+
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
310
|
+
`);
|
|
311
|
+
}
|
|
312
|
+
function replacesRows(replaces, colors = paint(process2.stdout)) {
|
|
313
|
+
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
314
|
+
}
|
|
315
|
+
function wantsHelpJson(env = process2.env) {
|
|
316
|
+
return env.KIT_HELP === "json";
|
|
317
|
+
}
|
|
318
|
+
function description(usage, { examples = [], replaces } = {}) {
|
|
319
|
+
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
320
|
+
`);
|
|
321
|
+
const first = lines[0];
|
|
322
|
+
const colon = first.indexOf(": ");
|
|
323
|
+
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
324
|
+
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
325
|
+
return {
|
|
326
|
+
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
327
|
+
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
328
|
+
...replaces === undefined ? {} : { replaces },
|
|
329
|
+
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
function exampleRows(examples, colors = paint(process2.stdout)) {
|
|
333
|
+
if (examples.length === 0)
|
|
334
|
+
return [];
|
|
335
|
+
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
336
|
+
}
|
|
337
|
+
function optionRows(options, colors = paint(process2.stdout)) {
|
|
338
|
+
const rows = Object.entries(options).map(([name, option]) => {
|
|
339
|
+
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
340
|
+
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
341
|
+
const placeholder = option.optional === undefined ? named : `[${named}]`;
|
|
342
|
+
const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
|
|
343
|
+
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
|
|
344
|
+
});
|
|
345
|
+
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
346
|
+
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
347
|
+
}
|
|
348
|
+
|
|
300
349
|
// ../kit/src/text.ts
|
|
301
350
|
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
|
|
302
351
|
function distance(a, b) {
|
|
@@ -316,8 +365,31 @@ function closest(name, names) {
|
|
|
316
365
|
const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
|
|
317
366
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
318
367
|
}
|
|
368
|
+
// ../kit/src/input.ts
|
|
369
|
+
import process3 from "process";
|
|
370
|
+
var WHOLE = /^\d+$/;
|
|
371
|
+
function wholeNumber(value, name, fallback, min = 1) {
|
|
372
|
+
if (value === undefined)
|
|
373
|
+
return fallback;
|
|
374
|
+
const number = Number(value);
|
|
375
|
+
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
376
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
377
|
+
return number;
|
|
378
|
+
}
|
|
379
|
+
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
380
|
+
if (path === "-") {
|
|
381
|
+
if (process3.stdin.isTTY)
|
|
382
|
+
fail(noStdin);
|
|
383
|
+
return Bun.stdin.text();
|
|
384
|
+
}
|
|
385
|
+
const file = Bun.file(path);
|
|
386
|
+
if (!await file.exists())
|
|
387
|
+
fail(`no file ${path}`);
|
|
388
|
+
return file.text();
|
|
389
|
+
}
|
|
319
390
|
|
|
320
391
|
// ../kit/src/args.ts
|
|
392
|
+
var DASHES = /^-+/;
|
|
321
393
|
class Exit extends Error {
|
|
322
394
|
code;
|
|
323
395
|
hint;
|
|
@@ -348,61 +420,20 @@ class HelpShown extends Exit {
|
|
|
348
420
|
|
|
349
421
|
class Completing {
|
|
350
422
|
options;
|
|
351
|
-
|
|
423
|
+
positionals;
|
|
424
|
+
candidates;
|
|
425
|
+
constructor(options, positionals = [], candidates = {}) {
|
|
352
426
|
this.options = options;
|
|
427
|
+
this.positionals = positionals;
|
|
428
|
+
this.candidates = candidates;
|
|
353
429
|
}
|
|
354
430
|
}
|
|
355
431
|
var completion = { active: false };
|
|
356
|
-
var OPTIONAL = /\[[^\]]+\]/g;
|
|
357
|
-
var USAGE_PREFIX = /^usage:\s*/i;
|
|
358
|
-
var FULL_STOP = /\.$/;
|
|
359
|
-
var DASHES = /^-+/;
|
|
360
|
-
function usageLine(usage, colors = paint(process2.stdout)) {
|
|
361
|
-
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
362
|
-
}
|
|
363
|
-
function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
|
|
364
|
-
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
365
|
-
`);
|
|
366
|
-
}
|
|
367
|
-
function replacesRows(replaces, colors = paint(process2.stdout)) {
|
|
368
|
-
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
369
|
-
}
|
|
370
|
-
function wantsHelpJson(env = process2.env) {
|
|
371
|
-
return env.KIT_HELP === "json";
|
|
372
|
-
}
|
|
373
|
-
function description(usage, { examples = [], replaces } = {}) {
|
|
374
|
-
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
375
|
-
`);
|
|
376
|
-
const first = lines[0];
|
|
377
|
-
const colon = first.indexOf(": ");
|
|
378
|
-
const prose = lines[lines.indexOf("") + 1] ?? "";
|
|
379
|
-
const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
|
|
380
|
-
return {
|
|
381
|
-
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
382
|
-
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
383
|
-
...replaces === undefined ? {} : { replaces },
|
|
384
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
385
|
-
};
|
|
386
|
-
}
|
|
387
|
-
function exampleRows(examples, colors = paint(process2.stdout)) {
|
|
388
|
-
if (examples.length === 0)
|
|
389
|
-
return [];
|
|
390
|
-
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
391
|
-
}
|
|
392
|
-
function optionRows(options, colors = paint(process2.stdout)) {
|
|
393
|
-
const rows = Object.entries(options).map(([name, option]) => {
|
|
394
|
-
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
395
|
-
const value = option.type === "string" ? ` ${colors.dim("<value>")}` : "";
|
|
396
|
-
return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? " <value>".length : 0), description: option.description ?? "" };
|
|
397
|
-
});
|
|
398
|
-
const width = Math.max(0, ...rows.map((row) => row.width));
|
|
399
|
-
return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
|
|
400
|
-
}
|
|
401
432
|
var OUTPUT_OPTIONS = {
|
|
402
433
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
403
434
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
404
435
|
};
|
|
405
|
-
function applyOutput(color, plain, env =
|
|
436
|
+
function applyOutput(color, plain, env = process4.env) {
|
|
406
437
|
const when = plain === true ? "never" : color ?? "auto";
|
|
407
438
|
if (when === "auto")
|
|
408
439
|
return;
|
|
@@ -419,14 +450,13 @@ function applyOutput(color, plain, env = process2.env) {
|
|
|
419
450
|
function parse(args, usage, options, settings = {}) {
|
|
420
451
|
const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
|
|
421
452
|
const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
|
|
453
|
+
const listing = listed(all, settings.allowNegative === true);
|
|
422
454
|
if (completion.active)
|
|
423
|
-
throw new Completing(
|
|
424
|
-
const
|
|
425
|
-
const own = separator === -1 ? args : args.slice(0, separator);
|
|
426
|
-
const rest = separator === -1 ? undefined : args.slice(separator + 1);
|
|
455
|
+
throw new Completing(listing, settings.positionals, settings.candidates);
|
|
456
|
+
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
427
457
|
let parsed;
|
|
428
458
|
try {
|
|
429
|
-
parsed = parseArgs({ args: joinDashValues(own, all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
459
|
+
parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
|
|
430
460
|
} catch (error) {
|
|
431
461
|
const message = parseError(error);
|
|
432
462
|
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
@@ -434,12 +464,84 @@ function parse(args, usage, options, settings = {}) {
|
|
|
434
464
|
const values = parsed.values;
|
|
435
465
|
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
436
466
|
if (values.help === true) {
|
|
437
|
-
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage,
|
|
467
|
+
console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
|
|
438
468
|
throw new HelpShown;
|
|
439
469
|
}
|
|
470
|
+
checkChoices(parsed.values, all);
|
|
471
|
+
checkConflicts(parsed.values, all);
|
|
440
472
|
if (settings.positionals !== undefined)
|
|
441
473
|
checkPositionals(parsed.positionals, settings.positionals);
|
|
442
|
-
return { ...parsed, positionals: parsed.positionals, rest };
|
|
474
|
+
return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
|
|
475
|
+
}
|
|
476
|
+
function splitRest(args, passes) {
|
|
477
|
+
const separator = passes ? args.indexOf("--") : -1;
|
|
478
|
+
return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
|
|
479
|
+
}
|
|
480
|
+
function splitTrailing(args, options, count) {
|
|
481
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
482
|
+
let seen = 0;
|
|
483
|
+
if (count === 0)
|
|
484
|
+
return { own: args, rest: undefined };
|
|
485
|
+
for (let at = 0;at < args.length; at++) {
|
|
486
|
+
const word = args[at];
|
|
487
|
+
if (word === "--")
|
|
488
|
+
break;
|
|
489
|
+
if (word.startsWith("-")) {
|
|
490
|
+
if (takesValue(word))
|
|
491
|
+
at++;
|
|
492
|
+
continue;
|
|
493
|
+
}
|
|
494
|
+
seen++;
|
|
495
|
+
if (seen === count)
|
|
496
|
+
return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
|
|
497
|
+
}
|
|
498
|
+
return { own: args, rest: undefined };
|
|
499
|
+
}
|
|
500
|
+
function listed(options, allowNegative) {
|
|
501
|
+
if (!allowNegative)
|
|
502
|
+
return options;
|
|
503
|
+
return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
|
|
504
|
+
if (option.type !== "boolean" || option.negative === undefined)
|
|
505
|
+
return [[name, option]];
|
|
506
|
+
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
507
|
+
}));
|
|
508
|
+
}
|
|
509
|
+
function withBare(args, options) {
|
|
510
|
+
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
511
|
+
if (bare.size === 0)
|
|
512
|
+
return args;
|
|
513
|
+
const separator = args.indexOf("--");
|
|
514
|
+
const own = separator === -1 ? args : args.slice(0, separator);
|
|
515
|
+
return [...own.flatMap((arg, index) => {
|
|
516
|
+
const optional = bare.get(arg);
|
|
517
|
+
const next = own[index + 1];
|
|
518
|
+
const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
|
|
519
|
+
return optional === undefined || value ? [arg] : [arg, optional.bare];
|
|
520
|
+
}), ...separator === -1 ? [] : args.slice(separator)];
|
|
521
|
+
}
|
|
522
|
+
function checkConflicts(values, options) {
|
|
523
|
+
const given = (name) => values[name] !== undefined && values[name] !== false;
|
|
524
|
+
for (const [name, { conflicts = [] }] of Object.entries(options)) {
|
|
525
|
+
const other = given(name) ? conflicts.find(given) : undefined;
|
|
526
|
+
if (other !== undefined)
|
|
527
|
+
badUsage(`--${name} cannot be used with --${other}`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
function checkChoices(values, options) {
|
|
531
|
+
for (const [name, option] of Object.entries(options)) {
|
|
532
|
+
if (option.choices === undefined)
|
|
533
|
+
continue;
|
|
534
|
+
const given = values[name];
|
|
535
|
+
for (const value of Array.isArray(given) ? given : [given]) {
|
|
536
|
+
if (typeof value === "string")
|
|
537
|
+
oneOf(value, name, option.choices);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
function oneOf(value, name, choices) {
|
|
542
|
+
if (!choices.includes(value))
|
|
543
|
+
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
|
|
544
|
+
return value;
|
|
443
545
|
}
|
|
444
546
|
function checkPositionals(given, names) {
|
|
445
547
|
const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
|
|
@@ -488,41 +590,73 @@ function nearestOption(message, options, allowNegative) {
|
|
|
488
590
|
const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
|
|
489
591
|
return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
|
|
490
592
|
}
|
|
491
|
-
var WHOLE = /^\d+$/;
|
|
492
|
-
function wholeNumber(value, name, fallback, min = 1) {
|
|
493
|
-
if (value === undefined)
|
|
494
|
-
return fallback;
|
|
495
|
-
const number = Number(value);
|
|
496
|
-
if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
|
|
497
|
-
badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
|
|
498
|
-
return number;
|
|
499
|
-
}
|
|
500
|
-
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
501
|
-
if (path === "-") {
|
|
502
|
-
if (process2.stdin.isTTY)
|
|
503
|
-
fail(noStdin);
|
|
504
|
-
return Bun.stdin.text();
|
|
505
|
-
}
|
|
506
|
-
const file = Bun.file(path);
|
|
507
|
-
if (!await file.exists())
|
|
508
|
-
fail(`no file ${path}`);
|
|
509
|
-
return file.text();
|
|
510
|
-
}
|
|
511
593
|
// ../kit/src/progress.ts
|
|
512
594
|
var ESC = String.fromCharCode(27);
|
|
513
595
|
var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
|
|
514
596
|
var RESET_STYLE = `${ESC}[0m`;
|
|
515
597
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
516
598
|
// ../kit/src/cli.ts
|
|
517
|
-
import
|
|
599
|
+
import process6 from "process";
|
|
600
|
+
|
|
601
|
+
// ../kit/src/usage.ts
|
|
602
|
+
import { appendFileSync, mkdirSync } from "fs";
|
|
603
|
+
import { homedir } from "os";
|
|
604
|
+
import { dirname, isAbsolute, join } from "path";
|
|
605
|
+
import process5 from "process";
|
|
606
|
+
|
|
607
|
+
// ../kit/src/logs.ts
|
|
608
|
+
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
609
|
+
var CLI_FOLDER = "kaynooo-cli";
|
|
610
|
+
|
|
611
|
+
// ../kit/src/usage.ts
|
|
612
|
+
var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
|
|
613
|
+
var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
|
|
614
|
+
var LONGEST_NAME = 40;
|
|
615
|
+
var usageError;
|
|
616
|
+
function noteUsageError(message) {
|
|
617
|
+
usageError = message;
|
|
618
|
+
}
|
|
619
|
+
function stateHome(env = process5.env) {
|
|
620
|
+
const dir = env.XDG_STATE_HOME;
|
|
621
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
622
|
+
}
|
|
623
|
+
function usagePath(env = process5.env) {
|
|
624
|
+
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
625
|
+
}
|
|
626
|
+
function usageRecorded(env = process5.env) {
|
|
627
|
+
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
628
|
+
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
629
|
+
}
|
|
630
|
+
function flagNames(argv) {
|
|
631
|
+
const end = argv.indexOf("--");
|
|
632
|
+
const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
|
|
633
|
+
return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
|
|
634
|
+
}
|
|
635
|
+
function usageEntry(bin, command, argv, code, now = new Date) {
|
|
636
|
+
const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
|
|
637
|
+
usageError = undefined;
|
|
638
|
+
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
639
|
+
}
|
|
640
|
+
function recordUsage(entry, env = process5.env) {
|
|
641
|
+
if (!usageRecorded(env))
|
|
642
|
+
return;
|
|
643
|
+
try {
|
|
644
|
+
const path = usagePath(env);
|
|
645
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
646
|
+
appendFileSync(path, `${JSON.stringify(entry)}
|
|
647
|
+
`, { mode: 384 });
|
|
648
|
+
} catch {}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// ../kit/src/cli.ts
|
|
518
652
|
var LEVEL_OPTIONS = {
|
|
519
653
|
...OUTPUT_OPTIONS,
|
|
520
654
|
help: { type: "boolean", short: "h", description: "show this help" }
|
|
521
655
|
};
|
|
522
656
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
523
657
|
function printError(prefix, message, hint, cause) {
|
|
524
|
-
const colors = paint(
|
|
525
|
-
const styled = takesControlCodes(
|
|
658
|
+
const colors = paint(process6.stderr);
|
|
659
|
+
const styled = takesControlCodes(process6.stderr);
|
|
526
660
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
527
661
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
528
662
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -541,49 +675,86 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
541
675
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
542
676
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
543
677
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
678
|
+
if (error instanceof UsageError)
|
|
679
|
+
noteUsageError(error.message);
|
|
544
680
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
545
681
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
546
682
|
return error instanceof Exit ? error.code : 1;
|
|
547
683
|
}
|
|
548
684
|
var COMPLETE = "__complete";
|
|
549
685
|
var FILES = "__files__";
|
|
550
|
-
async function
|
|
686
|
+
async function completingOf(run) {
|
|
551
687
|
completion.active = true;
|
|
552
688
|
try {
|
|
553
689
|
await run([]);
|
|
554
690
|
} catch (error) {
|
|
555
691
|
if (error instanceof Completing)
|
|
556
|
-
return error
|
|
692
|
+
return error;
|
|
557
693
|
} finally {
|
|
558
694
|
completion.active = false;
|
|
559
695
|
}
|
|
560
|
-
return {};
|
|
696
|
+
return new Completing({});
|
|
697
|
+
}
|
|
698
|
+
function candidateLine(candidate) {
|
|
699
|
+
return typeof candidate === "string" ? candidate : candidate.join("\t");
|
|
700
|
+
}
|
|
701
|
+
function positionalBeingTyped(before, { options, positionals }) {
|
|
702
|
+
const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
|
|
703
|
+
let index = 0;
|
|
704
|
+
let at = 0;
|
|
705
|
+
while (at < before.length) {
|
|
706
|
+
const word = before[at];
|
|
707
|
+
if (word === "--") {
|
|
708
|
+
index += before.length - at - 1;
|
|
709
|
+
break;
|
|
710
|
+
}
|
|
711
|
+
if (!word.startsWith("-"))
|
|
712
|
+
index++;
|
|
713
|
+
else if (takesValue(word))
|
|
714
|
+
at++;
|
|
715
|
+
at++;
|
|
716
|
+
}
|
|
717
|
+
const last = positionals.at(-1);
|
|
718
|
+
if (index < positionals.length)
|
|
719
|
+
return positionals[index];
|
|
720
|
+
return last?.replace("]", "").endsWith("...") === true ? last : undefined;
|
|
561
721
|
}
|
|
562
722
|
async function leafCandidates(run, words) {
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
723
|
+
const completing = await completingOf(run);
|
|
724
|
+
if ((words.at(-1) ?? "").startsWith("-"))
|
|
725
|
+
return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
|
|
726
|
+
const flag = words.at(-2);
|
|
727
|
+
const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
|
|
728
|
+
if (option?.type === "string") {
|
|
729
|
+
const values = option.choices === undefined ? await option.candidates?.() : option.choices;
|
|
730
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
731
|
+
}
|
|
732
|
+
const name = positionalBeingTyped(words.slice(0, -1), completing);
|
|
733
|
+
const values = name === undefined ? undefined : await completing.candidates[name]?.();
|
|
734
|
+
return values === undefined ? [FILES] : values.map(candidateLine);
|
|
566
735
|
}
|
|
567
736
|
async function printCandidates(found) {
|
|
568
737
|
for (const line of await found)
|
|
569
738
|
console.log(line);
|
|
570
739
|
return 0;
|
|
571
740
|
}
|
|
572
|
-
async function runMain({ name, version, run, redact }, argv =
|
|
741
|
+
async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
|
|
573
742
|
if (argv[0] === COMPLETE)
|
|
574
743
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
575
744
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
576
745
|
console.log(version);
|
|
577
746
|
return 0;
|
|
578
747
|
}
|
|
748
|
+
let code;
|
|
579
749
|
try {
|
|
580
|
-
|
|
750
|
+
code = await run(argv);
|
|
581
751
|
} catch (error) {
|
|
582
|
-
|
|
752
|
+
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
583
753
|
}
|
|
754
|
+
if (usage !== false)
|
|
755
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
756
|
+
return code;
|
|
584
757
|
}
|
|
585
|
-
// ../kit/src/logs.ts
|
|
586
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
587
758
|
// ../kit/src/secrets.ts
|
|
588
759
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
589
760
|
// ../kit/src/sessions.ts
|
|
@@ -591,7 +762,7 @@ var {Glob } = globalThis.Bun;
|
|
|
591
762
|
var SESSION_FILES = new Glob("*.json");
|
|
592
763
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
593
764
|
// package.json
|
|
594
|
-
var version = "0.4.
|
|
765
|
+
var version = "0.4.1";
|
|
595
766
|
|
|
596
767
|
// src/blocks.ts
|
|
597
768
|
var LINE_BREAK = /\r?\n/;
|
|
@@ -648,15 +819,15 @@ function parseBlocks(text) {
|
|
|
648
819
|
// src/diff.ts
|
|
649
820
|
import { mkdtempSync, rmSync, writeFileSync } from "fs";
|
|
650
821
|
import { tmpdir } from "os";
|
|
651
|
-
import { join } from "path";
|
|
822
|
+
import { join as join2 } from "path";
|
|
652
823
|
async function diffTexts(path, before, after) {
|
|
653
|
-
const dir = mkdtempSync(
|
|
824
|
+
const dir = mkdtempSync(join2(tmpdir(), "sub-"));
|
|
654
825
|
try {
|
|
655
|
-
writeFileSync(
|
|
656
|
-
writeFileSync(
|
|
826
|
+
writeFileSync(join2(dir, "before"), before);
|
|
827
|
+
writeFileSync(join2(dir, "after"), after);
|
|
657
828
|
let child;
|
|
658
829
|
try {
|
|
659
|
-
child = Bun.spawn(["diff", "-u", "--label", `a/${path}`, "--label", `b/${path}`,
|
|
830
|
+
child = Bun.spawn(["diff", "-u", "--label", `a/${path}`, "--label", `b/${path}`, join2(dir, "before"), join2(dir, "after")], { stdout: "pipe", stderr: "pipe" });
|
|
660
831
|
} catch {
|
|
661
832
|
throw new Error("diff is not installed, which sub needs to show its changes");
|
|
662
833
|
}
|
|
@@ -860,7 +1031,7 @@ function dedupe(paths) {
|
|
|
860
1031
|
}
|
|
861
1032
|
function writeAtomic(path, text) {
|
|
862
1033
|
const target = realpathSync(path);
|
|
863
|
-
const temp = `${target}.sub-${
|
|
1034
|
+
const temp = `${target}.sub-${process8.pid}`;
|
|
864
1035
|
try {
|
|
865
1036
|
writeFileSync2(temp, text);
|
|
866
1037
|
chmodSync(temp, (statSync(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
|
|
@@ -965,10 +1136,10 @@ ${error instanceof Error ? error.message : String(error)}`);
|
|
|
965
1136
|
writeAtomic(path, after);
|
|
966
1137
|
console.log(`${path}: ${plural(lines.length, "replacement")} on line${lines.length === 1 ? "" : "s"} ${listLines(lines)}, +${diff.added} -${diff.removed}`);
|
|
967
1138
|
if (values.diff === true && diff.unified !== "")
|
|
968
|
-
|
|
1139
|
+
process8.stdout.write(diff.unified);
|
|
969
1140
|
}
|
|
970
1141
|
if (values["dry-run"] === true)
|
|
971
1142
|
console.log("dry run: nothing written");
|
|
972
1143
|
return 0;
|
|
973
1144
|
}
|
|
974
|
-
|
|
1145
|
+
process8.exitCode = await runMain({ name: "sub", version, 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.
|
|
4
|
+
"version": "0.4.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",
|
|
@@ -36,6 +36,6 @@
|
|
|
36
36
|
"sub": "$npm_execpath src/cli.ts"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
|
-
"@kaynooo/cli-kit": "0.
|
|
39
|
+
"@kaynooo/cli-kit": "0.20.0"
|
|
40
40
|
}
|
|
41
41
|
}
|