@kaynooo/cli-edit 0.6.0 → 0.8.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 +328 -66
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -2,15 +2,36 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/cli.ts
|
|
5
|
-
import { accessSync, chmodSync, constants, existsSync, readFileSync as
|
|
6
|
-
import { normalize, resolve } from "path";
|
|
7
|
-
import
|
|
5
|
+
import { accessSync, chmodSync, constants, existsSync as existsSync3, readFileSync as readFileSync3, realpathSync as realpathSync2, renameSync, rmSync as rmSync2, statSync as statSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
6
|
+
import { normalize, resolve as resolve3 } from "path";
|
|
7
|
+
import process14 from "process";
|
|
8
8
|
// ../kit/src/args.ts
|
|
9
|
-
import
|
|
9
|
+
import process10 from "process";
|
|
10
10
|
import { parseArgs } from "util";
|
|
11
11
|
|
|
12
|
-
// ../kit/src/
|
|
12
|
+
// ../kit/src/format.ts
|
|
13
|
+
import process7 from "process";
|
|
14
|
+
|
|
15
|
+
// ../kit/src/mode.ts
|
|
13
16
|
import process2 from "process";
|
|
17
|
+
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
18
|
+
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
19
|
+
function isSet(value) {
|
|
20
|
+
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
21
|
+
}
|
|
22
|
+
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
23
|
+
const chosen = env.KIT_MODE;
|
|
24
|
+
if (chosen !== undefined && MODES.has(chosen))
|
|
25
|
+
return chosen;
|
|
26
|
+
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
27
|
+
return "agent";
|
|
28
|
+
if (stream.isTTY === true)
|
|
29
|
+
return "terminal";
|
|
30
|
+
return isSet(env.CI) ? "ci" : "pipe";
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// ../kit/src/style.ts
|
|
34
|
+
import process6 from "process";
|
|
14
35
|
|
|
15
36
|
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
16
37
|
function x(s) {
|
|
@@ -273,21 +294,229 @@ function le(i = {}) {
|
|
|
273
294
|
}
|
|
274
295
|
var t = le();
|
|
275
296
|
|
|
297
|
+
// ../kit/src/theme.ts
|
|
298
|
+
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
299
|
+
import { homedir as homedir2 } from "os";
|
|
300
|
+
import { join as join3, resolve as resolve2 } from "path";
|
|
301
|
+
import process5 from "process";
|
|
302
|
+
|
|
303
|
+
// ../kit/src/config.ts
|
|
304
|
+
import { existsSync } from "fs";
|
|
305
|
+
import { dirname, join, resolve } from "path";
|
|
306
|
+
import process3 from "process";
|
|
307
|
+
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
308
|
+
const wanted = typeof names === "string" ? [names] : names;
|
|
309
|
+
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
310
|
+
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
311
|
+
if (found !== undefined)
|
|
312
|
+
return found;
|
|
313
|
+
if (stop(dir) || dirname(dir) === dir)
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// ../kit/src/user-config.ts
|
|
319
|
+
import { homedir } from "os";
|
|
320
|
+
import { join as join2 } from "path";
|
|
321
|
+
import process4 from "process";
|
|
322
|
+
function configBase(where = {}) {
|
|
323
|
+
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
324
|
+
return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
|
|
325
|
+
}
|
|
326
|
+
function userConfigPath(bin, where = {}) {
|
|
327
|
+
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// ../kit/src/theme.ts
|
|
331
|
+
var DEFAULT = {
|
|
332
|
+
colors: { accent: "cyan", id: "yellow", path: "blue", label: "dim", value: "bold", ok: "green", warn: "yellow", problem: "red", note: "dim", passed: "green", failed: "red", running: "cyan", queued: "yellow", skipped: "dim" },
|
|
333
|
+
glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501", rule: "\u2500", corner: "\u256D" },
|
|
334
|
+
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
335
|
+
bins: {}
|
|
336
|
+
};
|
|
337
|
+
var BRIGHT = { accent: "cyanBright", id: "yellowBright", path: "blueBright", label: "white", value: "bold whiteBright", ok: "greenBright", warn: "yellowBright", problem: "redBright", note: "white", passed: "greenBright", failed: "redBright", running: "cyanBright", queued: "yellowBright", skipped: "white" };
|
|
338
|
+
var MONO = { accent: "bold", id: "bold", path: "underline", label: "dim", value: "bold", ok: "bold", warn: "bold", problem: "bold", note: "dim", passed: "bold", failed: "bold", running: "bold", queued: "dim", skipped: "dim" };
|
|
339
|
+
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#", rule: "-", corner: "+" };
|
|
340
|
+
var PRESETS = {
|
|
341
|
+
default: {},
|
|
342
|
+
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
|
|
343
|
+
mono: { colors: MONO, accents: ["bold"] },
|
|
344
|
+
ascii: { glyphs: ASCII }
|
|
345
|
+
};
|
|
346
|
+
var STYLES = new Set(["bold", "dim", "italic", "underline", "inverse", "strikethrough", "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "gray", "grey", "blackBright", "redBright", "greenBright", "yellowBright", "blueBright", "magentaBright", "cyanBright", "whiteBright"]);
|
|
347
|
+
var HEX = /^#[0-9a-f]{6}$/i;
|
|
348
|
+
var CONTROL = /\p{Cc}/u;
|
|
349
|
+
var MAX_FILE_BYTES = 64 * 1024;
|
|
350
|
+
var SPACES = /\s+/;
|
|
351
|
+
function isColorSpec(spec) {
|
|
352
|
+
if (typeof spec === "number")
|
|
353
|
+
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
354
|
+
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
355
|
+
}
|
|
356
|
+
var CUBE = [0, 95, 135, 175, 215, 255];
|
|
357
|
+
function cubeLevel(channel) {
|
|
358
|
+
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
359
|
+
}
|
|
360
|
+
function nearest256(hex) {
|
|
361
|
+
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
362
|
+
const levels = rgb.map(cubeLevel);
|
|
363
|
+
const cube = levels.map((level) => CUBE[level]);
|
|
364
|
+
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
365
|
+
const greyValue = 8 + grey * 10;
|
|
366
|
+
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
367
|
+
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
368
|
+
}
|
|
369
|
+
function hasTrueColor(env) {
|
|
370
|
+
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
371
|
+
}
|
|
372
|
+
function tinted(colors, spec, env = process5.env) {
|
|
373
|
+
if (typeof spec === "number")
|
|
374
|
+
return colors.ansi256(spec);
|
|
375
|
+
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
376
|
+
if (HEX.test(token))
|
|
377
|
+
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
378
|
+
return chain[token] ?? chain;
|
|
379
|
+
}, colors);
|
|
380
|
+
}
|
|
381
|
+
function isRecord(value) {
|
|
382
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
383
|
+
}
|
|
384
|
+
function readThemeFile(path, warn) {
|
|
385
|
+
try {
|
|
386
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
387
|
+
if (stat === undefined)
|
|
388
|
+
return;
|
|
389
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
390
|
+
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
394
|
+
if (isRecord(parsed))
|
|
395
|
+
return parsed;
|
|
396
|
+
warn(`${path} is not a JSON object, theme ignored`);
|
|
397
|
+
} catch (error) {
|
|
398
|
+
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
399
|
+
}
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
function applyPreset(theme, name, warn, where) {
|
|
403
|
+
if (name === undefined)
|
|
404
|
+
return;
|
|
405
|
+
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
406
|
+
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
const preset = PRESETS[name];
|
|
410
|
+
Object.assign(theme.colors, preset.colors);
|
|
411
|
+
Object.assign(theme.glyphs, preset.glyphs);
|
|
412
|
+
if (preset.accents !== undefined)
|
|
413
|
+
theme.accents = [...preset.accents];
|
|
414
|
+
return name;
|
|
415
|
+
}
|
|
416
|
+
function applyFile(theme, file, where, warn) {
|
|
417
|
+
if (isRecord(file.colors)) {
|
|
418
|
+
for (const [key, value] of Object.entries(file.colors)) {
|
|
419
|
+
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
420
|
+
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
421
|
+
else if (!isColorSpec(value))
|
|
422
|
+
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
423
|
+
else
|
|
424
|
+
theme.colors[key] = value;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
if (isRecord(file.glyphs)) {
|
|
428
|
+
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
429
|
+
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
430
|
+
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
431
|
+
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
432
|
+
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
433
|
+
else
|
|
434
|
+
theme.glyphs[key] = value;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
438
|
+
theme.accents = [...file.accents];
|
|
439
|
+
else if (file.accents !== undefined)
|
|
440
|
+
warn(`${where}: accents must be a non-empty list of colours`);
|
|
441
|
+
if (isRecord(file.bins)) {
|
|
442
|
+
for (const [bin, value] of Object.entries(file.bins)) {
|
|
443
|
+
if (isColorSpec(value))
|
|
444
|
+
theme.bins[bin] = value;
|
|
445
|
+
else
|
|
446
|
+
warn(`${where}: bin ${bin} has no valid colour`);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
function endsWalk(home) {
|
|
451
|
+
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
452
|
+
}
|
|
453
|
+
var warned = new Set;
|
|
454
|
+
function warnOnce(message) {
|
|
455
|
+
if (warned.has(message))
|
|
456
|
+
return;
|
|
457
|
+
warned.add(message);
|
|
458
|
+
console.error(`warning: theme ${message}`);
|
|
459
|
+
}
|
|
460
|
+
function isPath(chosen) {
|
|
461
|
+
return chosen.includes("/") || chosen.endsWith(".json");
|
|
462
|
+
}
|
|
463
|
+
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
464
|
+
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
|
|
465
|
+
const sources = [];
|
|
466
|
+
const chosen = env.KIT_THEME ?? "";
|
|
467
|
+
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
468
|
+
if (isPath(chosen))
|
|
469
|
+
wanted.push(resolve2(from, chosen));
|
|
470
|
+
const files = [];
|
|
471
|
+
for (const path of wanted) {
|
|
472
|
+
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
473
|
+
if (path !== undefined && file !== undefined)
|
|
474
|
+
files.push({ path, file });
|
|
475
|
+
}
|
|
476
|
+
let preset = "default";
|
|
477
|
+
if (chosen !== "" && !isPath(chosen)) {
|
|
478
|
+
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
479
|
+
} else {
|
|
480
|
+
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
481
|
+
if (named !== undefined)
|
|
482
|
+
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
483
|
+
}
|
|
484
|
+
for (const { path, file } of files) {
|
|
485
|
+
applyFile(theme, file, path, warn);
|
|
486
|
+
sources.push(path);
|
|
487
|
+
}
|
|
488
|
+
return { theme, sources, preset };
|
|
489
|
+
}
|
|
490
|
+
var current;
|
|
491
|
+
var currentKey = "";
|
|
492
|
+
function activeTheme() {
|
|
493
|
+
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
494
|
+
if (current === undefined || key !== currentKey) {
|
|
495
|
+
current = loadTheme();
|
|
496
|
+
currentKey = key;
|
|
497
|
+
}
|
|
498
|
+
return current;
|
|
499
|
+
}
|
|
500
|
+
|
|
276
501
|
// ../kit/src/style.ts
|
|
277
|
-
function takesControlCodes(stream, env =
|
|
278
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
502
|
+
function takesControlCodes(stream, env = process6.env) {
|
|
503
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
279
504
|
}
|
|
280
|
-
function paint(stream, env =
|
|
505
|
+
function paint(stream, env = process6.env) {
|
|
281
506
|
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
282
507
|
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
508
|
+
function role(name, stream, env = process6.env) {
|
|
509
|
+
const colors = paint(stream, env);
|
|
510
|
+
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
511
|
+
}
|
|
512
|
+
var STATUS_WORDS = {
|
|
513
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
514
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
515
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
516
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
517
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
289
518
|
};
|
|
290
|
-
var STATUS_OF = new Map(Object.entries(
|
|
519
|
+
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
291
520
|
|
|
292
521
|
// ../kit/src/format.ts
|
|
293
522
|
function upTo(text, separator) {
|
|
@@ -295,32 +524,35 @@ function upTo(text, separator) {
|
|
|
295
524
|
return end === -1 ? text : text.slice(0, end);
|
|
296
525
|
}
|
|
297
526
|
var ESCAPE = String.fromCharCode(27);
|
|
527
|
+
function jsonText(value, replacer, { stream = process7.stdout, env = process7.env } = {}) {
|
|
528
|
+
return JSON.stringify(value, replacer, outputMode(stream, env) === "agent" ? undefined : 2);
|
|
529
|
+
}
|
|
298
530
|
function printJson(value) {
|
|
299
|
-
console.log(
|
|
531
|
+
console.log(jsonText(value));
|
|
300
532
|
}
|
|
301
533
|
|
|
302
534
|
// ../kit/src/help.ts
|
|
303
|
-
import
|
|
535
|
+
import process8 from "process";
|
|
304
536
|
var OPTIONAL = /\[[^\]]+\]/g;
|
|
305
537
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
306
538
|
var FULL_STOP = /\.$/;
|
|
307
|
-
function usageLine(usage, colors = paint(
|
|
539
|
+
function usageLine(usage, colors = paint(process8.stdout)) {
|
|
308
540
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
309
541
|
}
|
|
310
|
-
function helpText(usage, options, colors = paint(
|
|
542
|
+
function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
311
543
|
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
312
544
|
`);
|
|
313
545
|
}
|
|
314
|
-
function exitRows(exits, colors = paint(
|
|
546
|
+
function exitRows(exits, colors = paint(process8.stdout)) {
|
|
315
547
|
if (exits.length === 0)
|
|
316
548
|
return [];
|
|
317
549
|
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
318
550
|
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
319
551
|
}
|
|
320
|
-
function replacesRows(replaces, colors = paint(
|
|
321
|
-
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
552
|
+
function replacesRows(replaces, colors = paint(process8.stdout)) {
|
|
553
|
+
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
322
554
|
}
|
|
323
|
-
function wantsHelpJson(env =
|
|
555
|
+
function wantsHelpJson(env = process8.env) {
|
|
324
556
|
return env.KIT_HELP === "json";
|
|
325
557
|
}
|
|
326
558
|
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
@@ -339,12 +571,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
|
339
571
|
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
340
572
|
};
|
|
341
573
|
}
|
|
342
|
-
function exampleRows(examples, colors = paint(
|
|
343
|
-
if (examples.length === 0)
|
|
574
|
+
function exampleRows(examples, colors = paint(process8.stdout)) {
|
|
575
|
+
if (examples.length === 0 || outputMode() === "agent")
|
|
344
576
|
return [];
|
|
345
577
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
346
578
|
}
|
|
347
|
-
function optionRows(options, colors = paint(
|
|
579
|
+
function optionRows(options, colors = paint(process8.stdout)) {
|
|
348
580
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
349
581
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
350
582
|
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
@@ -376,7 +608,7 @@ function closest(name, names) {
|
|
|
376
608
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
377
609
|
}
|
|
378
610
|
// ../kit/src/input.ts
|
|
379
|
-
import
|
|
611
|
+
import process9 from "process";
|
|
380
612
|
var WHOLE = /^\d+$/;
|
|
381
613
|
function wholeNumber(value, name, fallback, min = 1) {
|
|
382
614
|
if (value === undefined)
|
|
@@ -388,7 +620,7 @@ function wholeNumber(value, name, fallback, min = 1) {
|
|
|
388
620
|
}
|
|
389
621
|
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
390
622
|
if (path === "-") {
|
|
391
|
-
if (
|
|
623
|
+
if (process9.stdin.isTTY)
|
|
392
624
|
fail(noStdin);
|
|
393
625
|
return Bun.stdin.text();
|
|
394
626
|
}
|
|
@@ -403,7 +635,6 @@ var DASHES = /^-+/;
|
|
|
403
635
|
function jsonOption(holds) {
|
|
404
636
|
return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
|
|
405
637
|
}
|
|
406
|
-
|
|
407
638
|
class Exit extends Error {
|
|
408
639
|
code;
|
|
409
640
|
hint;
|
|
@@ -447,7 +678,7 @@ var OUTPUT_OPTIONS = {
|
|
|
447
678
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
448
679
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
449
680
|
};
|
|
450
|
-
function applyOutput(color, plain, env =
|
|
681
|
+
function applyOutput(color, plain, env = process10.env) {
|
|
451
682
|
const when = plain === true ? "never" : color ?? "auto";
|
|
452
683
|
if (when === "auto")
|
|
453
684
|
return;
|
|
@@ -622,15 +853,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
622
853
|
var RESET_STYLE = `${ESC}[0m`;
|
|
623
854
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
624
855
|
// ../kit/src/cli.ts
|
|
625
|
-
import { readFileSync, realpathSync } from "fs";
|
|
626
|
-
import { dirname as
|
|
627
|
-
import
|
|
856
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
857
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
858
|
+
import process12 from "process";
|
|
628
859
|
|
|
629
860
|
// ../kit/src/usage.ts
|
|
630
861
|
import { appendFileSync, mkdirSync } from "fs";
|
|
631
|
-
import { homedir } from "os";
|
|
632
|
-
import { dirname, isAbsolute, join } from "path";
|
|
633
|
-
import
|
|
862
|
+
import { homedir as homedir3 } from "os";
|
|
863
|
+
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
864
|
+
import process11 from "process";
|
|
634
865
|
|
|
635
866
|
// ../kit/src/logs.ts
|
|
636
867
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -644,14 +875,14 @@ var usageError;
|
|
|
644
875
|
function noteUsageError(message) {
|
|
645
876
|
usageError = message;
|
|
646
877
|
}
|
|
647
|
-
function stateHome(env =
|
|
878
|
+
function stateHome(env = process11.env) {
|
|
648
879
|
const dir = env.XDG_STATE_HOME;
|
|
649
|
-
return dir !== undefined && isAbsolute(dir) ? dir :
|
|
880
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
650
881
|
}
|
|
651
|
-
function usagePath(env =
|
|
652
|
-
return
|
|
882
|
+
function usagePath(env = process11.env) {
|
|
883
|
+
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
653
884
|
}
|
|
654
|
-
function usageRecorded(env =
|
|
885
|
+
function usageRecorded(env = process11.env) {
|
|
655
886
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
656
887
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
657
888
|
}
|
|
@@ -665,12 +896,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
665
896
|
usageError = undefined;
|
|
666
897
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
667
898
|
}
|
|
668
|
-
function recordUsage(entry, env =
|
|
899
|
+
function recordUsage(entry, env = process11.env) {
|
|
669
900
|
if (!usageRecorded(env))
|
|
670
901
|
return;
|
|
671
902
|
try {
|
|
672
903
|
const path = usagePath(env);
|
|
673
|
-
mkdirSync(
|
|
904
|
+
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
674
905
|
appendFileSync(path, `${JSON.stringify(entry)}
|
|
675
906
|
`, { mode: 384 });
|
|
676
907
|
} catch {}
|
|
@@ -683,8 +914,8 @@ var LEVEL_OPTIONS = {
|
|
|
683
914
|
};
|
|
684
915
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
685
916
|
function printError(prefix, message, hint, cause) {
|
|
686
|
-
const colors = paint(
|
|
687
|
-
const styled = takesControlCodes(
|
|
917
|
+
const colors = paint(process12.stderr);
|
|
918
|
+
const styled = takesControlCodes(process12.stderr);
|
|
688
919
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
689
920
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
690
921
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -767,17 +998,17 @@ async function printCandidates(found) {
|
|
|
767
998
|
return 0;
|
|
768
999
|
}
|
|
769
1000
|
function packageVersion(entry = Bun.main) {
|
|
770
|
-
for (let dir =
|
|
1001
|
+
for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
|
|
771
1002
|
try {
|
|
772
|
-
const { version } = JSON.parse(
|
|
1003
|
+
const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
|
|
773
1004
|
if (typeof version === "string")
|
|
774
1005
|
return version;
|
|
775
1006
|
} catch {}
|
|
776
|
-
if (
|
|
1007
|
+
if (dirname3(dir) === dir)
|
|
777
1008
|
return "0.0.0";
|
|
778
1009
|
}
|
|
779
1010
|
}
|
|
780
|
-
async function runMain({ name, version, run, redact, usage }, argv =
|
|
1011
|
+
async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
|
|
781
1012
|
if (argv[0] === COMPLETE)
|
|
782
1013
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
783
1014
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
@@ -797,6 +1028,8 @@ async function runMain({ name, version, run, redact, usage }, argv = process7.ar
|
|
|
797
1028
|
}
|
|
798
1029
|
return code;
|
|
799
1030
|
}
|
|
1031
|
+
// ../kit/src/folders.ts
|
|
1032
|
+
var SKIPPED_FOLDERS = new Set(["node_modules", "vendor", "dist", "build", "target", "coverage", "venv", "__pycache__"]);
|
|
800
1033
|
// ../kit/src/secrets.ts
|
|
801
1034
|
var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
|
|
802
1035
|
// ../kit/src/sessions.ts
|
|
@@ -858,15 +1091,15 @@ function parseBlocks(text) {
|
|
|
858
1091
|
// src/diff.ts
|
|
859
1092
|
import { mkdtempSync, rmSync, writeFileSync } from "fs";
|
|
860
1093
|
import { tmpdir } from "os";
|
|
861
|
-
import { join as
|
|
1094
|
+
import { join as join6 } from "path";
|
|
862
1095
|
async function diffTexts(path, before, after) {
|
|
863
|
-
const dir = mkdtempSync(
|
|
1096
|
+
const dir = mkdtempSync(join6(tmpdir(), "sub-"));
|
|
864
1097
|
try {
|
|
865
|
-
writeFileSync(
|
|
866
|
-
writeFileSync(
|
|
1098
|
+
writeFileSync(join6(dir, "before"), before);
|
|
1099
|
+
writeFileSync(join6(dir, "after"), after);
|
|
867
1100
|
let child;
|
|
868
1101
|
try {
|
|
869
|
-
child = Bun.spawn(["diff", "-u", "--label", `a/${path}`, "--label", `b/${path}`,
|
|
1102
|
+
child = Bun.spawn(["diff", "-u", "--label", `a/${path}`, "--label", `b/${path}`, join6(dir, "before"), join6(dir, "after")], { stdout: "pipe", stderr: "pipe" });
|
|
870
1103
|
} catch {
|
|
871
1104
|
throw new Error("diff is not installed, which sub needs to show its changes");
|
|
872
1105
|
}
|
|
@@ -967,7 +1200,7 @@ function applyPairs(original, pairs) {
|
|
|
967
1200
|
// src/cli.ts
|
|
968
1201
|
var USAGE = `sub [options] <file>...: replaces text in files, writing nothing unless every replacement matches as often as expected
|
|
969
1202
|
|
|
970
|
-
Multi-line text: give no --from, --to or --pairs and pipe SEARCH/REPLACE blocks on stdin from a quoted heredoc, which needs no escaping. The blocks apply in order to the files on the command line, each matching exactly once unless --count or --all says otherwise:
|
|
1203
|
+
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:
|
|
971
1204
|
|
|
972
1205
|
sub src/a.php <<'EOF'
|
|
973
1206
|
<<<<<<< SEARCH
|
|
@@ -1049,7 +1282,7 @@ function writable(path) {
|
|
|
1049
1282
|
var UTF8 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
1050
1283
|
function readUtf8(path) {
|
|
1051
1284
|
try {
|
|
1052
|
-
return UTF8.decode(
|
|
1285
|
+
return UTF8.decode(readFileSync3(path));
|
|
1053
1286
|
} catch {
|
|
1054
1287
|
return;
|
|
1055
1288
|
}
|
|
@@ -1058,7 +1291,7 @@ function canonical(path) {
|
|
|
1058
1291
|
try {
|
|
1059
1292
|
return realpathSync2(path);
|
|
1060
1293
|
} catch {
|
|
1061
|
-
return
|
|
1294
|
+
return resolve3(path);
|
|
1062
1295
|
}
|
|
1063
1296
|
}
|
|
1064
1297
|
function dedupe(paths) {
|
|
@@ -1072,16 +1305,47 @@ function dedupe(paths) {
|
|
|
1072
1305
|
}
|
|
1073
1306
|
function writeAtomic(path, text) {
|
|
1074
1307
|
const target = realpathSync2(path);
|
|
1075
|
-
const temp = `${target}.sub-${
|
|
1308
|
+
const temp = `${target}.sub-${process14.pid}`;
|
|
1076
1309
|
try {
|
|
1077
1310
|
writeFileSync2(temp, text);
|
|
1078
|
-
chmodSync(temp, (
|
|
1311
|
+
chmodSync(temp, (statSync2(target, { throwIfNoEntry: false })?.mode ?? 420) & 4095);
|
|
1079
1312
|
renameSync(temp, target);
|
|
1080
1313
|
} catch (error) {
|
|
1081
1314
|
rmSync2(temp, { force: true });
|
|
1082
1315
|
throw error;
|
|
1083
1316
|
}
|
|
1084
1317
|
}
|
|
1318
|
+
var STDIN_SILENCE_MS = 3000;
|
|
1319
|
+
async function blocksOnStdin(files) {
|
|
1320
|
+
const extra = files.slice(1).filter((path) => !existsSync3(path));
|
|
1321
|
+
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]}
|
|
1322
|
+
|
|
1323
|
+
`;
|
|
1324
|
+
const hint = `${strings}give --from and --to, or pipe SEARCH/REPLACE blocks on stdin from a heredoc
|
|
1325
|
+
|
|
1326
|
+
${USAGE}`;
|
|
1327
|
+
if (process14.stdin.isTTY)
|
|
1328
|
+
fail(hint);
|
|
1329
|
+
return new Promise((resolve) => {
|
|
1330
|
+
const chunks = [];
|
|
1331
|
+
const timer = setTimeout(() => {
|
|
1332
|
+
console.error(`error: sub: ${hint}`);
|
|
1333
|
+
process14.exit(2);
|
|
1334
|
+
}, STDIN_SILENCE_MS);
|
|
1335
|
+
process14.stdin.on("data", (chunk) => {
|
|
1336
|
+
clearTimeout(timer);
|
|
1337
|
+
chunks.push(chunk);
|
|
1338
|
+
});
|
|
1339
|
+
process14.stdin.on("end", () => {
|
|
1340
|
+
clearTimeout(timer);
|
|
1341
|
+
if (chunks.length === 0 && extra.length > 0) {
|
|
1342
|
+
console.error(`error: sub: ${hint}`);
|
|
1343
|
+
process14.exit(2);
|
|
1344
|
+
}
|
|
1345
|
+
resolve(Buffer.concat(chunks).toString("utf8"));
|
|
1346
|
+
});
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1085
1349
|
async function plan(values, files, defaults) {
|
|
1086
1350
|
const edits = new Map;
|
|
1087
1351
|
const spellings = new Map(files.map((path) => [canonical(path), path]));
|
|
@@ -1107,9 +1371,7 @@ ${USAGE}`);
|
|
|
1107
1371
|
edits.set(path, pairs);
|
|
1108
1372
|
return edits;
|
|
1109
1373
|
}
|
|
1110
|
-
const blocks = parseBlocks(await
|
|
1111
|
-
|
|
1112
|
-
${USAGE}` }));
|
|
1374
|
+
const blocks = parseBlocks(await blocksOnStdin(files));
|
|
1113
1375
|
if (typeof blocks === "string")
|
|
1114
1376
|
fail(`blocks: ${blocks}`);
|
|
1115
1377
|
for (const [i, block] of blocks.entries()) {
|
|
@@ -1141,7 +1403,7 @@ async function main(argv) {
|
|
|
1141
1403
|
const changes = [];
|
|
1142
1404
|
const problems = [];
|
|
1143
1405
|
for (const [path, pairs] of edits) {
|
|
1144
|
-
if (!
|
|
1406
|
+
if (!existsSync3(path)) {
|
|
1145
1407
|
problems.push({ path, problem: "no such file" });
|
|
1146
1408
|
continue;
|
|
1147
1409
|
}
|
|
@@ -1185,9 +1447,9 @@ ${error instanceof Error ? error.message : String(error)}`);
|
|
|
1185
1447
|
continue;
|
|
1186
1448
|
}
|
|
1187
1449
|
if (values.quiet !== true)
|
|
1188
|
-
console.log(`${path}: ${plural(lines.length, "replacement")} on line${lines.length === 1 ? "" : "s"} ${listLines(lines)},
|
|
1450
|
+
console.log(`${role("path", process14.stdout)(path)}: ${plural(lines.length, "replacement")} on line${lines.length === 1 ? "" : "s"} ${listLines(lines)}, ${role(diff.added === 0 ? "label" : "ok", process14.stdout)(`+${diff.added}`)} ${role(diff.removed === 0 ? "label" : "problem", process14.stdout)(`-${diff.removed}`)}`);
|
|
1189
1451
|
if (values.diff === true && diff.unified !== "")
|
|
1190
|
-
|
|
1452
|
+
process14.stdout.write(diff.unified);
|
|
1191
1453
|
}
|
|
1192
1454
|
if (json)
|
|
1193
1455
|
printJson({ dryRun: values["dry-run"] === true, files: done });
|
|
@@ -1195,4 +1457,4 @@ ${error instanceof Error ? error.message : String(error)}`);
|
|
|
1195
1457
|
console.log("dry run: nothing written");
|
|
1196
1458
|
return 0;
|
|
1197
1459
|
}
|
|
1198
|
-
|
|
1460
|
+
process14.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.8.0",
|
|
5
5
|
"description": "sub: text replaced in files for Claude Code, written only when every replacement matches as often as expected.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -36,6 +36,6 @@
|
|
|
36
36
|
"sub": "$npm_execpath src/cli.ts"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
|
-
"@kaynooo/cli-kit": "0.
|
|
39
|
+
"@kaynooo/cli-kit": "0.29.0"
|
|
40
40
|
}
|
|
41
41
|
}
|