@kaynooo/cli-pick 0.9.0 → 0.9.2

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.
Files changed (2) hide show
  1. package/dist/pick.js +81 -53
  2. package/package.json +2 -2
package/dist/pick.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/pick.ts
5
- import process15 from "process";
5
+ import process16 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -341,18 +341,14 @@ var FULL_STOP = /\.$/;
341
341
  function usageLine(usage, colors = paint(process8.stdout)) {
342
342
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
343
343
  }
344
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
345
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
344
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
345
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
346
346
  `);
347
347
  }
348
348
  function exitRows(exits, colors = paint(process8.stdout)) {
349
349
  if (exits.length === 0)
350
350
  return [];
351
- const width = Math.max(...exits.map(([code]) => String(code).length));
352
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
353
- }
354
- function replacesRows(replaces, colors = paint(process8.stdout)) {
355
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
351
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
356
352
  }
357
353
  function wantsHelpJson(env = process8.env) {
358
354
  return env.KIT_HELP === "json";
@@ -627,21 +623,45 @@ function nearestOption(message, options, allowNegative) {
627
623
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
628
624
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
629
625
  }
626
+ // ../kit/src/argv.ts
627
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
628
+ import { resolve as resolve3 } from "path";
629
+ import process10 from "process";
630
+ function commandLine() {
631
+ try {
632
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
633
+ } catch {
634
+ return;
635
+ }
636
+ }
637
+ function realPath(word) {
638
+ try {
639
+ return realpathSync(resolve3(word));
640
+ } catch {
641
+ return;
642
+ }
643
+ }
644
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
645
+ const target = script === undefined ? undefined : realPath(script) ?? script;
646
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
647
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
648
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
649
+ }
630
650
  // ../kit/src/progress.ts
631
651
  var ESC = String.fromCharCode(27);
632
652
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
633
653
  var RESET_STYLE = `${ESC}[0m`;
634
654
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
635
655
  // ../kit/src/cli.ts
636
- import { readFileSync as readFileSync2, realpathSync } from "fs";
656
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
637
657
  import { dirname as dirname3, join as join5 } from "path";
638
- import process11 from "process";
658
+ import process12 from "process";
639
659
 
640
660
  // ../kit/src/usage.ts
641
661
  import { appendFileSync, mkdirSync } from "fs";
642
662
  import { homedir as homedir3 } from "os";
643
663
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
644
- import process10 from "process";
664
+ import process11 from "process";
645
665
 
646
666
  // ../kit/src/logs.ts
647
667
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -655,14 +675,14 @@ var usageError;
655
675
  function noteUsageError(message) {
656
676
  usageError = message;
657
677
  }
658
- function stateHome(env = process10.env) {
678
+ function stateHome(env = process11.env) {
659
679
  const dir = env.XDG_STATE_HOME;
660
680
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
661
681
  }
662
- function usagePath(env = process10.env) {
682
+ function usagePath(env = process11.env) {
663
683
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
664
684
  }
665
- function usageRecorded(env = process10.env) {
685
+ function usageRecorded(env = process11.env) {
666
686
  const off = env.KAYNOOO_CLI_NO_USAGE;
667
687
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
668
688
  }
@@ -676,7 +696,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
676
696
  usageError = undefined;
677
697
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
678
698
  }
679
- function recordUsage(entry, env = process10.env) {
699
+ function recordUsage(entry, env = process11.env) {
680
700
  if (!usageRecorded(env))
681
701
  return;
682
702
  try {
@@ -694,8 +714,8 @@ var LEVEL_OPTIONS = {
694
714
  };
695
715
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
696
716
  function printError(prefix, message, hint, cause) {
697
- const colors = paint(process11.stderr);
698
- const styled = takesControlCodes(process11.stderr);
717
+ const colors = paint(process12.stderr);
718
+ const styled = takesControlCodes(process12.stderr);
699
719
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
700
720
  const under = (label, text, tint) => text === undefined ? "" : `
701
721
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -739,24 +759,24 @@ function candidateLine(candidate) {
739
759
  }
740
760
  function positionalBeingTyped(before, { options, positionals }) {
741
761
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
742
- let index = 0;
762
+ const typed = [];
743
763
  let at = 0;
744
764
  while (at < before.length) {
745
765
  const word = before[at];
746
766
  if (word === "--") {
747
- index += before.length - at - 1;
767
+ typed.push(...before.slice(at + 1));
748
768
  break;
749
769
  }
750
770
  if (!word.startsWith("-"))
751
- index++;
771
+ typed.push(word);
752
772
  else if (takesValue(word))
753
773
  at++;
754
774
  at++;
755
775
  }
756
776
  const last = positionals.at(-1);
757
- if (index < positionals.length)
758
- return positionals[index];
759
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
777
+ if (typed.length < positionals.length)
778
+ return { name: positionals[typed.length], typed };
779
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
760
780
  }
761
781
  async function leafCandidates(run, words) {
762
782
  const completing = await completingOf(run);
@@ -764,12 +784,12 @@ async function leafCandidates(run, words) {
764
784
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
765
785
  const flag = words.at(-2);
766
786
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
787
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
767
788
  if (option?.type === "string") {
768
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
789
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
769
790
  return values === undefined ? [FILES] : values.map(candidateLine);
770
791
  }
771
- const name = positionalBeingTyped(words.slice(0, -1), completing);
772
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
792
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
773
793
  return values === undefined ? [FILES] : values.map(candidateLine);
774
794
  }
775
795
  async function printCandidates(found) {
@@ -778,9 +798,13 @@ async function printCandidates(found) {
778
798
  return 0;
779
799
  }
780
800
  function packageVersion(entry = Bun.main) {
781
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
801
+ let resolved = entry;
802
+ try {
803
+ resolved = realpathSync2(entry);
804
+ } catch {}
805
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
782
806
  try {
783
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
807
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
784
808
  if (typeof version === "string")
785
809
  return version;
786
810
  } catch {}
@@ -788,7 +812,7 @@ function packageVersion(entry = Bun.main) {
788
812
  return "0.0.0";
789
813
  }
790
814
  }
791
- async function runMain({ name, version, run, redact, usage }, argv = process11.argv.slice(2)) {
815
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
792
816
  if (argv[0] === COMPLETE)
793
817
  return printCandidates(leafCandidates(run, argv.slice(1)));
794
818
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -909,7 +933,9 @@ var COLUMN_GAP = 2;
909
933
  var PASTE_START = "\x1B[200~";
910
934
  var PASTE_END = "\x1B[201~";
911
935
  var LAST_WORD = /\S*\s*$/;
912
- var KEY_SEQUENCES = /\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
936
+ var KEY_SEQUENCES = /\x1B\[<[0-9;]*[A-Za-z]|\x1B\[[0-9;]*[A-Z~]|\x1BO[A-Z]|\x1B[\s\S]|[\s\S]/gu;
937
+ var MOUSE = /^\x1B\[<(\d+);\d+;\d+[a-z]$/i;
938
+ var WHEEL_LINES = 3;
913
939
  var KEYS = {
914
940
  "\x1B[A": "up",
915
941
  "\x1BOA": "up",
@@ -990,6 +1016,9 @@ function lay(rows, searched) {
990
1016
  function parseKeys(input, paste = { active: false }, ctrls = []) {
991
1017
  const codes = new Map(ctrls.map((name) => [String.fromCharCode(name.codePointAt(name.length - 1) - 96), name]));
992
1018
  return (input.match(KEY_SEQUENCES) ?? []).flatMap((sequence) => {
1019
+ const wheel = MOUSE.exec(sequence)?.[1];
1020
+ if (wheel !== undefined)
1021
+ return repeat(wheel === "64" ? "up" : "down", wheel === "64" || wheel === "65" ? WHEEL_LINES : 0);
993
1022
  const named = codes.get(sequence);
994
1023
  const key = named === undefined ? KEYS[sequence] : { ctrl: named };
995
1024
  if (sequence === PASTE_START || sequence === PASTE_END) {
@@ -1079,11 +1108,11 @@ function chosen(state) {
1079
1108
 
1080
1109
  // ../kit/src/picker/terminal.ts
1081
1110
  import { openSync } from "fs";
1082
- import process14 from "process";
1111
+ import process15 from "process";
1083
1112
  import tty from "tty";
1084
1113
 
1085
1114
  // ../kit/src/picker/preview.ts
1086
- import process13 from "process";
1115
+ import process14 from "process";
1087
1116
 
1088
1117
  // ../kit/src/shell.ts
1089
1118
  var SEPARATORS = new Set([`
@@ -1152,7 +1181,7 @@ async function runPreview(template, line, signal, hidden = []) {
1152
1181
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1153
1182
  const stop = () => {
1154
1183
  try {
1155
- process13.kill(-proc.pid, "SIGKILL");
1184
+ process14.kill(-proc.pid, "SIGKILL");
1156
1185
  } catch {
1157
1186
  proc.kill();
1158
1187
  }
@@ -1233,7 +1262,7 @@ function caretColumn(state, layout) {
1233
1262
  }
1234
1263
  function helpLines(state, layout, theme) {
1235
1264
  const lines = [
1236
- "type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end move",
1265
+ "type to filter, up, down, ctrl-p, ctrl-n, pgup, pgdn, home, end, the wheel move",
1237
1266
  `enter picks${state.multi ? ", tab marks" : ""}, ctrl-u clears the query, ctrl-w a word, esc or ctrl-c cancels`,
1238
1267
  ...state.expect.length > 0 ? [`${state.expect.join(", ")} end the pick as this command asks`] : []
1239
1268
  ];
@@ -1283,8 +1312,11 @@ var ESCAPE_WAIT_MS = 30;
1283
1312
  var OPEN = { ctrl: "open" };
1284
1313
  var HIDE_CURSOR = "\x1B[?25l";
1285
1314
  var SHOW_CURSOR = "\x1B[?25h";
1315
+ var CARET = "\x1B[7m \x1B[27m";
1286
1316
  var PASTE_ON = "\x1B[?2004h";
1287
1317
  var PASTE_OFF = "\x1B[?2004l";
1318
+ var MOUSE_ON = "\x1B[?1000h\x1B[?1006h";
1319
+ var MOUSE_OFF = "\x1B[?1006l\x1B[?1000l";
1288
1320
  var CLEAR_BELOW = "\r\x1B[J";
1289
1321
  var SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
1290
1322
  function up(lines) {
@@ -1298,7 +1330,7 @@ function openTerminal() {
1298
1330
  return fail("no terminal to read keys from (/dev/tty)");
1299
1331
  }
1300
1332
  const keys = Bun.file("/dev/tty").stream().getReader();
1301
- const out = process14.stderr;
1333
+ const out = process15.stderr;
1302
1334
  let resize;
1303
1335
  async function read(onChunk) {
1304
1336
  const decoder = new TextDecoder;
@@ -1347,21 +1379,18 @@ async function select(rows, settings, terminal = openTerminal()) {
1347
1379
  let finish;
1348
1380
  let restored = false;
1349
1381
  let escape;
1350
- let caret;
1351
1382
  function draw(clear = false) {
1352
1383
  if (restored)
1353
1384
  return;
1354
1385
  const layout = layoutFor({ columns: terminal.columns, rows: terminal.rows }, settings.height, settings.preview !== undefined, settings.previewPosition);
1355
1386
  let frame = HIDE_CURSOR;
1356
1387
  if (reserved !== layout.height || clear) {
1357
- frame += clear && caret !== undefined ? up(Math.floor((caret - 1) / terminal.columns)) : "";
1358
1388
  frame += CLEAR_BELOW + `
1359
1389
  `.repeat(layout.height - 1) + up(layout.height - 1);
1360
1390
  reserved = layout.height;
1361
1391
  }
1362
- caret = caretColumn(state, layout);
1363
1392
  frame += `\r${render(state, layout, theme, preview).map((line) => `\x1B[2K${line}`).join(`
1364
- `)}${up(layout.height - 1)}\r\x1B[${caret}G${SHOW_CURSOR}`;
1393
+ `)}${up(layout.height - 1)}\r\x1B[${caretColumn(state, layout)}G${CARET}\r`;
1365
1394
  terminal.write(frame);
1366
1395
  }
1367
1396
  function pageSize() {
@@ -1400,7 +1429,7 @@ async function select(rows, settings, terminal = openTerminal()) {
1400
1429
  clearTimeout(previewTimer);
1401
1430
  clearTimeout(escape);
1402
1431
  previewing.abort();
1403
- terminal.write(`${CLEAR_BELOW}${PASTE_OFF}${SHOW_CURSOR}`);
1432
+ terminal.write(`${CLEAR_BELOW}${MOUSE_OFF}${PASTE_OFF}${SHOW_CURSOR}`);
1404
1433
  terminal.close();
1405
1434
  }
1406
1435
  const stop = () => {
@@ -1475,11 +1504,11 @@ async function select(rows, settings, terminal = openTerminal()) {
1475
1504
  const ended = new Promise((resolve) => {
1476
1505
  finish = resolve;
1477
1506
  });
1478
- process14.once("exit", restore);
1507
+ process15.once("exit", restore);
1479
1508
  for (const signal of SIGNALS)
1480
- process14.once(signal, stop);
1509
+ process15.once(signal, stop);
1481
1510
  try {
1482
- terminal.write(PASTE_ON);
1511
+ terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1483
1512
  terminal.listen(onChunk, () => draw(true));
1484
1513
  refreshPreview();
1485
1514
  draw(true);
@@ -1490,8 +1519,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1490
1519
  await ended;
1491
1520
  } finally {
1492
1521
  for (const signal of SIGNALS)
1493
- process14.off(signal, stop);
1494
- process14.off("exit", restore);
1522
+ process15.off(signal, stop);
1523
+ process15.off("exit", restore);
1495
1524
  restore();
1496
1525
  }
1497
1526
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1514,9 +1543,8 @@ Type to filter: the query matches as a subsequence, best matches first (a word s
1514
1543
  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).
1515
1544
  --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.
1516
1545
 
1517
- Without a terminal on stderr there is nobody to choose: it prints the first line containing the query (case-insensitive), every one with --multi.
1518
-
1519
- Exits 0 when it printed a choice, 1 when cancelled, nothing matches or there are no lines, 2 on a usage error.`;
1546
+ Without a terminal on stderr there is nobody to choose: it prints the first line containing the query (case-insensitive), every one with --multi.`;
1547
+ var EXITS = [[0, "it printed a choice"], [1, "cancelled, nothing matches or there are no lines"], [2, "a usage error"]];
1520
1548
  var OPTIONS = {
1521
1549
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
1522
1550
  prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
@@ -1529,24 +1557,24 @@ function print(chosen, json) {
1529
1557
  if (json)
1530
1558
  printJson({ picked: chosen });
1531
1559
  else
1532
- process15.stdout.write(`${chosen.join(`
1560
+ process16.stdout.write(`${chosen.join(`
1533
1561
  `)}
1534
1562
  `);
1535
1563
  }
1536
1564
  async function main(args) {
1537
- const { values, positionals } = parse(args, USAGE, OPTIONS, { replaces: "fzf for a quick choice in a pipe, select in a shell script", examples: ["git branch --format='%(refname:short)' | pick", "ls | pick --multi --preview 'head -20 {}'"] });
1565
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, replaces: "fzf for a quick choice in a pipe, select in a shell script", examples: ["git branch --format='%(refname:short)' | pick", "ls | pick --multi --preview 'head -20 {}'"] });
1538
1566
  if (positionals.length > 0)
1539
1567
  badUsage("pick takes its lines on stdin, not as arguments");
1540
1568
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1541
1569
  if (height === undefined)
1542
1570
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1543
- if (process15.stdin.isTTY)
1571
+ if (process16.stdin.isTTY)
1544
1572
  badUsage("pipe the lines to pick on stdin");
1545
1573
  const lines = (await Bun.stdin.text()).split(`
1546
1574
  `).filter((line) => line !== "");
1547
1575
  if (lines.length === 0)
1548
1576
  fail("nothing to pick from", 1);
1549
- if (!process15.stderr.isTTY) {
1577
+ if (!process16.stderr.isTTY) {
1550
1578
  const query = (values.query ?? "").toLowerCase();
1551
1579
  const matching = lines.filter((line) => line.toLowerCase().includes(query));
1552
1580
  if (matching.length === 0)
@@ -1560,4 +1588,4 @@ async function main(args) {
1560
1588
  print(picked, values.json === true);
1561
1589
  return 0;
1562
1590
  }
1563
- process15.exitCode = await runMain({ name: "pick", run: main });
1591
+ process16.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.9.0",
4
+ "version": "0.9.2",
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.36.0"
38
+ "@kaynooo/cli-kit": "0.38.3"
39
39
  }
40
40
  }