@kaynooo/cli-pick 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/pick.js +509 -182
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -18,4 +18,4 @@ Keys: type to filter, up and down or ctrl-p and ctrl-n to move, enter to pick, e
|
|
|
18
18
|
|
|
19
19
|
The query matches as a subsequence, best first: a word start, a run of consecutive characters or a prefix scores higher, a lowercase query ignores case and an uppercase letter makes it exact. Keys come from `/dev/tty` and the selector is drawn on stderr, so a pipe or a command substitution takes only the choice. Without a terminal on stderr it exits 2.
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
The same picker is what `gb`, `dx`, `sf` and `j` use, with `--expect` keys, the query back, hidden fields and reloads: its engine is `@kaynooo/cli-kit/picker`, so none of them needs fzf.
|
package/dist/pick.js
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/pick.ts
|
|
5
|
-
import
|
|
5
|
+
import process13 from "process";
|
|
6
6
|
// ../kit/src/args.ts
|
|
7
|
-
import
|
|
7
|
+
import process7 from "process";
|
|
8
8
|
import { parseArgs } from "util";
|
|
9
9
|
|
|
10
10
|
// ../kit/src/style.ts
|
|
11
|
-
import
|
|
11
|
+
import process5 from "process";
|
|
12
12
|
|
|
13
13
|
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
14
14
|
function x(s) {
|
|
@@ -271,31 +271,209 @@ function le(i = {}) {
|
|
|
271
271
|
}
|
|
272
272
|
var t = le();
|
|
273
273
|
|
|
274
|
+
// ../kit/src/theme.ts
|
|
275
|
+
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
276
|
+
import { homedir as homedir2 } from "os";
|
|
277
|
+
import { join as join3, resolve as resolve2 } from "path";
|
|
278
|
+
import process4 from "process";
|
|
279
|
+
|
|
280
|
+
// ../kit/src/config.ts
|
|
281
|
+
import { existsSync } from "fs";
|
|
282
|
+
import { dirname, join, resolve } from "path";
|
|
283
|
+
import process2 from "process";
|
|
284
|
+
function findUp(names, from = process2.cwd(), stop = () => false) {
|
|
285
|
+
const wanted = typeof names === "string" ? [names] : names;
|
|
286
|
+
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
287
|
+
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
288
|
+
if (found !== undefined)
|
|
289
|
+
return found;
|
|
290
|
+
if (stop(dir) || dirname(dir) === dir)
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// ../kit/src/user-config.ts
|
|
296
|
+
import { homedir } from "os";
|
|
297
|
+
import { join as join2 } from "path";
|
|
298
|
+
import process3 from "process";
|
|
299
|
+
function configBase(where = {}) {
|
|
300
|
+
const xdg = where.xdg ?? (where.home === undefined ? process3.env.XDG_CONFIG_HOME : undefined);
|
|
301
|
+
return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
|
|
302
|
+
}
|
|
303
|
+
function userConfigPath(bin, where = {}) {
|
|
304
|
+
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// ../kit/src/theme.ts
|
|
308
|
+
var DEFAULT = {
|
|
309
|
+
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" },
|
|
310
|
+
glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
|
|
311
|
+
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
312
|
+
bins: {}
|
|
313
|
+
};
|
|
314
|
+
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" };
|
|
315
|
+
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" };
|
|
316
|
+
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
|
|
317
|
+
var PRESETS = {
|
|
318
|
+
default: {},
|
|
319
|
+
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
|
|
320
|
+
mono: { colors: MONO, accents: ["bold"] },
|
|
321
|
+
ascii: { glyphs: ASCII }
|
|
322
|
+
};
|
|
323
|
+
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"]);
|
|
324
|
+
var HEX = /^#[0-9a-f]{6}$/i;
|
|
325
|
+
var CONTROL = /\p{Cc}/u;
|
|
326
|
+
var MAX_FILE_BYTES = 64 * 1024;
|
|
327
|
+
var SPACES = /\s+/;
|
|
328
|
+
function isColorSpec(spec) {
|
|
329
|
+
if (typeof spec === "number")
|
|
330
|
+
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
331
|
+
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
332
|
+
}
|
|
333
|
+
function tinted(colors, spec) {
|
|
334
|
+
if (typeof spec === "number")
|
|
335
|
+
return colors.ansi256(spec);
|
|
336
|
+
return spec.trim().split(SPACES).reduce((chain, token) => HEX.test(token) ? chain.hex(token) : chain[token] ?? chain, colors);
|
|
337
|
+
}
|
|
338
|
+
function isRecord(value) {
|
|
339
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
340
|
+
}
|
|
341
|
+
function readThemeFile(path, warn) {
|
|
342
|
+
try {
|
|
343
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
344
|
+
if (stat === undefined)
|
|
345
|
+
return;
|
|
346
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
347
|
+
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
351
|
+
if (isRecord(parsed))
|
|
352
|
+
return parsed;
|
|
353
|
+
warn(`${path} is not a JSON object, theme ignored`);
|
|
354
|
+
} catch (error) {
|
|
355
|
+
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
356
|
+
}
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
function applyPreset(theme, name, warn, where) {
|
|
360
|
+
if (name === undefined)
|
|
361
|
+
return;
|
|
362
|
+
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
363
|
+
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
const preset = PRESETS[name];
|
|
367
|
+
Object.assign(theme.colors, preset.colors);
|
|
368
|
+
Object.assign(theme.glyphs, preset.glyphs);
|
|
369
|
+
if (preset.accents !== undefined)
|
|
370
|
+
theme.accents = [...preset.accents];
|
|
371
|
+
return name;
|
|
372
|
+
}
|
|
373
|
+
function applyFile(theme, file, where, warn) {
|
|
374
|
+
if (isRecord(file.colors)) {
|
|
375
|
+
for (const [key, value] of Object.entries(file.colors)) {
|
|
376
|
+
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
377
|
+
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
378
|
+
else if (!isColorSpec(value))
|
|
379
|
+
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
380
|
+
else
|
|
381
|
+
theme.colors[key] = value;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
if (isRecord(file.glyphs)) {
|
|
385
|
+
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
386
|
+
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
387
|
+
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
388
|
+
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
389
|
+
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
390
|
+
else
|
|
391
|
+
theme.glyphs[key] = value;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
395
|
+
theme.accents = [...file.accents];
|
|
396
|
+
else if (file.accents !== undefined)
|
|
397
|
+
warn(`${where}: accents must be a non-empty list of colours`);
|
|
398
|
+
if (isRecord(file.bins)) {
|
|
399
|
+
for (const [bin, value] of Object.entries(file.bins)) {
|
|
400
|
+
if (isColorSpec(value))
|
|
401
|
+
theme.bins[bin] = value;
|
|
402
|
+
else
|
|
403
|
+
warn(`${where}: bin ${bin} has no valid colour`);
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
function endsWalk(home) {
|
|
408
|
+
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
409
|
+
}
|
|
410
|
+
var warned = new Set;
|
|
411
|
+
function warnOnce(message) {
|
|
412
|
+
if (warned.has(message))
|
|
413
|
+
return;
|
|
414
|
+
warned.add(message);
|
|
415
|
+
console.error(`warning: theme ${message}`);
|
|
416
|
+
}
|
|
417
|
+
function isPath(chosen) {
|
|
418
|
+
return chosen.includes("/") || chosen.endsWith(".json");
|
|
419
|
+
}
|
|
420
|
+
function loadTheme({ env = process4.env, from = process4.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
421
|
+
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
|
|
422
|
+
const sources = [];
|
|
423
|
+
const chosen = env.KIT_THEME ?? "";
|
|
424
|
+
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
425
|
+
if (isPath(chosen))
|
|
426
|
+
wanted.push(resolve2(from, chosen));
|
|
427
|
+
const files = [];
|
|
428
|
+
for (const path of wanted) {
|
|
429
|
+
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
430
|
+
if (path !== undefined && file !== undefined)
|
|
431
|
+
files.push({ path, file });
|
|
432
|
+
}
|
|
433
|
+
let preset = "default";
|
|
434
|
+
if (chosen !== "" && !isPath(chosen)) {
|
|
435
|
+
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
436
|
+
} else {
|
|
437
|
+
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
438
|
+
if (named !== undefined)
|
|
439
|
+
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
440
|
+
}
|
|
441
|
+
for (const { path, file } of files) {
|
|
442
|
+
applyFile(theme, file, path, warn);
|
|
443
|
+
sources.push(path);
|
|
444
|
+
}
|
|
445
|
+
return { theme, sources, preset };
|
|
446
|
+
}
|
|
447
|
+
var current;
|
|
448
|
+
var currentKey = "";
|
|
449
|
+
function activeTheme() {
|
|
450
|
+
const key = `${process4.cwd()}\x00${process4.env.KIT_THEME ?? ""}\x00${process4.env.XDG_CONFIG_HOME ?? ""}`;
|
|
451
|
+
if (current === undefined || key !== currentKey) {
|
|
452
|
+
current = loadTheme();
|
|
453
|
+
currentKey = key;
|
|
454
|
+
}
|
|
455
|
+
return current;
|
|
456
|
+
}
|
|
457
|
+
|
|
274
458
|
// ../kit/src/style.ts
|
|
275
|
-
function takesControlCodes(stream, env =
|
|
459
|
+
function takesControlCodes(stream, env = process5.env) {
|
|
276
460
|
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
277
461
|
}
|
|
278
|
-
function paint(stream, env =
|
|
462
|
+
function paint(stream, env = process5.env) {
|
|
279
463
|
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
280
464
|
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
var STATUSES = {
|
|
292
|
-
passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
|
|
293
|
-
failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
|
|
294
|
-
running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
|
|
295
|
-
queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
|
|
296
|
-
skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
|
|
465
|
+
function role(name, stream, env = process5.env) {
|
|
466
|
+
const colors = paint(stream, env);
|
|
467
|
+
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name]) : colors;
|
|
468
|
+
}
|
|
469
|
+
var STATUS_WORDS = {
|
|
470
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
471
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
472
|
+
running: ["running", "in_progress", "started"],
|
|
473
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
474
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
297
475
|
};
|
|
298
|
-
var STATUS_OF = new Map(Object.entries(
|
|
476
|
+
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
299
477
|
|
|
300
478
|
// ../kit/src/format.ts
|
|
301
479
|
function upTo(text, separator) {
|
|
@@ -305,27 +483,27 @@ function upTo(text, separator) {
|
|
|
305
483
|
var ESCAPE = String.fromCharCode(27);
|
|
306
484
|
|
|
307
485
|
// ../kit/src/help.ts
|
|
308
|
-
import
|
|
486
|
+
import process6 from "process";
|
|
309
487
|
var OPTIONAL = /\[[^\]]+\]/g;
|
|
310
488
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
311
489
|
var FULL_STOP = /\.$/;
|
|
312
|
-
function usageLine(usage, colors = paint(
|
|
490
|
+
function usageLine(usage, colors = paint(process6.stdout)) {
|
|
313
491
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
314
492
|
}
|
|
315
|
-
function helpText(usage, options, colors = paint(
|
|
493
|
+
function helpText(usage, options, colors = paint(process6.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
316
494
|
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
317
495
|
`);
|
|
318
496
|
}
|
|
319
|
-
function exitRows(exits, colors = paint(
|
|
497
|
+
function exitRows(exits, colors = paint(process6.stdout)) {
|
|
320
498
|
if (exits.length === 0)
|
|
321
499
|
return [];
|
|
322
500
|
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
323
501
|
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
324
502
|
}
|
|
325
|
-
function replacesRows(replaces, colors = paint(
|
|
503
|
+
function replacesRows(replaces, colors = paint(process6.stdout)) {
|
|
326
504
|
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
327
505
|
}
|
|
328
|
-
function wantsHelpJson(env =
|
|
506
|
+
function wantsHelpJson(env = process6.env) {
|
|
329
507
|
return env.KIT_HELP === "json";
|
|
330
508
|
}
|
|
331
509
|
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
@@ -344,12 +522,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
|
344
522
|
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
345
523
|
};
|
|
346
524
|
}
|
|
347
|
-
function exampleRows(examples, colors = paint(
|
|
525
|
+
function exampleRows(examples, colors = paint(process6.stdout)) {
|
|
348
526
|
if (examples.length === 0)
|
|
349
527
|
return [];
|
|
350
528
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
351
529
|
}
|
|
352
|
-
function optionRows(options, colors = paint(
|
|
530
|
+
function optionRows(options, colors = paint(process6.stdout)) {
|
|
353
531
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
354
532
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
355
533
|
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
@@ -426,7 +604,7 @@ var OUTPUT_OPTIONS = {
|
|
|
426
604
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
427
605
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
428
606
|
};
|
|
429
|
-
function applyOutput(color, plain, env =
|
|
607
|
+
function applyOutput(color, plain, env = process7.env) {
|
|
430
608
|
const when = plain === true ? "never" : color ?? "auto";
|
|
431
609
|
if (when === "auto")
|
|
432
610
|
return;
|
|
@@ -601,15 +779,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
601
779
|
var RESET_STYLE = `${ESC}[0m`;
|
|
602
780
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
603
781
|
// ../kit/src/cli.ts
|
|
604
|
-
import { readFileSync, realpathSync } from "fs";
|
|
605
|
-
import { dirname as
|
|
606
|
-
import
|
|
782
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
783
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
784
|
+
import process9 from "process";
|
|
607
785
|
|
|
608
786
|
// ../kit/src/usage.ts
|
|
609
787
|
import { appendFileSync, mkdirSync } from "fs";
|
|
610
|
-
import { homedir } from "os";
|
|
611
|
-
import { dirname, isAbsolute, join } from "path";
|
|
612
|
-
import
|
|
788
|
+
import { homedir as homedir3 } from "os";
|
|
789
|
+
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
790
|
+
import process8 from "process";
|
|
613
791
|
|
|
614
792
|
// ../kit/src/logs.ts
|
|
615
793
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -623,14 +801,14 @@ var usageError;
|
|
|
623
801
|
function noteUsageError(message) {
|
|
624
802
|
usageError = message;
|
|
625
803
|
}
|
|
626
|
-
function stateHome(env =
|
|
804
|
+
function stateHome(env = process8.env) {
|
|
627
805
|
const dir = env.XDG_STATE_HOME;
|
|
628
|
-
return dir !== undefined && isAbsolute(dir) ? dir :
|
|
806
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
629
807
|
}
|
|
630
|
-
function usagePath(env =
|
|
631
|
-
return
|
|
808
|
+
function usagePath(env = process8.env) {
|
|
809
|
+
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
632
810
|
}
|
|
633
|
-
function usageRecorded(env =
|
|
811
|
+
function usageRecorded(env = process8.env) {
|
|
634
812
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
635
813
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
636
814
|
}
|
|
@@ -644,12 +822,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
644
822
|
usageError = undefined;
|
|
645
823
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
646
824
|
}
|
|
647
|
-
function recordUsage(entry, env =
|
|
825
|
+
function recordUsage(entry, env = process8.env) {
|
|
648
826
|
if (!usageRecorded(env))
|
|
649
827
|
return;
|
|
650
828
|
try {
|
|
651
829
|
const path = usagePath(env);
|
|
652
|
-
mkdirSync(
|
|
830
|
+
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
653
831
|
appendFileSync(path, `${JSON.stringify(entry)}
|
|
654
832
|
`, { mode: 384 });
|
|
655
833
|
} catch {}
|
|
@@ -662,8 +840,8 @@ var LEVEL_OPTIONS = {
|
|
|
662
840
|
};
|
|
663
841
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
664
842
|
function printError(prefix, message, hint, cause) {
|
|
665
|
-
const colors = paint(
|
|
666
|
-
const styled = takesControlCodes(
|
|
843
|
+
const colors = paint(process9.stderr);
|
|
844
|
+
const styled = takesControlCodes(process9.stderr);
|
|
667
845
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
668
846
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
669
847
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -682,7 +860,7 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
682
860
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
683
861
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
684
862
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
685
|
-
if (error instanceof
|
|
863
|
+
if (error instanceof Exit && error.code === 2)
|
|
686
864
|
noteUsageError(error.message);
|
|
687
865
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
688
866
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
@@ -746,17 +924,17 @@ async function printCandidates(found) {
|
|
|
746
924
|
return 0;
|
|
747
925
|
}
|
|
748
926
|
function packageVersion(entry = Bun.main) {
|
|
749
|
-
for (let dir =
|
|
927
|
+
for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
|
|
750
928
|
try {
|
|
751
|
-
const { version } = JSON.parse(
|
|
929
|
+
const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
|
|
752
930
|
if (typeof version === "string")
|
|
753
931
|
return version;
|
|
754
932
|
} catch {}
|
|
755
|
-
if (
|
|
933
|
+
if (dirname3(dir) === dir)
|
|
756
934
|
return "0.0.0";
|
|
757
935
|
}
|
|
758
936
|
}
|
|
759
|
-
async function runMain({ name, version, run, redact, usage }, argv =
|
|
937
|
+
async function runMain({ name, version, run, redact, usage }, argv = process9.argv.slice(2)) {
|
|
760
938
|
if (argv[0] === COMPLETE)
|
|
761
939
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
762
940
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
@@ -782,62 +960,7 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
|
|
|
782
960
|
var {Glob } = globalThis.Bun;
|
|
783
961
|
var SESSION_FILES = new Glob("*.json");
|
|
784
962
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
785
|
-
// src/
|
|
786
|
-
import { openSync } from "fs";
|
|
787
|
-
import process9 from "process";
|
|
788
|
-
import tty from "tty";
|
|
789
|
-
|
|
790
|
-
// src/preview.ts
|
|
791
|
-
import process8 from "process";
|
|
792
|
-
|
|
793
|
-
// ../kit/src/shell.ts
|
|
794
|
-
var SEPARATORS = new Set([`
|
|
795
|
-
`, ";", "|"]);
|
|
796
|
-
var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
|
|
797
|
-
var GLOB_CHARS = new Set(["*", "?", "["]);
|
|
798
|
-
var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
|
|
799
|
-
var SAFE_WORD = /^[\w@%+=:,./-]+$/;
|
|
800
|
-
var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
|
|
801
|
-
var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
|
|
802
|
-
var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
|
|
803
|
-
var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
|
|
804
|
-
var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
|
|
805
|
-
var POWERSHELL = new Set(["pwsh", "powershell"]);
|
|
806
|
-
var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
|
|
807
|
-
var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
|
|
808
|
-
var PRINTERS = new Set(["echo", "printf"]);
|
|
809
|
-
var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
810
|
-
function wrapper(short = "", long = [], operands = 0, runsString = false) {
|
|
811
|
-
return { short, long, operands, runsString };
|
|
812
|
-
}
|
|
813
|
-
var WRAPPERS = new Map([
|
|
814
|
-
["command", wrapper()],
|
|
815
|
-
["builtin", wrapper()],
|
|
816
|
-
["nohup", wrapper()],
|
|
817
|
-
["setsid", wrapper()],
|
|
818
|
-
["busybox", wrapper()],
|
|
819
|
-
["exec", wrapper("a")],
|
|
820
|
-
["time", wrapper("fo", ["--format", "--output"])],
|
|
821
|
-
["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
|
|
822
|
-
["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
|
|
823
|
-
["doas", wrapper("uC")],
|
|
824
|
-
["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
|
|
825
|
-
["nice", wrapper("n", ["--adjustment"])],
|
|
826
|
-
["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
|
|
827
|
-
["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
|
|
828
|
-
["chroot", wrapper("", ["--userspec", "--groups"], 1)],
|
|
829
|
-
["watch", wrapper("n", ["--interval"], 0, true)],
|
|
830
|
-
["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
|
|
831
|
-
["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
|
|
832
|
-
["unbuffer", wrapper()],
|
|
833
|
-
["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
|
|
834
|
-
["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
|
|
835
|
-
]);
|
|
836
|
-
function shellQuote(word) {
|
|
837
|
-
return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
838
|
-
}
|
|
839
|
-
|
|
840
|
-
// src/score.ts
|
|
963
|
+
// ../kit/src/picker/score.ts
|
|
841
964
|
var MATCH = 16;
|
|
842
965
|
var CONSECUTIVE = 12;
|
|
843
966
|
var BOUNDARY = 10;
|
|
@@ -920,10 +1043,13 @@ function rank(query, lines) {
|
|
|
920
1043
|
return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
|
|
921
1044
|
}
|
|
922
1045
|
|
|
923
|
-
// src/state.ts
|
|
1046
|
+
// ../kit/src/picker/state.ts
|
|
924
1047
|
var ANSI2 = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
|
|
925
|
-
var
|
|
1048
|
+
var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
|
|
926
1049
|
var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
1050
|
+
var SGR = /^\x1B\[[0-9;]*m$/;
|
|
1051
|
+
var RESET = /^\x1B\[0?m$/;
|
|
1052
|
+
var COLUMN_GAP = 2;
|
|
927
1053
|
var PASTE_START = "\x1B[200~";
|
|
928
1054
|
var PASTE_END = "\x1B[201~";
|
|
929
1055
|
var LAST_WORD = /\S*\s*$/;
|
|
@@ -945,12 +1071,60 @@ var KEYS = {
|
|
|
945
1071
|
"\x17": "word",
|
|
946
1072
|
"\t": "tab"
|
|
947
1073
|
};
|
|
948
|
-
function
|
|
949
|
-
return
|
|
1074
|
+
function repeat(value, count) {
|
|
1075
|
+
return Array.from({ length: count }).fill(value);
|
|
1076
|
+
}
|
|
1077
|
+
function styled(line) {
|
|
1078
|
+
let text = "";
|
|
1079
|
+
const styles = [];
|
|
1080
|
+
let active = "";
|
|
1081
|
+
let colored = false;
|
|
1082
|
+
let last = 0;
|
|
1083
|
+
function add(chunk) {
|
|
1084
|
+
const flat = chunk.replace(CONTROL2, " ");
|
|
1085
|
+
text += flat;
|
|
1086
|
+
colored ||= active !== "" && flat !== "";
|
|
1087
|
+
styles.push(...repeat(active, flat.length));
|
|
1088
|
+
}
|
|
1089
|
+
for (const found of line.matchAll(ANSI2)) {
|
|
1090
|
+
add(line.slice(last, found.index));
|
|
1091
|
+
last = found.index + found[0].length;
|
|
1092
|
+
if (SGR.test(found[0]))
|
|
1093
|
+
active = RESET.test(found[0]) ? "" : active + found[0];
|
|
1094
|
+
}
|
|
1095
|
+
add(line.slice(last));
|
|
1096
|
+
return { text, styles: colored ? styles : undefined };
|
|
1097
|
+
}
|
|
1098
|
+
function lay(rows, searched) {
|
|
1099
|
+
const parsed = rows.map((row) => row.cells.map(styled));
|
|
1100
|
+
const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
|
|
1101
|
+
return parsed.map((cells) => {
|
|
1102
|
+
let text = "";
|
|
1103
|
+
const styles = [];
|
|
1104
|
+
let colored = false;
|
|
1105
|
+
let searchEnd = 0;
|
|
1106
|
+
for (const [column, cell] of cells.entries()) {
|
|
1107
|
+
const last = column === cells.length - 1;
|
|
1108
|
+
const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
|
|
1109
|
+
text += shown;
|
|
1110
|
+
colored ||= cell.styles !== undefined;
|
|
1111
|
+
styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
|
|
1112
|
+
if (column < searched)
|
|
1113
|
+
searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
|
|
1114
|
+
if (!last) {
|
|
1115
|
+
const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
|
|
1116
|
+
text += " ".repeat(pad);
|
|
1117
|
+
styles.push(...repeat("", pad));
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
return { text, styles: colored ? styles : undefined, searchable: text.slice(0, searchEnd) };
|
|
1121
|
+
});
|
|
950
1122
|
}
|
|
951
|
-
function parseKeys(input, paste = { active: false }) {
|
|
1123
|
+
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
1124
|
+
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
952
1125
|
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
953
|
-
const
|
|
1126
|
+
const named = codes.get(sequence);
|
|
1127
|
+
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
954
1128
|
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
955
1129
|
paste.active = sequence === PASTE_START;
|
|
956
1130
|
return [];
|
|
@@ -963,12 +1137,19 @@ function parseKeys(input, paste = { active: false }) {
|
|
|
963
1137
|
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
964
1138
|
});
|
|
965
1139
|
}
|
|
966
|
-
function createState(
|
|
967
|
-
const
|
|
968
|
-
return
|
|
1140
|
+
function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
|
|
1141
|
+
const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, matches: [], cursor: 0, marked: new Set, multi, prompt, done: undefined };
|
|
1142
|
+
return withRows(state, rows);
|
|
1143
|
+
}
|
|
1144
|
+
function withRows(state, rows, header = state.header) {
|
|
1145
|
+
const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
|
|
1146
|
+
const laid = lay(cells, state.searched);
|
|
1147
|
+
const searchable = laid.map((row) => row.searchable);
|
|
1148
|
+
const matches = rank(state.query, searchable);
|
|
1149
|
+
return { ...state, rows: cells, items: laid.map((row) => row.text), styles: laid.map((row) => row.styles), searchable, header, matches, cursor: Math.max(0, Math.min(matches.length - 1, state.cursor)), marked: new Set };
|
|
969
1150
|
}
|
|
970
1151
|
function withQuery(state, query) {
|
|
971
|
-
return { ...state, query, matches: rank(query, state.
|
|
1152
|
+
return { ...state, query, matches: rank(query, state.searchable), cursor: 0 };
|
|
972
1153
|
}
|
|
973
1154
|
function move(state, by) {
|
|
974
1155
|
return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
|
|
@@ -979,8 +1160,11 @@ function highlighted(state) {
|
|
|
979
1160
|
function press(state, key) {
|
|
980
1161
|
if (state.done !== undefined)
|
|
981
1162
|
return state;
|
|
982
|
-
if (typeof key === "object")
|
|
983
|
-
|
|
1163
|
+
if (typeof key === "object") {
|
|
1164
|
+
if ("text" in key)
|
|
1165
|
+
return withQuery(state, state.query + key.text);
|
|
1166
|
+
return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
|
|
1167
|
+
}
|
|
984
1168
|
switch (key) {
|
|
985
1169
|
case "up":
|
|
986
1170
|
return move(state, -1);
|
|
@@ -1009,31 +1193,87 @@ function press(state, key) {
|
|
|
1009
1193
|
}
|
|
1010
1194
|
function chosen(state) {
|
|
1011
1195
|
if (state.marked.size > 0)
|
|
1012
|
-
return state.
|
|
1196
|
+
return state.rows.filter((_, index) => state.marked.has(index));
|
|
1013
1197
|
const at = highlighted(state);
|
|
1014
|
-
return at === undefined ? [] : [state.
|
|
1198
|
+
return at === undefined ? [] : [state.rows[at]];
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
// ../kit/src/picker/terminal.ts
|
|
1202
|
+
import { openSync } from "fs";
|
|
1203
|
+
import process12 from "process";
|
|
1204
|
+
import tty from "tty";
|
|
1205
|
+
|
|
1206
|
+
// ../kit/src/picker/preview.ts
|
|
1207
|
+
import process11 from "process";
|
|
1208
|
+
|
|
1209
|
+
// ../kit/src/shell.ts
|
|
1210
|
+
var SEPARATORS = new Set([`
|
|
1211
|
+
`, ";", "|"]);
|
|
1212
|
+
var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
|
|
1213
|
+
var GLOB_CHARS = new Set(["*", "?", "["]);
|
|
1214
|
+
var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
|
|
1215
|
+
var SAFE_WORD = /^[\w@%+=:,./-]+$/;
|
|
1216
|
+
var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
|
|
1217
|
+
var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
|
|
1218
|
+
var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
|
|
1219
|
+
var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
|
|
1220
|
+
var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
|
|
1221
|
+
var POWERSHELL = new Set(["pwsh", "powershell"]);
|
|
1222
|
+
var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
|
|
1223
|
+
var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
|
|
1224
|
+
var PRINTERS = new Set(["echo", "printf"]);
|
|
1225
|
+
var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
1226
|
+
function wrapper(short = "", long = [], operands = 0, runsString = false) {
|
|
1227
|
+
return { short, long, operands, runsString };
|
|
1228
|
+
}
|
|
1229
|
+
var WRAPPERS = new Map([
|
|
1230
|
+
["command", wrapper()],
|
|
1231
|
+
["builtin", wrapper()],
|
|
1232
|
+
["nohup", wrapper()],
|
|
1233
|
+
["setsid", wrapper()],
|
|
1234
|
+
["busybox", wrapper()],
|
|
1235
|
+
["exec", wrapper("a")],
|
|
1236
|
+
["time", wrapper("fo", ["--format", "--output"])],
|
|
1237
|
+
["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
|
|
1238
|
+
["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
|
|
1239
|
+
["doas", wrapper("uC")],
|
|
1240
|
+
["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
|
|
1241
|
+
["nice", wrapper("n", ["--adjustment"])],
|
|
1242
|
+
["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
|
|
1243
|
+
["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
|
|
1244
|
+
["chroot", wrapper("", ["--userspec", "--groups"], 1)],
|
|
1245
|
+
["watch", wrapper("n", ["--interval"], 0, true)],
|
|
1246
|
+
["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
|
|
1247
|
+
["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
|
|
1248
|
+
["unbuffer", wrapper()],
|
|
1249
|
+
["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
|
|
1250
|
+
["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
|
|
1251
|
+
]);
|
|
1252
|
+
function shellQuote(word) {
|
|
1253
|
+
return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
1015
1254
|
}
|
|
1016
1255
|
|
|
1017
|
-
// src/preview.ts
|
|
1256
|
+
// ../kit/src/picker/preview.ts
|
|
1018
1257
|
var PREVIEW_BYTES = 64 * 1024;
|
|
1019
1258
|
var PREVIEW_LINES = 200;
|
|
1020
1259
|
var PREVIEW_TIMEOUT_MS = 3000;
|
|
1021
|
-
|
|
1022
|
-
|
|
1260
|
+
var PLACEHOLDER = /\{([1-9]\d*)?\}/g;
|
|
1261
|
+
function previewCommand(template, line, hidden = []) {
|
|
1262
|
+
return template.replace(PLACEHOLDER, (_, field) => shellQuote(field === undefined ? line : hidden[Number(field) - 1] ?? ""));
|
|
1023
1263
|
}
|
|
1024
1264
|
function previewLines(output) {
|
|
1025
1265
|
const lines = output.split(`
|
|
1026
1266
|
`);
|
|
1027
1267
|
if (lines.at(-1) === "")
|
|
1028
1268
|
lines.pop();
|
|
1029
|
-
return lines.slice(0, PREVIEW_LINES)
|
|
1269
|
+
return lines.slice(0, PREVIEW_LINES);
|
|
1030
1270
|
}
|
|
1031
|
-
async function runPreview(template, line, signal) {
|
|
1271
|
+
async function runPreview(template, line, signal, hidden = []) {
|
|
1032
1272
|
const proc = Bun.spawn(["sh", "-c", `exec 2>&1
|
|
1033
|
-
${previewCommand(template, line)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
|
|
1273
|
+
${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
|
|
1034
1274
|
const stop = () => {
|
|
1035
1275
|
try {
|
|
1036
|
-
|
|
1276
|
+
process11.kill(-proc.pid, "SIGKILL");
|
|
1037
1277
|
} catch {
|
|
1038
1278
|
proc.kill();
|
|
1039
1279
|
}
|
|
@@ -1058,9 +1298,12 @@ ${previewCommand(template, line)}`], { stdin: "ignore", stdout: "pipe", stderr:
|
|
|
1058
1298
|
return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
|
|
1059
1299
|
}
|
|
1060
1300
|
|
|
1061
|
-
// src/view.ts
|
|
1301
|
+
// ../kit/src/picker/view.ts
|
|
1062
1302
|
var MIN_HEIGHT = 4;
|
|
1063
1303
|
var PREVIEW_MIN_COLUMNS = 80;
|
|
1304
|
+
var PREVIEW_MIN_ROWS = 10;
|
|
1305
|
+
var PREVIEW_SHARE = 0.4;
|
|
1306
|
+
var RESET2 = "\x1B[0m";
|
|
1064
1307
|
var SEPARATOR = " \u2502 ";
|
|
1065
1308
|
var HEIGHT = /^(\d+)(%?)$/;
|
|
1066
1309
|
var DEFAULT_HEIGHT = { percent: 40 };
|
|
@@ -1070,14 +1313,18 @@ function parseHeight(text) {
|
|
|
1070
1313
|
return;
|
|
1071
1314
|
return found[2] === "%" ? { percent: Math.min(100, Number(found[1])) } : { lines: Number(found[1]) };
|
|
1072
1315
|
}
|
|
1073
|
-
function layoutFor(size, height, previewing) {
|
|
1316
|
+
function layoutFor(size, height, previewing, position = "right") {
|
|
1074
1317
|
const wanted = "lines" in height ? height.lines : Math.round(size.rows * height.percent / 100);
|
|
1075
1318
|
const rows = Math.min(size.rows, Math.max(MIN_HEIGHT, wanted));
|
|
1319
|
+
if (position === "down") {
|
|
1320
|
+
const previewHeight = previewing && rows >= PREVIEW_MIN_ROWS ? Math.round(rows * PREVIEW_SHARE) : 0;
|
|
1321
|
+
return { height: rows, listHeight: rows - previewHeight, listWidth: size.columns, previewWidth: 0, previewHeight };
|
|
1322
|
+
}
|
|
1076
1323
|
const split = previewing && size.columns >= PREVIEW_MIN_COLUMNS;
|
|
1077
1324
|
const listWidth = split ? Math.floor(size.columns / 2) : size.columns;
|
|
1078
|
-
return { height: rows, listWidth, previewWidth: split ? size.columns - listWidth - SEPARATOR.length : 0 };
|
|
1325
|
+
return { height: rows, listHeight: rows, listWidth, previewWidth: split ? size.columns - listWidth - SEPARATOR.length : 0, previewHeight: 0 };
|
|
1079
1326
|
}
|
|
1080
|
-
function fit(text, width, plain, mark = plain, marked = new Set) {
|
|
1327
|
+
function fit(text, width, plain, mark = plain, marked = new Set, styles) {
|
|
1081
1328
|
const room = Bun.stringWidth(text) > width ? width - 1 : width;
|
|
1082
1329
|
let out = "";
|
|
1083
1330
|
let used = 0;
|
|
@@ -1086,7 +1333,8 @@ function fit(text, width, plain, mark = plain, marked = new Set) {
|
|
|
1086
1333
|
const size = Bun.stringWidth(char);
|
|
1087
1334
|
if (used + size > room)
|
|
1088
1335
|
break;
|
|
1089
|
-
|
|
1336
|
+
const style = marked.has(at) ? "" : styles?.[at] ?? "";
|
|
1337
|
+
out += style === "" ? (marked.has(at) ? mark : plain)(char) : `${style}${char}${RESET2}`;
|
|
1090
1338
|
used += size;
|
|
1091
1339
|
at += char.length;
|
|
1092
1340
|
}
|
|
@@ -1097,25 +1345,31 @@ function fit(text, width, plain, mark = plain, marked = new Set) {
|
|
|
1097
1345
|
return { text: out, width: used };
|
|
1098
1346
|
}
|
|
1099
1347
|
var identity = (text) => text;
|
|
1348
|
+
function fitStyled(line, width, plain = identity) {
|
|
1349
|
+
const { text, styles } = styled(line);
|
|
1350
|
+
return fit(text, width, plain, plain, new Set, styles);
|
|
1351
|
+
}
|
|
1100
1352
|
function caretColumn(state, layout) {
|
|
1101
1353
|
return Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + Bun.stringWidth(state.query) + 1);
|
|
1102
1354
|
}
|
|
1103
1355
|
function listLines(state, layout, theme) {
|
|
1104
|
-
const
|
|
1356
|
+
const header = state.header === "" ? [] : state.header.split(`
|
|
1357
|
+
`).map((line) => fitStyled(line, layout.listWidth, theme.label));
|
|
1358
|
+
const rows = Math.max(1, layout.listHeight - 2 - header.length);
|
|
1105
1359
|
const prefixWidth = state.multi ? 4 : 2;
|
|
1106
1360
|
const top = Math.max(0, Math.min(state.cursor - Math.floor(rows / 2), state.matches.length - rows));
|
|
1107
|
-
const marks = state.marked.size > 0 ? ` (${state.marked.size} marked)` : "";
|
|
1361
|
+
const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
|
|
1108
1362
|
const promptWidth = Bun.stringWidth(state.prompt);
|
|
1109
1363
|
const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
|
|
1110
1364
|
const count = fit(` ${state.matches.length}/${state.items.length}${marks}`, layout.listWidth, theme.label);
|
|
1111
|
-
const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count];
|
|
1365
|
+
const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
|
|
1112
1366
|
if (state.matches.length === 0)
|
|
1113
1367
|
lines.push(fit(" no match", layout.listWidth, theme.label));
|
|
1114
1368
|
for (const [offset, match] of state.matches.slice(top, top + rows).entries()) {
|
|
1115
1369
|
const current = top + offset === state.cursor;
|
|
1116
1370
|
const pointer = current ? theme.accent("\u276F") : " ";
|
|
1117
1371
|
const mark = state.multi ? `${state.marked.has(match.index) ? theme.id("\u25CF") : " "} ` : "";
|
|
1118
|
-
const text = fit(state.items[match.index], layout.listWidth - prefixWidth, current ? theme.value : identity, theme.accent, new Set(match.positions));
|
|
1372
|
+
const text = fit(state.items[match.index], layout.listWidth - prefixWidth, current ? theme.value : identity, theme.accent, new Set(match.positions), state.styles[match.index]);
|
|
1119
1373
|
lines.push({ text: `${pointer} ${mark}${text.text}`, width: prefixWidth + text.width });
|
|
1120
1374
|
}
|
|
1121
1375
|
return lines;
|
|
@@ -1123,37 +1377,65 @@ function listLines(state, layout, theme) {
|
|
|
1123
1377
|
function render(state, layout, theme, preview = []) {
|
|
1124
1378
|
const left = listLines(state, layout, theme);
|
|
1125
1379
|
return Array.from({ length: layout.height }, (_, row) => {
|
|
1380
|
+
if (row >= layout.listHeight)
|
|
1381
|
+
return row === layout.listHeight ? theme.label("\u2500".repeat(layout.listWidth)) : fitStyled(preview[row - layout.listHeight - 1] ?? "", layout.listWidth).text;
|
|
1126
1382
|
const list = left[row] ?? { text: "", width: 0 };
|
|
1127
1383
|
if (layout.previewWidth === 0)
|
|
1128
1384
|
return list.text;
|
|
1129
|
-
return `${list.text}${" ".repeat(Math.max(0, layout.listWidth - list.width))}${theme.label(SEPARATOR)}${
|
|
1385
|
+
return `${list.text}${" ".repeat(Math.max(0, layout.listWidth - list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row] ?? "", layout.previewWidth).text}`;
|
|
1130
1386
|
});
|
|
1131
1387
|
}
|
|
1132
1388
|
|
|
1133
|
-
// src/terminal.ts
|
|
1389
|
+
// ../kit/src/picker/terminal.ts
|
|
1134
1390
|
var PREVIEW_DELAY_MS = 120;
|
|
1391
|
+
var OPEN = { ctrl: "open" };
|
|
1135
1392
|
var HIDE_CURSOR = "\x1B[?25l";
|
|
1136
1393
|
var SHOW_CURSOR = "\x1B[?25h";
|
|
1137
1394
|
var PASTE_ON = "\x1B[?2004h";
|
|
1138
1395
|
var PASTE_OFF = "\x1B[?2004l";
|
|
1139
1396
|
var CLEAR_BELOW = "\r\x1B[J";
|
|
1140
1397
|
var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
|
|
1141
|
-
function themeFor(stream) {
|
|
1142
|
-
return { accent: role("accent", stream), label: role("label", stream), value: role("value", stream), id: role("id", stream) };
|
|
1143
|
-
}
|
|
1144
1398
|
function up(lines) {
|
|
1145
1399
|
return lines > 0 ? `\x1B[${lines}A` : "";
|
|
1146
1400
|
}
|
|
1147
|
-
|
|
1401
|
+
function openTerminal() {
|
|
1148
1402
|
let input;
|
|
1149
1403
|
try {
|
|
1150
1404
|
input = new tty.ReadStream(openSync("/dev/tty", "r"));
|
|
1151
1405
|
} catch {
|
|
1152
1406
|
return fail("no terminal to read keys from (/dev/tty)");
|
|
1153
1407
|
}
|
|
1154
|
-
const out =
|
|
1155
|
-
|
|
1156
|
-
|
|
1408
|
+
const out = process12.stderr;
|
|
1409
|
+
let resize;
|
|
1410
|
+
return {
|
|
1411
|
+
get columns() {
|
|
1412
|
+
return out.columns || 80;
|
|
1413
|
+
},
|
|
1414
|
+
get rows() {
|
|
1415
|
+
return out.rows || 24;
|
|
1416
|
+
},
|
|
1417
|
+
theme: { accent: role("accent", out), label: role("label", out), value: role("value", out), id: role("id", out) },
|
|
1418
|
+
write: (text) => void out.write(text),
|
|
1419
|
+
listen(onChunk, onResize) {
|
|
1420
|
+
resize = onResize;
|
|
1421
|
+
input.setRawMode(true);
|
|
1422
|
+
out.on("resize", onResize);
|
|
1423
|
+
input.on("data", (chunk) => onChunk(chunk.toString()));
|
|
1424
|
+
},
|
|
1425
|
+
close() {
|
|
1426
|
+
if (resize !== undefined)
|
|
1427
|
+
out.off("resize", resize);
|
|
1428
|
+
try {
|
|
1429
|
+
input.setRawMode(false);
|
|
1430
|
+
} finally {
|
|
1431
|
+
input.destroy();
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
};
|
|
1435
|
+
}
|
|
1436
|
+
async function select(rows, settings, terminal = openTerminal()) {
|
|
1437
|
+
const { theme } = terminal;
|
|
1438
|
+
let state = createState(rows, settings);
|
|
1157
1439
|
let preview = [];
|
|
1158
1440
|
let reserved = 0;
|
|
1159
1441
|
let previewTimer;
|
|
@@ -1162,7 +1444,9 @@ async function choose(lines, settings) {
|
|
|
1162
1444
|
let finish;
|
|
1163
1445
|
let restored = false;
|
|
1164
1446
|
function draw(clear = false) {
|
|
1165
|
-
|
|
1447
|
+
if (restored)
|
|
1448
|
+
return;
|
|
1449
|
+
const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
|
|
1166
1450
|
let frame = HIDE_CURSOR;
|
|
1167
1451
|
if (reserved !== layout.height || clear) {
|
|
1168
1452
|
frame += CLEAR_BELOW + `
|
|
@@ -1171,7 +1455,7 @@ async function choose(lines, settings) {
|
|
|
1171
1455
|
}
|
|
1172
1456
|
frame += `\r${render(state, layout, theme, preview).map((line) => `\x1B[2K${line}`).join(`
|
|
1173
1457
|
`)}${up(layout.height - 1)}\r\x1B[${caretColumn(state, layout)}G${SHOW_CURSOR}`;
|
|
1174
|
-
|
|
1458
|
+
terminal.write(frame);
|
|
1175
1459
|
}
|
|
1176
1460
|
function refreshPreview() {
|
|
1177
1461
|
const at = highlighted(state);
|
|
@@ -1187,9 +1471,9 @@ async function choose(lines, settings) {
|
|
|
1187
1471
|
}
|
|
1188
1472
|
const { signal } = previewing;
|
|
1189
1473
|
const template = settings.preview;
|
|
1190
|
-
const
|
|
1474
|
+
const row = state.rows[at];
|
|
1191
1475
|
async function show() {
|
|
1192
|
-
const shown = await runPreview(template,
|
|
1476
|
+
const shown = typeof template === "string" ? await runPreview(template, row.cells.join(" "), signal, row.hidden) : await previewOf(template, row.hidden, signal);
|
|
1193
1477
|
if (!signal.aborted) {
|
|
1194
1478
|
preview = shown;
|
|
1195
1479
|
draw();
|
|
@@ -1203,56 +1487,99 @@ async function choose(lines, settings) {
|
|
|
1203
1487
|
restored = true;
|
|
1204
1488
|
clearTimeout(previewTimer);
|
|
1205
1489
|
previewing.abort();
|
|
1206
|
-
|
|
1207
|
-
|
|
1490
|
+
terminal.write(`${CLEAR_BELOW}${PASTE_OFF}${SHOW_CURSOR}`);
|
|
1491
|
+
terminal.close();
|
|
1492
|
+
}
|
|
1493
|
+
const stop = () => {
|
|
1494
|
+
state = { ...state, done: "cancel" };
|
|
1495
|
+
finish?.();
|
|
1496
|
+
};
|
|
1497
|
+
const paste = { active: false };
|
|
1498
|
+
const { reload } = settings;
|
|
1499
|
+
const pending = [];
|
|
1500
|
+
let busy = false;
|
|
1501
|
+
let draining = false;
|
|
1502
|
+
async function reloadRows() {
|
|
1503
|
+
if (reload === undefined)
|
|
1504
|
+
return;
|
|
1505
|
+
busy = true;
|
|
1506
|
+
state = { ...state, status: "reloading" };
|
|
1507
|
+
draw();
|
|
1208
1508
|
try {
|
|
1209
|
-
|
|
1509
|
+
const next = await reload.run();
|
|
1510
|
+
state = { ...withRows(state, next.rows, next.header), status: "" };
|
|
1511
|
+
shownLine = undefined;
|
|
1512
|
+
} catch (error) {
|
|
1513
|
+
state = { ...state, status: `reload failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
1210
1514
|
} finally {
|
|
1211
|
-
|
|
1515
|
+
busy = false;
|
|
1212
1516
|
}
|
|
1213
1517
|
}
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1518
|
+
async function drain() {
|
|
1519
|
+
if (draining)
|
|
1520
|
+
return;
|
|
1521
|
+
draining = true;
|
|
1522
|
+
try {
|
|
1523
|
+
for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
|
|
1524
|
+
if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
|
|
1525
|
+
await reloadRows();
|
|
1526
|
+
else
|
|
1527
|
+
state = press(state, key);
|
|
1224
1528
|
}
|
|
1529
|
+
} finally {
|
|
1530
|
+
draining = false;
|
|
1531
|
+
}
|
|
1532
|
+
if (state.done !== undefined) {
|
|
1533
|
+
finish?.();
|
|
1534
|
+
return;
|
|
1225
1535
|
}
|
|
1226
1536
|
refreshPreview();
|
|
1227
1537
|
draw();
|
|
1228
1538
|
}
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1539
|
+
function onChunk(chunk) {
|
|
1540
|
+
const keys = parseKeys(chunk, paste, [...settings.expect ?? [], ...reload?.key === undefined ? [] : [reload.key]]);
|
|
1541
|
+
if (busy && keys.includes("cancel")) {
|
|
1542
|
+
stop();
|
|
1543
|
+
return;
|
|
1544
|
+
}
|
|
1545
|
+
pending.push(...keys);
|
|
1546
|
+
drain();
|
|
1547
|
+
}
|
|
1233
1548
|
const ended = new Promise((resolve) => {
|
|
1234
1549
|
finish = resolve;
|
|
1235
1550
|
});
|
|
1236
|
-
|
|
1551
|
+
process12.once("exit", restore);
|
|
1237
1552
|
for (const signal of SIGNALS)
|
|
1238
|
-
|
|
1553
|
+
process12.once(signal, stop);
|
|
1239
1554
|
try {
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
out.on("resize", onResize);
|
|
1243
|
-
input.on("data", onData);
|
|
1555
|
+
terminal.write(PASTE_ON);
|
|
1556
|
+
terminal.listen(onChunk, () => draw(true));
|
|
1244
1557
|
refreshPreview();
|
|
1245
1558
|
draw(true);
|
|
1559
|
+
if (reload?.onOpen === true) {
|
|
1560
|
+
pending.push(OPEN);
|
|
1561
|
+
drain();
|
|
1562
|
+
}
|
|
1246
1563
|
await ended;
|
|
1247
1564
|
} finally {
|
|
1248
1565
|
for (const signal of SIGNALS)
|
|
1249
|
-
|
|
1250
|
-
|
|
1566
|
+
process12.off(signal, stop);
|
|
1567
|
+
process12.off("exit", restore);
|
|
1251
1568
|
restore();
|
|
1252
1569
|
}
|
|
1253
|
-
return state.done === "accept" ? chosen(state) : undefined;
|
|
1570
|
+
return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
|
|
1571
|
+
}
|
|
1572
|
+
async function previewOf(preview, hidden, signal) {
|
|
1573
|
+
try {
|
|
1574
|
+
return previewLines(await preview(hidden, signal));
|
|
1575
|
+
} catch (error) {
|
|
1576
|
+
return [error instanceof Error ? error.message : String(error)];
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
async function choose(lines, settings) {
|
|
1580
|
+
const picked = await select(lines.map((line) => ({ hidden: [], cells: [line] })), settings);
|
|
1581
|
+
return picked?.rows.map((row) => row.cells[0]);
|
|
1254
1582
|
}
|
|
1255
|
-
|
|
1256
1583
|
// src/pick.ts
|
|
1257
1584
|
var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
|
|
1258
1585
|
|
|
@@ -1275,9 +1602,9 @@ async function main(args) {
|
|
|
1275
1602
|
const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
|
|
1276
1603
|
if (height === undefined)
|
|
1277
1604
|
badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
|
|
1278
|
-
if (!
|
|
1605
|
+
if (!process13.stderr.isTTY)
|
|
1279
1606
|
fail("pick draws on stderr and it is not a terminal");
|
|
1280
|
-
if (
|
|
1607
|
+
if (process13.stdin.isTTY)
|
|
1281
1608
|
badUsage("pipe the lines to pick on stdin");
|
|
1282
1609
|
const lines = (await Bun.stdin.text()).split(`
|
|
1283
1610
|
`).filter((line) => line !== "");
|
|
@@ -1286,9 +1613,9 @@ async function main(args) {
|
|
|
1286
1613
|
const picked = await choose(lines, { multi: values.multi === true, prompt: values.prompt ?? "> ", query: values.query ?? "", height, preview: values.preview });
|
|
1287
1614
|
if (picked === undefined)
|
|
1288
1615
|
return 1;
|
|
1289
|
-
|
|
1616
|
+
process13.stdout.write(`${picked.join(`
|
|
1290
1617
|
`)}
|
|
1291
1618
|
`);
|
|
1292
1619
|
return 0;
|
|
1293
1620
|
}
|
|
1294
|
-
|
|
1621
|
+
process13.exitCode = await runMain({ name: "pick", run: main });
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaynooo/cli-pick",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.0",
|
|
5
5
|
"description": "pick: a themed fuzzy selector, lines on stdin, the chosen one on stdout.",
|
|
6
6
|
"author": "Kaynooo <contact@kaynooo.fr>",
|
|
7
7
|
"license": "MIT",
|
|
@@ -35,6 +35,6 @@
|
|
|
35
35
|
"pick": "$npm_execpath src/pick.ts"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
|
-
"@kaynooo/cli-kit": "0.
|
|
38
|
+
"@kaynooo/cli-kit": "0.22.0"
|
|
39
39
|
}
|
|
40
40
|
}
|