@kaynooo/cli-pick 0.2.1 → 0.4.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 +2 -2
- package/dist/pick.js +562 -187
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @kaynooo/cli-pick
|
|
2
2
|
|
|
3
|
-
`pick` is a fuzzy selector in the colours of the other @kaynooo CLIs: lines on stdin, the chosen one on stdout. It is for a person at a terminal, not for a Claude Code session, which has no terminal to answer it.
|
|
3
|
+
`pick` is a fuzzy selector in the colours of the other @kaynooo CLIs: lines on stdin, the chosen one on stdout. It is for a person at a terminal, not for a Claude Code session, which has no terminal to answer it; without a terminal on stderr it prints the first line containing `--query` (case-insensitive, every one with `--multi`) and exits 1 when none does.
|
|
4
4
|
|
|
5
5
|
```sh
|
|
6
6
|
bun add -g @kaynooo/cli-pick
|
|
@@ -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,31 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/pick.ts
|
|
5
|
-
import
|
|
5
|
+
import process14 from "process";
|
|
6
6
|
// ../kit/src/args.ts
|
|
7
|
-
import
|
|
7
|
+
import process8 from "process";
|
|
8
8
|
import { parseArgs } from "util";
|
|
9
9
|
|
|
10
|
-
// ../kit/src/
|
|
10
|
+
// ../kit/src/mode.ts
|
|
11
11
|
import process2 from "process";
|
|
12
|
+
var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
|
|
13
|
+
var AGENT_VARIABLES = ["CLAUDECODE", "AI_AGENT"];
|
|
14
|
+
function isSet(value) {
|
|
15
|
+
return value !== undefined && value !== "" && value !== "0" && value.toLowerCase() !== "false";
|
|
16
|
+
}
|
|
17
|
+
function outputMode(stream = process2.stdout, env = process2.env) {
|
|
18
|
+
const chosen = env.KIT_MODE;
|
|
19
|
+
if (chosen !== undefined && MODES.has(chosen))
|
|
20
|
+
return chosen;
|
|
21
|
+
if (AGENT_VARIABLES.some((name) => isSet(env[name])))
|
|
22
|
+
return "agent";
|
|
23
|
+
if (stream.isTTY === true)
|
|
24
|
+
return "terminal";
|
|
25
|
+
return isSet(env.CI) ? "ci" : "pipe";
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// ../kit/src/style.ts
|
|
29
|
+
import process6 from "process";
|
|
12
30
|
|
|
13
31
|
// ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
|
|
14
32
|
function x(s) {
|
|
@@ -271,31 +289,229 @@ function le(i = {}) {
|
|
|
271
289
|
}
|
|
272
290
|
var t = le();
|
|
273
291
|
|
|
292
|
+
// ../kit/src/theme.ts
|
|
293
|
+
import { existsSync as existsSync2, readFileSync, statSync } from "fs";
|
|
294
|
+
import { homedir as homedir2 } from "os";
|
|
295
|
+
import { join as join3, resolve as resolve2 } from "path";
|
|
296
|
+
import process5 from "process";
|
|
297
|
+
|
|
298
|
+
// ../kit/src/config.ts
|
|
299
|
+
import { existsSync } from "fs";
|
|
300
|
+
import { dirname, join, resolve } from "path";
|
|
301
|
+
import process3 from "process";
|
|
302
|
+
function findUp(names, from = process3.cwd(), stop = () => false) {
|
|
303
|
+
const wanted = typeof names === "string" ? [names] : names;
|
|
304
|
+
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
305
|
+
const found = wanted.map((name) => join(dir, name)).find((path) => existsSync(path));
|
|
306
|
+
if (found !== undefined)
|
|
307
|
+
return found;
|
|
308
|
+
if (stop(dir) || dirname(dir) === dir)
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// ../kit/src/user-config.ts
|
|
314
|
+
import { homedir } from "os";
|
|
315
|
+
import { join as join2 } from "path";
|
|
316
|
+
import process4 from "process";
|
|
317
|
+
function configBase(where = {}) {
|
|
318
|
+
const xdg = where.xdg ?? (where.home === undefined ? process4.env.XDG_CONFIG_HOME : undefined);
|
|
319
|
+
return xdg !== undefined && xdg !== "" ? xdg : join2(where.home ?? homedir(), ".config");
|
|
320
|
+
}
|
|
321
|
+
function userConfigPath(bin, where = {}) {
|
|
322
|
+
return join2(configBase(where), "kaynooo-cli", `${bin}.json`);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ../kit/src/theme.ts
|
|
326
|
+
var DEFAULT = {
|
|
327
|
+
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" },
|
|
328
|
+
glyphs: { ok: "\u2713", warn: "\u25B2", problem: "\u2717", note: "\u203A", passed: "\u2713", failed: "\u2717", running: "\u25CF", queued: "\u25CB", skipped: "-", bar: "\u2501" },
|
|
329
|
+
accents: ["cyan", "magenta", "green", "blue", "yellow", "redBright"],
|
|
330
|
+
bins: {}
|
|
331
|
+
};
|
|
332
|
+
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" };
|
|
333
|
+
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" };
|
|
334
|
+
var ASCII = { ok: "+", warn: "!", problem: "x", note: ">", passed: "+", failed: "x", running: "*", queued: "o", skipped: "-", bar: "#" };
|
|
335
|
+
var PRESETS = {
|
|
336
|
+
default: {},
|
|
337
|
+
"high-contrast": { colors: BRIGHT, accents: ["cyanBright", "magentaBright", "greenBright", "blueBright", "yellowBright", "redBright"] },
|
|
338
|
+
mono: { colors: MONO, accents: ["bold"] },
|
|
339
|
+
ascii: { glyphs: ASCII }
|
|
340
|
+
};
|
|
341
|
+
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"]);
|
|
342
|
+
var HEX = /^#[0-9a-f]{6}$/i;
|
|
343
|
+
var CONTROL = /\p{Cc}/u;
|
|
344
|
+
var MAX_FILE_BYTES = 64 * 1024;
|
|
345
|
+
var SPACES = /\s+/;
|
|
346
|
+
function isColorSpec(spec) {
|
|
347
|
+
if (typeof spec === "number")
|
|
348
|
+
return Number.isInteger(spec) && spec >= 0 && spec <= 255;
|
|
349
|
+
return typeof spec === "string" && spec.trim() !== "" && spec.trim().split(SPACES).every((token) => STYLES.has(token) || HEX.test(token));
|
|
350
|
+
}
|
|
351
|
+
var CUBE = [0, 95, 135, 175, 215, 255];
|
|
352
|
+
function cubeLevel(channel) {
|
|
353
|
+
return CUBE.reduce((best, value, level) => Math.abs(value - channel) < Math.abs(CUBE[best] - channel) ? level : best, 0);
|
|
354
|
+
}
|
|
355
|
+
function nearest256(hex) {
|
|
356
|
+
const rgb = [1, 3, 5].map((at) => Number.parseInt(hex.slice(at, at + 2), 16));
|
|
357
|
+
const levels = rgb.map(cubeLevel);
|
|
358
|
+
const cube = levels.map((level) => CUBE[level]);
|
|
359
|
+
const grey = Math.min(23, Math.max(0, Math.round((rgb.reduce((sum, channel) => sum + channel, 0) / 3 - 8) / 10)));
|
|
360
|
+
const greyValue = 8 + grey * 10;
|
|
361
|
+
const distance = (colour) => colour.reduce((sum, channel, at) => sum + (channel - rgb[at]) ** 2, 0);
|
|
362
|
+
return distance([greyValue, greyValue, greyValue]) < distance(cube) ? 232 + grey : 16 + 36 * levels[0] + 6 * levels[1] + levels[2];
|
|
363
|
+
}
|
|
364
|
+
function hasTrueColor(env) {
|
|
365
|
+
return env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
366
|
+
}
|
|
367
|
+
function tinted(colors, spec, env = process5.env) {
|
|
368
|
+
if (typeof spec === "number")
|
|
369
|
+
return colors.ansi256(spec);
|
|
370
|
+
return spec.trim().split(SPACES).reduce((chain, token) => {
|
|
371
|
+
if (HEX.test(token))
|
|
372
|
+
return hasTrueColor(env) ? chain.hex(token) : chain.ansi256(nearest256(token));
|
|
373
|
+
return chain[token] ?? chain;
|
|
374
|
+
}, colors);
|
|
375
|
+
}
|
|
376
|
+
function isRecord(value) {
|
|
377
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
378
|
+
}
|
|
379
|
+
function readThemeFile(path, warn) {
|
|
380
|
+
try {
|
|
381
|
+
const stat = statSync(path, { throwIfNoEntry: false });
|
|
382
|
+
if (stat === undefined)
|
|
383
|
+
return;
|
|
384
|
+
if (!stat.isFile() || stat.size > MAX_FILE_BYTES) {
|
|
385
|
+
warn(`${path} is not a regular file under ${MAX_FILE_BYTES / 1024} KiB, theme ignored`);
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
389
|
+
if (isRecord(parsed))
|
|
390
|
+
return parsed;
|
|
391
|
+
warn(`${path} is not a JSON object, theme ignored`);
|
|
392
|
+
} catch (error) {
|
|
393
|
+
warn(`${path} does not parse (${error instanceof Error ? error.message : String(error)}), theme ignored`);
|
|
394
|
+
}
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
function applyPreset(theme, name, warn, where) {
|
|
398
|
+
if (name === undefined)
|
|
399
|
+
return;
|
|
400
|
+
if (typeof name !== "string" || !Object.hasOwn(PRESETS, name)) {
|
|
401
|
+
warn(`${where}: no preset ${String(name)}, one of ${Object.keys(PRESETS).join(", ")}`);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
const preset = PRESETS[name];
|
|
405
|
+
Object.assign(theme.colors, preset.colors);
|
|
406
|
+
Object.assign(theme.glyphs, preset.glyphs);
|
|
407
|
+
if (preset.accents !== undefined)
|
|
408
|
+
theme.accents = [...preset.accents];
|
|
409
|
+
return name;
|
|
410
|
+
}
|
|
411
|
+
function applyFile(theme, file, where, warn) {
|
|
412
|
+
if (isRecord(file.colors)) {
|
|
413
|
+
for (const [key, value] of Object.entries(file.colors)) {
|
|
414
|
+
if (!Object.hasOwn(DEFAULT.colors, key))
|
|
415
|
+
warn(`${where}: no colour ${key}, one of ${Object.keys(DEFAULT.colors).join(", ")}`);
|
|
416
|
+
else if (!isColorSpec(value))
|
|
417
|
+
warn(`${where}: colour ${key} is not an ANSI name, \`#rrggbb\` or a number up to 255`);
|
|
418
|
+
else
|
|
419
|
+
theme.colors[key] = value;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
if (isRecord(file.glyphs)) {
|
|
423
|
+
for (const [key, value] of Object.entries(file.glyphs)) {
|
|
424
|
+
if (!Object.hasOwn(DEFAULT.glyphs, key))
|
|
425
|
+
warn(`${where}: no glyph ${key}, one of ${Object.keys(DEFAULT.glyphs).join(", ")}`);
|
|
426
|
+
else if (typeof value !== "string" || CONTROL.test(value) || Bun.stringWidth(value) !== 1)
|
|
427
|
+
warn(`${where}: glyph ${key} must be one visible character wide, with no control character`);
|
|
428
|
+
else
|
|
429
|
+
theme.glyphs[key] = value;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
if (Array.isArray(file.accents) && file.accents.length > 0 && file.accents.every(isColorSpec))
|
|
433
|
+
theme.accents = [...file.accents];
|
|
434
|
+
else if (file.accents !== undefined)
|
|
435
|
+
warn(`${where}: accents must be a non-empty list of colours`);
|
|
436
|
+
if (isRecord(file.bins)) {
|
|
437
|
+
for (const [bin, value] of Object.entries(file.bins)) {
|
|
438
|
+
if (isColorSpec(value))
|
|
439
|
+
theme.bins[bin] = value;
|
|
440
|
+
else
|
|
441
|
+
warn(`${where}: bin ${bin} has no valid colour`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
function endsWalk(home) {
|
|
446
|
+
return (dir) => dir === resolve2(home) || existsSync2(join3(dir, ".git"));
|
|
447
|
+
}
|
|
448
|
+
var warned = new Set;
|
|
449
|
+
function warnOnce(message) {
|
|
450
|
+
if (warned.has(message))
|
|
451
|
+
return;
|
|
452
|
+
warned.add(message);
|
|
453
|
+
console.error(`warning: theme ${message}`);
|
|
454
|
+
}
|
|
455
|
+
function isPath(chosen) {
|
|
456
|
+
return chosen.includes("/") || chosen.endsWith(".json");
|
|
457
|
+
}
|
|
458
|
+
function loadTheme({ env = process5.env, from = process5.cwd(), home = homedir2(), warn = warnOnce } = {}) {
|
|
459
|
+
const theme = { colors: { ...DEFAULT.colors }, glyphs: { ...DEFAULT.glyphs }, accents: [...DEFAULT.accents], bins: Object.create(null) };
|
|
460
|
+
const sources = [];
|
|
461
|
+
const chosen = env.KIT_THEME ?? "";
|
|
462
|
+
const wanted = chosen === "" ? [userConfigPath("theme", { home, xdg: env.XDG_CONFIG_HOME }), findUp(join3(".kaynooo", "theme.json"), from, endsWalk(home))] : [];
|
|
463
|
+
if (isPath(chosen))
|
|
464
|
+
wanted.push(resolve2(from, chosen));
|
|
465
|
+
const files = [];
|
|
466
|
+
for (const path of wanted) {
|
|
467
|
+
const file = path === undefined ? undefined : readThemeFile(path, warn);
|
|
468
|
+
if (path !== undefined && file !== undefined)
|
|
469
|
+
files.push({ path, file });
|
|
470
|
+
}
|
|
471
|
+
let preset = "default";
|
|
472
|
+
if (chosen !== "" && !isPath(chosen)) {
|
|
473
|
+
preset = applyPreset(theme, chosen, warn, "KIT_THEME") ?? preset;
|
|
474
|
+
} else {
|
|
475
|
+
const named = files.findLast(({ file }) => file.preset !== undefined);
|
|
476
|
+
if (named !== undefined)
|
|
477
|
+
preset = applyPreset(theme, named.file.preset, warn, named.path) ?? preset;
|
|
478
|
+
}
|
|
479
|
+
for (const { path, file } of files) {
|
|
480
|
+
applyFile(theme, file, path, warn);
|
|
481
|
+
sources.push(path);
|
|
482
|
+
}
|
|
483
|
+
return { theme, sources, preset };
|
|
484
|
+
}
|
|
485
|
+
var current;
|
|
486
|
+
var currentKey = "";
|
|
487
|
+
function activeTheme() {
|
|
488
|
+
const key = `${process5.cwd()}\x00${process5.env.KIT_THEME ?? ""}\x00${process5.env.XDG_CONFIG_HOME ?? ""}`;
|
|
489
|
+
if (current === undefined || key !== currentKey) {
|
|
490
|
+
current = loadTheme();
|
|
491
|
+
currentKey = key;
|
|
492
|
+
}
|
|
493
|
+
return current;
|
|
494
|
+
}
|
|
495
|
+
|
|
274
496
|
// ../kit/src/style.ts
|
|
275
|
-
function takesControlCodes(stream, env =
|
|
276
|
-
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
|
|
497
|
+
function takesControlCodes(stream, env = process6.env) {
|
|
498
|
+
return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
|
|
277
499
|
}
|
|
278
|
-
function paint(stream, env =
|
|
500
|
+
function paint(stream, env = process6.env) {
|
|
279
501
|
return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
|
|
280
502
|
}
|
|
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 }
|
|
503
|
+
function role(name, stream, env = process6.env) {
|
|
504
|
+
const colors = paint(stream, env);
|
|
505
|
+
return takesControlCodes(stream, env) ? tinted(colors, activeTheme().theme.colors[name], env) : colors;
|
|
506
|
+
}
|
|
507
|
+
var STATUS_WORDS = {
|
|
508
|
+
passed: ["passed", "success", "succeeded", "ok"],
|
|
509
|
+
failed: ["failed", "failure", "error", "errored"],
|
|
510
|
+
running: ["running", "in_progress", "started", "holding"],
|
|
511
|
+
queued: ["queued", "waiting", "pending", "created", "blocked", "scheduled"],
|
|
512
|
+
skipped: ["skipped", "cancelled", "canceled", "manual"]
|
|
297
513
|
};
|
|
298
|
-
var STATUS_OF = new Map(Object.entries(
|
|
514
|
+
var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
|
|
299
515
|
|
|
300
516
|
// ../kit/src/format.ts
|
|
301
517
|
function upTo(text, separator) {
|
|
@@ -305,27 +521,27 @@ function upTo(text, separator) {
|
|
|
305
521
|
var ESCAPE = String.fromCharCode(27);
|
|
306
522
|
|
|
307
523
|
// ../kit/src/help.ts
|
|
308
|
-
import
|
|
524
|
+
import process7 from "process";
|
|
309
525
|
var OPTIONAL = /\[[^\]]+\]/g;
|
|
310
526
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
311
527
|
var FULL_STOP = /\.$/;
|
|
312
|
-
function usageLine(usage, colors = paint(
|
|
528
|
+
function usageLine(usage, colors = paint(process7.stdout)) {
|
|
313
529
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
314
530
|
}
|
|
315
|
-
function helpText(usage, options, colors = paint(
|
|
531
|
+
function helpText(usage, options, colors = paint(process7.stdout), { examples = [], replaces, exits = [] } = {}) {
|
|
316
532
|
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
|
|
317
533
|
`);
|
|
318
534
|
}
|
|
319
|
-
function exitRows(exits, colors = paint(
|
|
535
|
+
function exitRows(exits, colors = paint(process7.stdout)) {
|
|
320
536
|
if (exits.length === 0)
|
|
321
537
|
return [];
|
|
322
538
|
const width = Math.max(...exits.map(([code]) => String(code).length));
|
|
323
539
|
return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
|
|
324
540
|
}
|
|
325
|
-
function replacesRows(replaces, colors = paint(
|
|
326
|
-
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
541
|
+
function replacesRows(replaces, colors = paint(process7.stdout)) {
|
|
542
|
+
return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
327
543
|
}
|
|
328
|
-
function wantsHelpJson(env =
|
|
544
|
+
function wantsHelpJson(env = process7.env) {
|
|
329
545
|
return env.KIT_HELP === "json";
|
|
330
546
|
}
|
|
331
547
|
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
@@ -344,12 +560,12 @@ function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
|
344
560
|
...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
|
|
345
561
|
};
|
|
346
562
|
}
|
|
347
|
-
function exampleRows(examples, colors = paint(
|
|
348
|
-
if (examples.length === 0)
|
|
563
|
+
function exampleRows(examples, colors = paint(process7.stdout)) {
|
|
564
|
+
if (examples.length === 0 || outputMode() === "agent")
|
|
349
565
|
return [];
|
|
350
566
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
351
567
|
}
|
|
352
|
-
function optionRows(options, colors = paint(
|
|
568
|
+
function optionRows(options, colors = paint(process7.stdout)) {
|
|
353
569
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
354
570
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
355
571
|
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
@@ -426,7 +642,7 @@ var OUTPUT_OPTIONS = {
|
|
|
426
642
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
427
643
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
428
644
|
};
|
|
429
|
-
function applyOutput(color, plain, env =
|
|
645
|
+
function applyOutput(color, plain, env = process8.env) {
|
|
430
646
|
const when = plain === true ? "never" : color ?? "auto";
|
|
431
647
|
if (when === "auto")
|
|
432
648
|
return;
|
|
@@ -601,15 +817,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
601
817
|
var RESET_STYLE = `${ESC}[0m`;
|
|
602
818
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
603
819
|
// ../kit/src/cli.ts
|
|
604
|
-
import { readFileSync, realpathSync } from "fs";
|
|
605
|
-
import { dirname as
|
|
606
|
-
import
|
|
820
|
+
import { readFileSync as readFileSync2, realpathSync } from "fs";
|
|
821
|
+
import { dirname as dirname3, join as join5 } from "path";
|
|
822
|
+
import process10 from "process";
|
|
607
823
|
|
|
608
824
|
// ../kit/src/usage.ts
|
|
609
825
|
import { appendFileSync, mkdirSync } from "fs";
|
|
610
|
-
import { homedir } from "os";
|
|
611
|
-
import { dirname, isAbsolute, join } from "path";
|
|
612
|
-
import
|
|
826
|
+
import { homedir as homedir3 } from "os";
|
|
827
|
+
import { dirname as dirname2, isAbsolute, join as join4 } from "path";
|
|
828
|
+
import process9 from "process";
|
|
613
829
|
|
|
614
830
|
// ../kit/src/logs.ts
|
|
615
831
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -623,14 +839,14 @@ var usageError;
|
|
|
623
839
|
function noteUsageError(message) {
|
|
624
840
|
usageError = message;
|
|
625
841
|
}
|
|
626
|
-
function stateHome(env =
|
|
842
|
+
function stateHome(env = process9.env) {
|
|
627
843
|
const dir = env.XDG_STATE_HOME;
|
|
628
|
-
return dir !== undefined && isAbsolute(dir) ? dir :
|
|
844
|
+
return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
|
|
629
845
|
}
|
|
630
|
-
function usagePath(env =
|
|
631
|
-
return
|
|
846
|
+
function usagePath(env = process9.env) {
|
|
847
|
+
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
632
848
|
}
|
|
633
|
-
function usageRecorded(env =
|
|
849
|
+
function usageRecorded(env = process9.env) {
|
|
634
850
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
635
851
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
636
852
|
}
|
|
@@ -644,12 +860,12 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
644
860
|
usageError = undefined;
|
|
645
861
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
646
862
|
}
|
|
647
|
-
function recordUsage(entry, env =
|
|
863
|
+
function recordUsage(entry, env = process9.env) {
|
|
648
864
|
if (!usageRecorded(env))
|
|
649
865
|
return;
|
|
650
866
|
try {
|
|
651
867
|
const path = usagePath(env);
|
|
652
|
-
mkdirSync(
|
|
868
|
+
mkdirSync(dirname2(path), { recursive: true, mode: 448 });
|
|
653
869
|
appendFileSync(path, `${JSON.stringify(entry)}
|
|
654
870
|
`, { mode: 384 });
|
|
655
871
|
} catch {}
|
|
@@ -662,8 +878,8 @@ var LEVEL_OPTIONS = {
|
|
|
662
878
|
};
|
|
663
879
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
664
880
|
function printError(prefix, message, hint, cause) {
|
|
665
|
-
const colors = paint(
|
|
666
|
-
const styled = takesControlCodes(
|
|
881
|
+
const colors = paint(process10.stderr);
|
|
882
|
+
const styled = takesControlCodes(process10.stderr);
|
|
667
883
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
668
884
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
669
885
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -682,7 +898,7 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
|
|
|
682
898
|
const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
|
|
683
899
|
const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
|
|
684
900
|
const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
|
|
685
|
-
if (error instanceof
|
|
901
|
+
if (error instanceof Exit && error.code === 2)
|
|
686
902
|
noteUsageError(error.message);
|
|
687
903
|
const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
|
|
688
904
|
report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
|
|
@@ -746,17 +962,17 @@ async function printCandidates(found) {
|
|
|
746
962
|
return 0;
|
|
747
963
|
}
|
|
748
964
|
function packageVersion(entry = Bun.main) {
|
|
749
|
-
for (let dir =
|
|
965
|
+
for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
|
|
750
966
|
try {
|
|
751
|
-
const { version } = JSON.parse(
|
|
967
|
+
const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
|
|
752
968
|
if (typeof version === "string")
|
|
753
969
|
return version;
|
|
754
970
|
} catch {}
|
|
755
|
-
if (
|
|
971
|
+
if (dirname3(dir) === dir)
|
|
756
972
|
return "0.0.0";
|
|
757
973
|
}
|
|
758
974
|
}
|
|
759
|
-
async function runMain({ name, version, run, redact, usage }, argv =
|
|
975
|
+
async function runMain({ name, version, run, redact, usage }, argv = process10.argv.slice(2)) {
|
|
760
976
|
if (argv[0] === COMPLETE)
|
|
761
977
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
762
978
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
@@ -782,62 +998,7 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
|
|
|
782
998
|
var {Glob } = globalThis.Bun;
|
|
783
999
|
var SESSION_FILES = new Glob("*.json");
|
|
784
1000
|
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
|
|
1001
|
+
// ../kit/src/picker/score.ts
|
|
841
1002
|
var MATCH = 16;
|
|
842
1003
|
var CONSECUTIVE = 12;
|
|
843
1004
|
var BOUNDARY = 10;
|
|
@@ -920,10 +1081,13 @@ function rank(query, lines) {
|
|
|
920
1081
|
return found.sort((a, b) => b.score - a.score || lines[a.index].length - lines[b.index].length || a.index - b.index);
|
|
921
1082
|
}
|
|
922
1083
|
|
|
923
|
-
// src/state.ts
|
|
1084
|
+
// ../kit/src/picker/state.ts
|
|
924
1085
|
var ANSI2 = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
|
|
925
|
-
var
|
|
1086
|
+
var CONTROL2 = /[\x00-\x1F\x7F-\x9F]/g;
|
|
926
1087
|
var IS_CONTROL = /[\x00-\x1F\x7F-\x9F]/;
|
|
1088
|
+
var SGR = /^\x1B\[[0-9;]*m$/;
|
|
1089
|
+
var RESET = /^\x1B\[0?m$/;
|
|
1090
|
+
var COLUMN_GAP = 2;
|
|
927
1091
|
var PASTE_START = "\x1B[200~";
|
|
928
1092
|
var PASTE_END = "\x1B[201~";
|
|
929
1093
|
var LAST_WORD = /\S*\s*$/;
|
|
@@ -945,12 +1109,60 @@ var KEYS = {
|
|
|
945
1109
|
"\x17": "word",
|
|
946
1110
|
"\t": "tab"
|
|
947
1111
|
};
|
|
948
|
-
function
|
|
949
|
-
return
|
|
1112
|
+
function repeat(value, count) {
|
|
1113
|
+
return Array.from({ length: count }).fill(value);
|
|
1114
|
+
}
|
|
1115
|
+
function styled(line) {
|
|
1116
|
+
let text = "";
|
|
1117
|
+
const styles = [];
|
|
1118
|
+
let active = "";
|
|
1119
|
+
let colored = false;
|
|
1120
|
+
let last = 0;
|
|
1121
|
+
function add(chunk) {
|
|
1122
|
+
const flat = chunk.replace(CONTROL2, " ");
|
|
1123
|
+
text += flat;
|
|
1124
|
+
colored ||= active !== "" && flat !== "";
|
|
1125
|
+
styles.push(...repeat(active, flat.length));
|
|
1126
|
+
}
|
|
1127
|
+
for (const found of line.matchAll(ANSI2)) {
|
|
1128
|
+
add(line.slice(last, found.index));
|
|
1129
|
+
last = found.index + found[0].length;
|
|
1130
|
+
if (SGR.test(found[0]))
|
|
1131
|
+
active = RESET.test(found[0]) ? "" : active + found[0];
|
|
1132
|
+
}
|
|
1133
|
+
add(line.slice(last));
|
|
1134
|
+
return { text, styles: colored ? styles : undefined };
|
|
1135
|
+
}
|
|
1136
|
+
function lay(rows, searched) {
|
|
1137
|
+
const parsed = rows.map((row) => row.cells.map(styled));
|
|
1138
|
+
const widths = (parsed[0] ?? []).map((_, column) => Math.max(...parsed.map((cells) => Bun.stringWidth(cells[column]?.text ?? ""))));
|
|
1139
|
+
return parsed.map((cells) => {
|
|
1140
|
+
let text = "";
|
|
1141
|
+
const styles = [];
|
|
1142
|
+
let colored = false;
|
|
1143
|
+
let searchEnd = 0;
|
|
1144
|
+
for (const [column, cell] of cells.entries()) {
|
|
1145
|
+
const last = column === cells.length - 1;
|
|
1146
|
+
const shown = cells.length > 1 && last ? cell.text.trimEnd() : cell.text;
|
|
1147
|
+
text += shown;
|
|
1148
|
+
colored ||= cell.styles !== undefined;
|
|
1149
|
+
styles.push(...cell.styles?.slice(0, shown.length) ?? repeat("", shown.length));
|
|
1150
|
+
if (column < searched)
|
|
1151
|
+
searchEnd = cells.length > 1 ? text.trimEnd().length : text.length;
|
|
1152
|
+
if (!last) {
|
|
1153
|
+
const pad = widths[column] - Bun.stringWidth(cell.text) + COLUMN_GAP;
|
|
1154
|
+
text += " ".repeat(pad);
|
|
1155
|
+
styles.push(...repeat("", pad));
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
return { text, styles: colored ? styles : undefined, searchable: text.slice(0, searchEnd) };
|
|
1159
|
+
});
|
|
950
1160
|
}
|
|
951
|
-
function parseKeys(input, paste = { active: false }) {
|
|
1161
|
+
function parseKeys(input, paste = { active: false }, ctrls = []) {
|
|
1162
|
+
const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
|
|
952
1163
|
return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
|
|
953
|
-
const
|
|
1164
|
+
const named = codes.get(sequence);
|
|
1165
|
+
const key = named === undefined ? KEYS[sequence] : { ctrl: named };
|
|
954
1166
|
if (sequence === PASTE_START || sequence === PASTE_END) {
|
|
955
1167
|
paste.active = sequence === PASTE_START;
|
|
956
1168
|
return [];
|
|
@@ -963,12 +1175,19 @@ function parseKeys(input, paste = { active: false }) {
|
|
|
963
1175
|
return IS_CONTROL.test(sequence) || sequence.startsWith("\x1B") ? [] : [{ text: sequence }];
|
|
964
1176
|
});
|
|
965
1177
|
}
|
|
966
|
-
function createState(
|
|
967
|
-
const
|
|
968
|
-
return
|
|
1178
|
+
function createState(rows, { multi = false, prompt = "> ", query = "", header = "", expect = [], searched = Number.POSITIVE_INFINITY } = {}) {
|
|
1179
|
+
const state = { rows: [], items: [], styles: [], searchable: [], searched, header, expect, key: "", status: "", query, matches: [], cursor: 0, marked: new Set, multi, prompt, done: undefined };
|
|
1180
|
+
return withRows(state, rows);
|
|
1181
|
+
}
|
|
1182
|
+
function withRows(state, rows, header = state.header) {
|
|
1183
|
+
const cells = rows.map((row) => typeof row === "string" ? { hidden: [], cells: [row] } : row);
|
|
1184
|
+
const laid = lay(cells, state.searched);
|
|
1185
|
+
const searchable = laid.map((row) => row.searchable);
|
|
1186
|
+
const matches = rank(state.query, searchable);
|
|
1187
|
+
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
1188
|
}
|
|
970
1189
|
function withQuery(state, query) {
|
|
971
|
-
return { ...state, query, matches: rank(query, state.
|
|
1190
|
+
return { ...state, query, matches: rank(query, state.searchable), cursor: 0 };
|
|
972
1191
|
}
|
|
973
1192
|
function move(state, by) {
|
|
974
1193
|
return { ...state, cursor: Math.max(0, Math.min(state.matches.length - 1, state.cursor + by)) };
|
|
@@ -979,8 +1198,11 @@ function highlighted(state) {
|
|
|
979
1198
|
function press(state, key) {
|
|
980
1199
|
if (state.done !== undefined)
|
|
981
1200
|
return state;
|
|
982
|
-
if (typeof key === "object")
|
|
983
|
-
|
|
1201
|
+
if (typeof key === "object") {
|
|
1202
|
+
if ("text" in key)
|
|
1203
|
+
return withQuery(state, state.query + key.text);
|
|
1204
|
+
return state.expect.includes(key.ctrl) ? { ...state, done: "accept", key: key.ctrl } : state;
|
|
1205
|
+
}
|
|
984
1206
|
switch (key) {
|
|
985
1207
|
case "up":
|
|
986
1208
|
return move(state, -1);
|
|
@@ -1009,31 +1231,87 @@ function press(state, key) {
|
|
|
1009
1231
|
}
|
|
1010
1232
|
function chosen(state) {
|
|
1011
1233
|
if (state.marked.size > 0)
|
|
1012
|
-
return state.
|
|
1234
|
+
return state.rows.filter((_, index) => state.marked.has(index));
|
|
1013
1235
|
const at = highlighted(state);
|
|
1014
|
-
return at === undefined ? [] : [state.
|
|
1236
|
+
return at === undefined ? [] : [state.rows[at]];
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
// ../kit/src/picker/terminal.ts
|
|
1240
|
+
import { openSync } from "fs";
|
|
1241
|
+
import process13 from "process";
|
|
1242
|
+
import tty from "tty";
|
|
1243
|
+
|
|
1244
|
+
// ../kit/src/picker/preview.ts
|
|
1245
|
+
import process12 from "process";
|
|
1246
|
+
|
|
1247
|
+
// ../kit/src/shell.ts
|
|
1248
|
+
var SEPARATORS = new Set([`
|
|
1249
|
+
`, ";", "|"]);
|
|
1250
|
+
var PLAIN_BREAKERS = new Set(["<", ">", "(", ")", "&", "|"]);
|
|
1251
|
+
var GLOB_CHARS = new Set(["*", "?", "["]);
|
|
1252
|
+
var COMMENT_PREFIXES = new Set([";", "&", "|", "(", ")"]);
|
|
1253
|
+
var SAFE_WORD = /^[\w@%+=:,./-]+$/;
|
|
1254
|
+
var DOUBLE_QUOTED_ESCAPES = new Set(["$", "`", '"', "\\"]);
|
|
1255
|
+
var KEYWORDS = new Set(["then", "do", "else", "if", "elif", "while", "until", "!", "{", "}"]);
|
|
1256
|
+
var SHELLS = new Set(["sh", "bash", "zsh", "dash", "ash", "ksh", "fish", "csh", "tcsh", "nu", "xonsh", "elvish", "pwsh", "powershell"]);
|
|
1257
|
+
var SCANNED_PROGRAMS = new Set(["su", "runuser", "flock"]);
|
|
1258
|
+
var COMMAND_STRING_PROGRAMS = new Set([...SHELLS, ...SCANNED_PROGRAMS]);
|
|
1259
|
+
var POWERSHELL = new Set(["pwsh", "powershell"]);
|
|
1260
|
+
var SHELL_VALUE_OPTIONS = new Set(["-o", "-O", "--rcfile", "--init-file"]);
|
|
1261
|
+
var FISH_VALUE_OPTIONS = new Set(["-C", "--init-command"]);
|
|
1262
|
+
var PRINTERS = new Set(["echo", "printf"]);
|
|
1263
|
+
var FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
1264
|
+
function wrapper(short = "", long = [], operands = 0, runsString = false) {
|
|
1265
|
+
return { short, long, operands, runsString };
|
|
1266
|
+
}
|
|
1267
|
+
var WRAPPERS = new Map([
|
|
1268
|
+
["command", wrapper()],
|
|
1269
|
+
["builtin", wrapper()],
|
|
1270
|
+
["nohup", wrapper()],
|
|
1271
|
+
["setsid", wrapper()],
|
|
1272
|
+
["busybox", wrapper()],
|
|
1273
|
+
["exec", wrapper("a")],
|
|
1274
|
+
["time", wrapper("fo", ["--format", "--output"])],
|
|
1275
|
+
["env", wrapper("uCS", ["--unset", "--chdir", "--split-string", "--argv0"])],
|
|
1276
|
+
["sudo", wrapper("ughpCTrtUDR", ["--user", "--group", "--host", "--prompt", "--close-from", "--command-timeout", "--role", "--type", "--other-user", "--chdir", "--chroot"])],
|
|
1277
|
+
["doas", wrapper("uC")],
|
|
1278
|
+
["timeout", wrapper("sk", ["--signal", "--kill-after"], 1)],
|
|
1279
|
+
["nice", wrapper("n", ["--adjustment"])],
|
|
1280
|
+
["ionice", wrapper("cnpPu", ["--class", "--classdata", "--pid", "--pgid", "--uid"])],
|
|
1281
|
+
["stdbuf", wrapper("ioe", ["--input", "--output", "--error"])],
|
|
1282
|
+
["chroot", wrapper("", ["--userspec", "--groups"], 1)],
|
|
1283
|
+
["watch", wrapper("n", ["--interval"], 0, true)],
|
|
1284
|
+
["flock", wrapper("wE", ["--timeout", "--conflict-exit-code"], 1)],
|
|
1285
|
+
["parallel", wrapper("jnNSaIPlLdTsC", ["--jobs", "--max-args", "--max-replace-args", "--sshlogin", "--arg-file", "--delimiter", "--colsep"], 0, true)],
|
|
1286
|
+
["unbuffer", wrapper()],
|
|
1287
|
+
["systemd-run", wrapper("puEMH", ["--property", "--unit", "--description", "--slice", "--setenv", "--machine", "--host", "--uid", "--gid", "--working-directory", "--nice", "--service-type"])],
|
|
1288
|
+
["xargs", wrapper("IndsEaPL", ["--max-args", "--max-procs", "--max-chars", "--delimiter", "--arg-file", "--eof", "--max-lines", "--process-slot-var"])]
|
|
1289
|
+
]);
|
|
1290
|
+
function shellQuote(word) {
|
|
1291
|
+
return SAFE_WORD.test(word) && !word.startsWith("=") ? word : `'${word.replaceAll("'", "'\\''")}'`;
|
|
1015
1292
|
}
|
|
1016
1293
|
|
|
1017
|
-
// src/preview.ts
|
|
1294
|
+
// ../kit/src/picker/preview.ts
|
|
1018
1295
|
var PREVIEW_BYTES = 64 * 1024;
|
|
1019
1296
|
var PREVIEW_LINES = 200;
|
|
1020
1297
|
var PREVIEW_TIMEOUT_MS = 3000;
|
|
1021
|
-
|
|
1022
|
-
|
|
1298
|
+
var PLACEHOLDER = /\{([1-9]\d*)?\}/g;
|
|
1299
|
+
function previewCommand(template, line, hidden = []) {
|
|
1300
|
+
return template.replace(PLACEHOLDER, (_, field) => shellQuote(field === undefined ? line : hidden[Number(field) - 1] ?? ""));
|
|
1023
1301
|
}
|
|
1024
1302
|
function previewLines(output) {
|
|
1025
1303
|
const lines = output.split(`
|
|
1026
1304
|
`);
|
|
1027
1305
|
if (lines.at(-1) === "")
|
|
1028
1306
|
lines.pop();
|
|
1029
|
-
return lines.slice(0, PREVIEW_LINES)
|
|
1307
|
+
return lines.slice(0, PREVIEW_LINES);
|
|
1030
1308
|
}
|
|
1031
|
-
async function runPreview(template, line, signal) {
|
|
1309
|
+
async function runPreview(template, line, signal, hidden = []) {
|
|
1032
1310
|
const proc = Bun.spawn(["sh", "-c", `exec 2>&1
|
|
1033
|
-
${previewCommand(template, line)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
|
|
1311
|
+
${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
|
|
1034
1312
|
const stop = () => {
|
|
1035
1313
|
try {
|
|
1036
|
-
|
|
1314
|
+
process12.kill(-proc.pid, "SIGKILL");
|
|
1037
1315
|
} catch {
|
|
1038
1316
|
proc.kill();
|
|
1039
1317
|
}
|
|
@@ -1058,9 +1336,12 @@ ${previewCommand(template, line)}`], { stdin: "ignore", stdout: "pipe", stderr:
|
|
|
1058
1336
|
return signal.aborted ? [] : previewLines(Buffer.concat(chunks).subarray(0, PREVIEW_BYTES).toString());
|
|
1059
1337
|
}
|
|
1060
1338
|
|
|
1061
|
-
// src/view.ts
|
|
1339
|
+
// ../kit/src/picker/view.ts
|
|
1062
1340
|
var MIN_HEIGHT = 4;
|
|
1063
1341
|
var PREVIEW_MIN_COLUMNS = 80;
|
|
1342
|
+
var PREVIEW_MIN_ROWS = 10;
|
|
1343
|
+
var PREVIEW_SHARE = 0.4;
|
|
1344
|
+
var RESET2 = "\x1B[0m";
|
|
1064
1345
|
var SEPARATOR = " \u2502 ";
|
|
1065
1346
|
var HEIGHT = /^(\d+)(%?)$/;
|
|
1066
1347
|
var DEFAULT_HEIGHT = { percent: 40 };
|
|
@@ -1070,14 +1351,18 @@ function parseHeight(text) {
|
|
|
1070
1351
|
return;
|
|
1071
1352
|
return found[2] === "%" ? { percent: Math.min(100, Number(found[1])) } : { lines: Number(found[1]) };
|
|
1072
1353
|
}
|
|
1073
|
-
function layoutFor(size, height, previewing) {
|
|
1354
|
+
function layoutFor(size, height, previewing, position = "right") {
|
|
1074
1355
|
const wanted = "lines" in height ? height.lines : Math.round(size.rows * height.percent / 100);
|
|
1075
1356
|
const rows = Math.min(size.rows, Math.max(MIN_HEIGHT, wanted));
|
|
1357
|
+
if (position === "down") {
|
|
1358
|
+
const previewHeight = previewing && rows >= PREVIEW_MIN_ROWS ? Math.round(rows * PREVIEW_SHARE) : 0;
|
|
1359
|
+
return { height: rows, listHeight: rows - previewHeight, listWidth: size.columns, previewWidth: 0, previewHeight };
|
|
1360
|
+
}
|
|
1076
1361
|
const split = previewing && size.columns >= PREVIEW_MIN_COLUMNS;
|
|
1077
1362
|
const listWidth = split ? Math.floor(size.columns / 2) : size.columns;
|
|
1078
|
-
return { height: rows, listWidth, previewWidth: split ? size.columns - listWidth - SEPARATOR.length : 0 };
|
|
1363
|
+
return { height: rows, listHeight: rows, listWidth, previewWidth: split ? size.columns - listWidth - SEPARATOR.length : 0, previewHeight: 0 };
|
|
1079
1364
|
}
|
|
1080
|
-
function fit(text, width, plain, mark = plain, marked = new Set) {
|
|
1365
|
+
function fit(text, width, plain, mark = plain, marked = new Set, styles) {
|
|
1081
1366
|
const room = Bun.stringWidth(text) > width ? width - 1 : width;
|
|
1082
1367
|
let out = "";
|
|
1083
1368
|
let used = 0;
|
|
@@ -1086,7 +1371,8 @@ function fit(text, width, plain, mark = plain, marked = new Set) {
|
|
|
1086
1371
|
const size = Bun.stringWidth(char);
|
|
1087
1372
|
if (used + size > room)
|
|
1088
1373
|
break;
|
|
1089
|
-
|
|
1374
|
+
const style = marked.has(at) ? "" : styles?.[at] ?? "";
|
|
1375
|
+
out += style === "" ? (marked.has(at) ? mark : plain)(char) : `${style}${char}${RESET2}`;
|
|
1090
1376
|
used += size;
|
|
1091
1377
|
at += char.length;
|
|
1092
1378
|
}
|
|
@@ -1097,25 +1383,31 @@ function fit(text, width, plain, mark = plain, marked = new Set) {
|
|
|
1097
1383
|
return { text: out, width: used };
|
|
1098
1384
|
}
|
|
1099
1385
|
var identity = (text) => text;
|
|
1386
|
+
function fitStyled(line, width, plain = identity) {
|
|
1387
|
+
const { text, styles } = styled(line);
|
|
1388
|
+
return fit(text, width, plain, plain, new Set, styles);
|
|
1389
|
+
}
|
|
1100
1390
|
function caretColumn(state, layout) {
|
|
1101
1391
|
return Math.min(layout.listWidth, Bun.stringWidth(state.prompt) + Bun.stringWidth(state.query) + 1);
|
|
1102
1392
|
}
|
|
1103
1393
|
function listLines(state, layout, theme) {
|
|
1104
|
-
const
|
|
1394
|
+
const header = state.header === "" ? [] : state.header.split(`
|
|
1395
|
+
`).map((line) => fitStyled(line, layout.listWidth, theme.label));
|
|
1396
|
+
const rows = Math.max(1, layout.listHeight - 2 - header.length);
|
|
1105
1397
|
const prefixWidth = state.multi ? 4 : 2;
|
|
1106
1398
|
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)` : "";
|
|
1399
|
+
const marks = (state.marked.size > 0 ? ` (${state.marked.size} marked)` : "") + (state.status === "" ? "" : ` ${state.status}`);
|
|
1108
1400
|
const promptWidth = Bun.stringWidth(state.prompt);
|
|
1109
1401
|
const query = fit(state.query, Math.max(1, layout.listWidth - promptWidth), identity);
|
|
1110
1402
|
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];
|
|
1403
|
+
const lines = [{ text: theme.accent(state.prompt) + query.text, width: promptWidth + query.width }, count, ...header];
|
|
1112
1404
|
if (state.matches.length === 0)
|
|
1113
1405
|
lines.push(fit(" no match", layout.listWidth, theme.label));
|
|
1114
1406
|
for (const [offset, match] of state.matches.slice(top, top + rows).entries()) {
|
|
1115
1407
|
const current = top + offset === state.cursor;
|
|
1116
1408
|
const pointer = current ? theme.accent("\u276F") : " ";
|
|
1117
1409
|
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));
|
|
1410
|
+
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
1411
|
lines.push({ text: `${pointer} ${mark}${text.text}`, width: prefixWidth + text.width });
|
|
1120
1412
|
}
|
|
1121
1413
|
return lines;
|
|
@@ -1123,37 +1415,65 @@ function listLines(state, layout, theme) {
|
|
|
1123
1415
|
function render(state, layout, theme, preview = []) {
|
|
1124
1416
|
const left = listLines(state, layout, theme);
|
|
1125
1417
|
return Array.from({ length: layout.height }, (_, row) => {
|
|
1418
|
+
if (row >= layout.listHeight)
|
|
1419
|
+
return row === layout.listHeight ? theme.label("\u2500".repeat(layout.listWidth)) : fitStyled(preview[row - layout.listHeight - 1] ?? "", layout.listWidth).text;
|
|
1126
1420
|
const list = left[row] ?? { text: "", width: 0 };
|
|
1127
1421
|
if (layout.previewWidth === 0)
|
|
1128
1422
|
return list.text;
|
|
1129
|
-
return `${list.text}${" ".repeat(Math.max(0, layout.listWidth - list.width))}${theme.label(SEPARATOR)}${
|
|
1423
|
+
return `${list.text}${" ".repeat(Math.max(0, layout.listWidth - list.width))}${theme.label(SEPARATOR)}${fitStyled(preview[row] ?? "", layout.previewWidth).text}`;
|
|
1130
1424
|
});
|
|
1131
1425
|
}
|
|
1132
1426
|
|
|
1133
|
-
// src/terminal.ts
|
|
1427
|
+
// ../kit/src/picker/terminal.ts
|
|
1134
1428
|
var PREVIEW_DELAY_MS = 120;
|
|
1429
|
+
var OPEN = { ctrl: "open" };
|
|
1135
1430
|
var HIDE_CURSOR = "\x1B[?25l";
|
|
1136
1431
|
var SHOW_CURSOR = "\x1B[?25h";
|
|
1137
1432
|
var PASTE_ON = "\x1B[?2004h";
|
|
1138
1433
|
var PASTE_OFF = "\x1B[?2004l";
|
|
1139
1434
|
var CLEAR_BELOW = "\r\x1B[J";
|
|
1140
1435
|
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
1436
|
function up(lines) {
|
|
1145
1437
|
return lines > 0 ? `\x1B[${lines}A` : "";
|
|
1146
1438
|
}
|
|
1147
|
-
|
|
1439
|
+
function openTerminal() {
|
|
1148
1440
|
let input;
|
|
1149
1441
|
try {
|
|
1150
1442
|
input = new tty.ReadStream(openSync("/dev/tty", "r"));
|
|
1151
1443
|
} catch {
|
|
1152
1444
|
return fail("no terminal to read keys from (/dev/tty)");
|
|
1153
1445
|
}
|
|
1154
|
-
const out =
|
|
1155
|
-
|
|
1156
|
-
|
|
1446
|
+
const out = process13.stderr;
|
|
1447
|
+
let resize;
|
|
1448
|
+
return {
|
|
1449
|
+
get columns() {
|
|
1450
|
+
return out.columns || 80;
|
|
1451
|
+
},
|
|
1452
|
+
get rows() {
|
|
1453
|
+
return out.rows || 24;
|
|
1454
|
+
},
|
|
1455
|
+
theme: { accent: role("accent", out), label: role("label", out), value: role("value", out), id: role("id", out) },
|
|
1456
|
+
write: (text) => void out.write(text),
|
|
1457
|
+
listen(onChunk, onResize) {
|
|
1458
|
+
resize = onResize;
|
|
1459
|
+
input.setRawMode(true);
|
|
1460
|
+
out.on("resize", onResize);
|
|
1461
|
+
input.on("data", (chunk) => onChunk(chunk.toString()));
|
|
1462
|
+
},
|
|
1463
|
+
close() {
|
|
1464
|
+
if (resize !== undefined)
|
|
1465
|
+
out.off("resize", resize);
|
|
1466
|
+
try {
|
|
1467
|
+
input.setRawMode(false);
|
|
1468
|
+
} finally {
|
|
1469
|
+
input.destroy();
|
|
1470
|
+
}
|
|
1471
|
+
}
|
|
1472
|
+
};
|
|
1473
|
+
}
|
|
1474
|
+
async function select(rows, settings, terminal = openTerminal()) {
|
|
1475
|
+
const { theme } = terminal;
|
|
1476
|
+
let state = createState(rows, settings);
|
|
1157
1477
|
let preview = [];
|
|
1158
1478
|
let reserved = 0;
|
|
1159
1479
|
let previewTimer;
|
|
@@ -1162,7 +1482,9 @@ async function choose(lines, settings) {
|
|
|
1162
1482
|
let finish;
|
|
1163
1483
|
let restored = false;
|
|
1164
1484
|
function draw(clear = false) {
|
|
1165
|
-
|
|
1485
|
+
if (restored)
|
|
1486
|
+
return;
|
|
1487
|
+
const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
|
|
1166
1488
|
let frame = HIDE_CURSOR;
|
|
1167
1489
|
if (reserved !== layout.height || clear) {
|
|
1168
1490
|
frame += CLEAR_BELOW + `
|
|
@@ -1171,7 +1493,7 @@ async function choose(lines, settings) {
|
|
|
1171
1493
|
}
|
|
1172
1494
|
frame += `\r${render(state, layout, theme, preview).map((line) => `\x1B[2K${line}`).join(`
|
|
1173
1495
|
`)}${up(layout.height - 1)}\r\x1B[${caretColumn(state, layout)}G${SHOW_CURSOR}`;
|
|
1174
|
-
|
|
1496
|
+
terminal.write(frame);
|
|
1175
1497
|
}
|
|
1176
1498
|
function refreshPreview() {
|
|
1177
1499
|
const at = highlighted(state);
|
|
@@ -1187,9 +1509,9 @@ async function choose(lines, settings) {
|
|
|
1187
1509
|
}
|
|
1188
1510
|
const { signal } = previewing;
|
|
1189
1511
|
const template = settings.preview;
|
|
1190
|
-
const
|
|
1512
|
+
const row = state.rows[at];
|
|
1191
1513
|
async function show() {
|
|
1192
|
-
const shown = await runPreview(template,
|
|
1514
|
+
const shown = typeof template === "string" ? await runPreview(template, row.cells.join(" "), signal, row.hidden) : await previewOf(template, row.hidden, signal);
|
|
1193
1515
|
if (!signal.aborted) {
|
|
1194
1516
|
preview = shown;
|
|
1195
1517
|
draw();
|
|
@@ -1203,56 +1525,99 @@ async function choose(lines, settings) {
|
|
|
1203
1525
|
restored = true;
|
|
1204
1526
|
clearTimeout(previewTimer);
|
|
1205
1527
|
previewing.abort();
|
|
1206
|
-
|
|
1207
|
-
|
|
1528
|
+
terminal.write(`${CLEAR_BELOW}${PASTE_OFF}${SHOW_CURSOR}`);
|
|
1529
|
+
terminal.close();
|
|
1530
|
+
}
|
|
1531
|
+
const stop = () => {
|
|
1532
|
+
state = { ...state, done: "cancel" };
|
|
1533
|
+
finish?.();
|
|
1534
|
+
};
|
|
1535
|
+
const paste = { active: false };
|
|
1536
|
+
const { reload } = settings;
|
|
1537
|
+
const pending = [];
|
|
1538
|
+
let busy = false;
|
|
1539
|
+
let draining = false;
|
|
1540
|
+
async function reloadRows() {
|
|
1541
|
+
if (reload === undefined)
|
|
1542
|
+
return;
|
|
1543
|
+
busy = true;
|
|
1544
|
+
state = { ...state, status: "reloading" };
|
|
1545
|
+
draw();
|
|
1208
1546
|
try {
|
|
1209
|
-
|
|
1547
|
+
const next = await reload.run();
|
|
1548
|
+
state = { ...withRows(state, next.rows, next.header), status: "" };
|
|
1549
|
+
shownLine = undefined;
|
|
1550
|
+
} catch (error) {
|
|
1551
|
+
state = { ...state, status: `reload failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
1210
1552
|
} finally {
|
|
1211
|
-
|
|
1553
|
+
busy = false;
|
|
1212
1554
|
}
|
|
1213
1555
|
}
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1556
|
+
async function drain() {
|
|
1557
|
+
if (draining)
|
|
1558
|
+
return;
|
|
1559
|
+
draining = true;
|
|
1560
|
+
try {
|
|
1561
|
+
for (let key = pending.shift();key !== undefined && state.done === undefined; key = pending.shift()) {
|
|
1562
|
+
if (key === OPEN || typeof key === "object" && "ctrl" in key && key.ctrl === reload?.key)
|
|
1563
|
+
await reloadRows();
|
|
1564
|
+
else
|
|
1565
|
+
state = press(state, key);
|
|
1224
1566
|
}
|
|
1567
|
+
} finally {
|
|
1568
|
+
draining = false;
|
|
1569
|
+
}
|
|
1570
|
+
if (state.done !== undefined) {
|
|
1571
|
+
finish?.();
|
|
1572
|
+
return;
|
|
1225
1573
|
}
|
|
1226
1574
|
refreshPreview();
|
|
1227
1575
|
draw();
|
|
1228
1576
|
}
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1577
|
+
function onChunk(chunk) {
|
|
1578
|
+
const keys = parseKeys(chunk, paste, [...settings.expect ?? [], ...reload?.key === undefined ? [] : [reload.key]]);
|
|
1579
|
+
if (busy && keys.includes("cancel")) {
|
|
1580
|
+
stop();
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
pending.push(...keys);
|
|
1584
|
+
drain();
|
|
1585
|
+
}
|
|
1233
1586
|
const ended = new Promise((resolve) => {
|
|
1234
1587
|
finish = resolve;
|
|
1235
1588
|
});
|
|
1236
|
-
|
|
1589
|
+
process13.once("exit", restore);
|
|
1237
1590
|
for (const signal of SIGNALS)
|
|
1238
|
-
|
|
1591
|
+
process13.once(signal, stop);
|
|
1239
1592
|
try {
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
out.on("resize", onResize);
|
|
1243
|
-
input.on("data", onData);
|
|
1593
|
+
terminal.write(PASTE_ON);
|
|
1594
|
+
terminal.listen(onChunk, () => draw(true));
|
|
1244
1595
|
refreshPreview();
|
|
1245
1596
|
draw(true);
|
|
1597
|
+
if (reload?.onOpen === true) {
|
|
1598
|
+
pending.push(OPEN);
|
|
1599
|
+
drain();
|
|
1600
|
+
}
|
|
1246
1601
|
await ended;
|
|
1247
1602
|
} finally {
|
|
1248
1603
|
for (const signal of SIGNALS)
|
|
1249
|
-
|
|
1250
|
-
|
|
1604
|
+
process13.off(signal, stop);
|
|
1605
|
+
process13.off("exit", restore);
|
|
1251
1606
|
restore();
|
|
1252
1607
|
}
|
|
1253
|
-
return state.done === "accept" ? chosen(state) : undefined;
|
|
1608
|
+
return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
|
|
1609
|
+
}
|
|
1610
|
+
async function previewOf(preview, hidden, signal) {
|
|
1611
|
+
try {
|
|
1612
|
+
return previewLines(await preview(hidden, signal));
|
|
1613
|
+
} catch (error) {
|
|
1614
|
+
return [error instanceof Error ? error.message : String(error)];
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
async function choose(lines, settings) {
|
|
1618
|
+
const picked = await select(lines.map((line) => ({ hidden: [], cells: [line] })), settings);
|
|
1619
|
+
return picked?.rows.map((row) => row.cells[0]);
|
|
1254
1620
|
}
|
|
1255
|
-
|
|
1256
1621
|
// src/pick.ts
|
|
1257
1622
|
var USAGE = `pick [options]: a fuzzy selector, the lines on stdin in, the chosen one on stdout out
|
|
1258
1623
|
|
|
@@ -1260,7 +1625,9 @@ Type to filter: the query matches as a subsequence, best matches first (a word s
|
|
|
1260
1625
|
The keys are read from the terminal and the selector is drawn on stderr, so \`pick\` in a pipe or a command substitution prints only the choice. With --multi, tab marks the highlighted line and enter prints the marked lines in input order (the highlighted one when none is marked).
|
|
1261
1626
|
--preview runs a command for the highlighted line, \`{}\` standing for it shell-quoted, in a pane on the right when the terminal is at least 80 columns wide; its output is cut at 64 KiB and 200 lines.
|
|
1262
1627
|
|
|
1263
|
-
|
|
1628
|
+
Without a terminal on stderr there is nobody to choose: it prints the first line containing the query (case-insensitive), every one with --multi.
|
|
1629
|
+
|
|
1630
|
+
Exits 0 when it printed a choice, 1 when cancelled, nothing matches or there are no lines, 2 on a usage error.`;
|
|
1264
1631
|
var OPTIONS = {
|
|
1265
1632
|
multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
|
|
1266
1633
|
prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
|
|
@@ -1275,20 +1642,28 @@ async function main(args) {
|
|
|
1275
1642
|
const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
|
|
1276
1643
|
if (height === undefined)
|
|
1277
1644
|
badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
|
|
1278
|
-
if (
|
|
1279
|
-
fail("pick draws on stderr and it is not a terminal");
|
|
1280
|
-
if (process10.stdin.isTTY)
|
|
1645
|
+
if (process14.stdin.isTTY)
|
|
1281
1646
|
badUsage("pipe the lines to pick on stdin");
|
|
1282
1647
|
const lines = (await Bun.stdin.text()).split(`
|
|
1283
1648
|
`).filter((line) => line !== "");
|
|
1284
1649
|
if (lines.length === 0)
|
|
1285
1650
|
fail("nothing to pick from", 1);
|
|
1651
|
+
if (!process14.stderr.isTTY) {
|
|
1652
|
+
const query = (values.query ?? "").toLowerCase();
|
|
1653
|
+
const matching = lines.filter((line) => line.toLowerCase().includes(query));
|
|
1654
|
+
if (matching.length === 0)
|
|
1655
|
+
return 1;
|
|
1656
|
+
process14.stdout.write(`${(values.multi === true ? matching : matching.slice(0, 1)).join(`
|
|
1657
|
+
`)}
|
|
1658
|
+
`);
|
|
1659
|
+
return 0;
|
|
1660
|
+
}
|
|
1286
1661
|
const picked = await choose(lines, { multi: values.multi === true, prompt: values.prompt ?? "> ", query: values.query ?? "", height, preview: values.preview });
|
|
1287
1662
|
if (picked === undefined)
|
|
1288
1663
|
return 1;
|
|
1289
|
-
|
|
1664
|
+
process14.stdout.write(`${picked.join(`
|
|
1290
1665
|
`)}
|
|
1291
1666
|
`);
|
|
1292
1667
|
return 0;
|
|
1293
1668
|
}
|
|
1294
|
-
|
|
1669
|
+
process14.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.4.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.23.0"
|
|
39
39
|
}
|
|
40
40
|
}
|