@kaynooo/cli-pick 0.9.1 → 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 +68 -45
  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")) {
@@ -1084,11 +1108,11 @@ function chosen(state) {
1084
1108
 
1085
1109
  // ../kit/src/picker/terminal.ts
1086
1110
  import { openSync } from "fs";
1087
- import process14 from "process";
1111
+ import process15 from "process";
1088
1112
  import tty from "tty";
1089
1113
 
1090
1114
  // ../kit/src/picker/preview.ts
1091
- import process13 from "process";
1115
+ import process14 from "process";
1092
1116
 
1093
1117
  // ../kit/src/shell.ts
1094
1118
  var SEPARATORS = new Set([`
@@ -1157,7 +1181,7 @@ async function runPreview(template, line, signal, hidden = []) {
1157
1181
  ${previewCommand(template, line, hidden)}`], { stdin: "ignore", stdout: "pipe", stderr: "ignore", detached: true });
1158
1182
  const stop = () => {
1159
1183
  try {
1160
- process13.kill(-proc.pid, "SIGKILL");
1184
+ process14.kill(-proc.pid, "SIGKILL");
1161
1185
  } catch {
1162
1186
  proc.kill();
1163
1187
  }
@@ -1306,7 +1330,7 @@ function openTerminal() {
1306
1330
  return fail("no terminal to read keys from (/dev/tty)");
1307
1331
  }
1308
1332
  const keys = Bun.file("/dev/tty").stream().getReader();
1309
- const out = process14.stderr;
1333
+ const out = process15.stderr;
1310
1334
  let resize;
1311
1335
  async function read(onChunk) {
1312
1336
  const decoder = new TextDecoder;
@@ -1480,9 +1504,9 @@ async function select(rows, settings, terminal = openTerminal()) {
1480
1504
  const ended = new Promise((resolve) => {
1481
1505
  finish = resolve;
1482
1506
  });
1483
- process14.once("exit", restore);
1507
+ process15.once("exit", restore);
1484
1508
  for (const signal of SIGNALS)
1485
- process14.once(signal, stop);
1509
+ process15.once(signal, stop);
1486
1510
  try {
1487
1511
  terminal.write(`${PASTE_ON}${MOUSE_ON}`);
1488
1512
  terminal.listen(onChunk, () => draw(true));
@@ -1495,8 +1519,8 @@ async function select(rows, settings, terminal = openTerminal()) {
1495
1519
  await ended;
1496
1520
  } finally {
1497
1521
  for (const signal of SIGNALS)
1498
- process14.off(signal, stop);
1499
- process14.off("exit", restore);
1522
+ process15.off(signal, stop);
1523
+ process15.off("exit", restore);
1500
1524
  restore();
1501
1525
  }
1502
1526
  return state.done === "accept" ? { rows: chosen(state), key: state.key, query: state.query } : undefined;
@@ -1519,9 +1543,8 @@ Type to filter: the query matches as a subsequence, best matches first (a word s
1519
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).
1520
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.
1521
1545
 
1522
- Without a terminal on stderr there is nobody to choose: it prints the first line containing the query (case-insensitive), every one with --multi.
1523
-
1524
- 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"]];
1525
1548
  var OPTIONS = {
1526
1549
  multi: { type: "boolean", short: "m", description: "tab marks several lines, enter prints them" },
1527
1550
  prompt: { type: "string", short: "p", description: "the prompt before the query (> )" },
@@ -1534,24 +1557,24 @@ function print(chosen, json) {
1534
1557
  if (json)
1535
1558
  printJson({ picked: chosen });
1536
1559
  else
1537
- process15.stdout.write(`${chosen.join(`
1560
+ process16.stdout.write(`${chosen.join(`
1538
1561
  `)}
1539
1562
  `);
1540
1563
  }
1541
1564
  async function main(args) {
1542
- 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 {}'"] });
1543
1566
  if (positionals.length > 0)
1544
1567
  badUsage("pick takes its lines on stdin, not as arguments");
1545
1568
  const height = values.height === undefined ? DEFAULT_HEIGHT : parseHeight(values.height);
1546
1569
  if (height === undefined)
1547
1570
  badUsage(`--height takes a number of lines or a percentage such as 40%, not ${values.height}`);
1548
- if (process15.stdin.isTTY)
1571
+ if (process16.stdin.isTTY)
1549
1572
  badUsage("pipe the lines to pick on stdin");
1550
1573
  const lines = (await Bun.stdin.text()).split(`
1551
1574
  `).filter((line) => line !== "");
1552
1575
  if (lines.length === 0)
1553
1576
  fail("nothing to pick from", 1);
1554
- if (!process15.stderr.isTTY) {
1577
+ if (!process16.stderr.isTTY) {
1555
1578
  const query = (values.query ?? "").toLowerCase();
1556
1579
  const matching = lines.filter((line) => line.toLowerCase().includes(query));
1557
1580
  if (matching.length === 0)
@@ -1565,4 +1588,4 @@ async function main(args) {
1565
1588
  print(picked, values.json === true);
1566
1589
  return 0;
1567
1590
  }
1568
- 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.1",
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.37.0"
38
+ "@kaynooo/cli-kit": "0.38.3"
39
39
  }
40
40
  }