@kaynooo/cli-gloss 0.0.1 → 0.0.3

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/gloss.js +164 -35
  2. package/package.json +2 -2
package/dist/gloss.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/gloss.ts
5
- import process16 from "process";
5
+ import process17 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -321,6 +321,23 @@ var STATUS_WORDS = {
321
321
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
322
322
 
323
323
  // ../kit/src/format.ts
324
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
325
+ function formatSeconds(total) {
326
+ let rest = Math.max(0, Math.round(total));
327
+ const amounts = UNITS.map(([unit, size]) => {
328
+ const amount = Math.floor(rest / size);
329
+ rest -= amount * size;
330
+ return `${amount}${unit}`;
331
+ });
332
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
333
+ if (first === -1)
334
+ return "0s";
335
+ const next = amounts[first + 1];
336
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
337
+ }
338
+ function formatDuration(ms) {
339
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
340
+ }
324
341
  function upTo(text, separator) {
325
342
  const end = text.indexOf(separator);
326
343
  return end === -1 ? text : text.slice(0, end);
@@ -335,7 +352,7 @@ function printJson(value) {
335
352
 
336
353
  // ../kit/src/help.ts
337
354
  import process8 from "process";
338
- var OPTIONAL = /\[[^\]]+\]/g;
355
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
339
356
  var USAGE_PREFIX = /^usage:\s*/i;
340
357
  var FULL_STOP = /\.$/;
341
358
  function usageLine(usage, colors = paint(process8.stdout)) {
@@ -374,32 +391,44 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
374
391
  return [];
375
392
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
376
393
  }
394
+ var MAX_INLINE_CHOICES = 24;
377
395
  function optionRows(options, colors = paint(process8.stdout)) {
378
396
  const rows = Object.entries(options).map(([name, option]) => {
379
397
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
380
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
398
+ const choices = option.choices?.join("|");
399
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
400
+ const named = inline ? `<${choices}>` : "<value>";
381
401
  const placeholder = option.optional === undefined ? named : `[${named}]`;
382
402
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
383
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
403
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
404
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
384
405
  });
385
406
  const width = Math.max(0, ...rows.map((row) => row.width));
386
407
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
387
408
  }
388
409
 
389
410
  // ../kit/src/text.ts
390
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
411
+ var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
391
412
  function stripAnsi(text) {
392
413
  return text.replace(ANSI, "");
393
414
  }
394
415
  function distance(a, b) {
395
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
396
- for (const [i, left] of [...a].entries()) {
416
+ const left = [...a];
417
+ const right = [...b];
418
+ let before = [];
419
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
420
+ for (const [i, x] of left.entries()) {
397
421
  const current = [i + 1];
398
- for (const [j, right] of [...b].entries())
399
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
422
+ for (const [j, y] of right.entries()) {
423
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
424
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
425
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
426
+ current.push(cost);
427
+ }
428
+ before = previous;
400
429
  previous = current;
401
430
  }
402
- return previous[b.length] ?? 0;
431
+ return previous[right.length] ?? 0;
403
432
  }
404
433
  function closest(name, names) {
405
434
  const started = names.find((known) => known.startsWith(name));
@@ -450,7 +479,7 @@ class Completing {
450
479
  }
451
480
  var completion = { active: false };
452
481
  var OUTPUT_OPTIONS = {
453
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
482
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
454
483
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
455
484
  };
456
485
  function applyOutput(color, plain, env = process9.env) {
@@ -654,13 +683,91 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
654
683
  // ../kit/src/cli.ts
655
684
  import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
656
685
  import { dirname as dirname3, join as join5 } from "path";
657
- import process12 from "process";
686
+ import process13 from "process";
687
+
688
+ // ../kit/src/completions.ts
689
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
690
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
691
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
692
+ set -l current (commandline -ct)
693
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
694
+ if test "$line" = __files__
695
+ __fish_complete_path $current
696
+ else
697
+ echo $line
698
+ end
699
+ end
700
+ end`;
701
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
702
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
703
+ local -a lines
704
+ COMPREPLY=()
705
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
706
+ for line in "\${lines[@]}"; do
707
+ if [[ $line == __files__ ]]; then
708
+ COMPREPLY+=($(compgen -f -- "$cur"))
709
+ else
710
+ words+="\${line%%$'\\t'*}"$'\\n'
711
+ fi
712
+ done
713
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
714
+ }`;
715
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
716
+ local line
717
+ local -a described plain
718
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
719
+ if [[ $line == __files__ ]]; then
720
+ _files
721
+ elif [[ $line == *$'\\t'* ]]; then
722
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
723
+ else
724
+ plain+=("$line")
725
+ fi
726
+ done
727
+ (( \${#described} )) && _describe -V value described
728
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
729
+ return 0
730
+ }`;
731
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
732
+ if (shell === "fish")
733
+ return `${header}
734
+ ${FISH_FUNCTION}
735
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
736
+ `).join("")}`;
737
+ if (shell === "bash")
738
+ return `${header}
739
+ ${BASH_FUNCTION}
740
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
741
+ `;
742
+ return `${header}
743
+ ${ZSH_FUNCTION}
744
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
745
+ `;
746
+ }
747
+
748
+ // ../kit/src/notify.ts
749
+ import process11 from "process";
750
+ var NOTIFY_AFTER_MS = 1e4;
751
+ var CANCELLED = 130;
752
+ function base64(text) {
753
+ return Buffer.from(text).toString("base64");
754
+ }
755
+ function notification(title, body, env = process11.env) {
756
+ const id = `kit${process11.pid}`;
757
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
758
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
759
+ }
760
+ function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
761
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
762
+ return;
763
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
764
+ }
658
765
 
659
766
  // ../kit/src/usage.ts
660
767
  import { appendFileSync, mkdirSync } from "fs";
661
768
  import { homedir as homedir3 } from "os";
662
769
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
663
- import process11 from "process";
770
+ import process12 from "process";
664
771
 
665
772
  // ../kit/src/logs.ts
666
773
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -674,14 +781,14 @@ var usageError;
674
781
  function noteUsageError(message) {
675
782
  usageError = message;
676
783
  }
677
- function stateHome(env = process11.env) {
784
+ function stateHome(env = process12.env) {
678
785
  const dir = env.XDG_STATE_HOME;
679
786
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
680
787
  }
681
- function usagePath(env = process11.env) {
788
+ function usagePath(env = process12.env) {
682
789
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
683
790
  }
684
- function usageRecorded(env = process11.env) {
791
+ function usageRecorded(env = process12.env) {
685
792
  const off = env.KAYNOOO_CLI_NO_USAGE;
686
793
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
687
794
  }
@@ -695,7 +802,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
695
802
  usageError = undefined;
696
803
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
697
804
  }
698
- function recordUsage(entry, env = process11.env) {
805
+ function recordUsage(entry, env = process12.env) {
699
806
  if (!usageRecorded(env))
700
807
  return;
701
808
  try {
@@ -711,10 +818,14 @@ var LEVEL_OPTIONS = {
711
818
  ...OUTPUT_OPTIONS,
712
819
  help: { type: "boolean", short: "h", description: "show this help" }
713
820
  };
714
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
821
+ var TOP_OPTIONS = {
822
+ ...LEVEL_OPTIONS,
823
+ version: { type: "boolean", short: "v", description: "print the version" },
824
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
825
+ };
715
826
  function printError(prefix, message, hint, cause) {
716
- const colors = paint(process12.stderr);
717
- const styled = takesControlCodes(process12.stderr);
827
+ const colors = paint(process13.stderr);
828
+ const styled = takesControlCodes(process13.stderr);
718
829
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
719
830
  const under = (label, text, tint) => text === undefined ? "" : `
720
831
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -791,6 +902,19 @@ async function leafCandidates(run, words) {
791
902
  const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
792
903
  return values === undefined ? [FILES] : values.map(candidateLine);
793
904
  }
905
+ var COMPLETIONS = "--completions";
906
+ function flagValue([flag = "", ...rest]) {
907
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
908
+ }
909
+ function printCompletionScript(name, args) {
910
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
911
+ if (shell === undefined || args.length !== 1) {
912
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
913
+ return 2;
914
+ }
915
+ console.log(completionScript(shell, [name]).trimEnd());
916
+ return 0;
917
+ }
794
918
  async function printCandidates(found) {
795
919
  for (const line of await found)
796
920
  console.log(line);
@@ -814,16 +938,20 @@ function packageVersion(entry = Bun.main) {
814
938
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
815
939
  if (argv[0] === COMPLETE)
816
940
  return printCandidates(leafCandidates(run, argv.slice(1)));
941
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
942
+ return printCompletionScript(name, flagValue(argv));
817
943
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
818
944
  console.log(version ?? packageVersion());
819
945
  return 0;
820
946
  }
821
947
  let code;
948
+ const started = performance.now();
822
949
  try {
823
950
  code = await run(argv);
824
951
  } catch (error) {
825
952
  code = reportThrown(name, error, redact, wantsJson(argv));
826
953
  }
954
+ notifyEnd(name, code, performance.now() - started);
827
955
  if (usage !== false) {
828
956
  try {
829
957
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -841,13 +969,13 @@ var SESSION_FILES = new Glob("*.json");
841
969
  var ACCOUNT_DIRS = new Glob("*/sessions");
842
970
  // src/help.ts
843
971
  import { tmpdir } from "os";
844
- import process15 from "process";
972
+ import process16 from "process";
845
973
 
846
974
  // src/man.ts
847
975
  import { existsSync as existsSync3, readdirSync, readFileSync as readFileSync4 } from "fs";
848
976
  import { homedir as homedir4 } from "os";
849
977
  import { join as join6 } from "path";
850
- import process14 from "process";
978
+ import process15 from "process";
851
979
  var SECTIONS = ["1", "8", "6"];
852
980
  var SAFE_NAME = /^[\w.+-]+$/;
853
981
  var COMPRESSED_UNSUPPORTED = /\.(?:bz2|xz)$/;
@@ -866,7 +994,7 @@ function manDirs(env) {
866
994
  const configured = env.MANPATH?.split(":").filter((dir) => dir !== "") ?? [];
867
995
  return [...configured, "/usr/share/man", "/usr/local/share/man", join6(homedir4(), ".local/share/man")];
868
996
  }
869
- function findPage(name, env = process14.env) {
997
+ function findPage(name, env = process15.env) {
870
998
  if (!SAFE_NAME.test(name))
871
999
  return;
872
1000
  for (const section of SECTIONS) {
@@ -900,12 +1028,12 @@ function unOverstrike(text) {
900
1028
  return kept.join("");
901
1029
  }
902
1030
  function render(source) {
903
- const result = Bun.spawnSync(["nroff", "-man", "-Tutf8", "-rLL=200n", "-rLT=200n"], { stdin: source, stdout: "pipe", stderr: "ignore", env: { ...process14.env, GROFF_NO_SGR: "1" } });
1031
+ const result = Bun.spawnSync(["nroff", "-man", "-Tutf8", "-rLL=200n", "-rLT=200n"], { stdin: source, stdout: "pipe", stderr: "ignore", env: { ...process15.env, GROFF_NO_SGR: "1" } });
904
1032
  if (result.exitCode !== 0)
905
1033
  return;
906
1034
  return stripAnsi(unOverstrike(result.stdout.toString())).replaceAll(UNICODE_HYPHENS, "-");
907
1035
  }
908
- function pageText(name, env = process14.env) {
1036
+ function pageText(name, env = process15.env) {
909
1037
  const path = findPage(name, env);
910
1038
  const source = path === undefined ? undefined : readSource(path);
911
1039
  return source === undefined ? undefined : render(source);
@@ -949,12 +1077,13 @@ function parseOptions(text) {
949
1077
  close();
950
1078
  continue;
951
1079
  }
952
- if (trimmed.startsWith("-") && (current === undefined || indent <= current.indent)) {
1080
+ if (trimmed.startsWith("-")) {
953
1081
  const [head = "", ...rest] = trimmed.split(HEAD_SPLIT);
954
1082
  const parsed = parseHead(head);
955
- if (parsed !== undefined) {
1083
+ const starts = current === undefined || indent <= current.indent || current.inline && rest.length > 0;
1084
+ if (parsed !== undefined && starts) {
956
1085
  close();
957
- current = { doc: { ...parsed, text: "" }, indent, lines: rest };
1086
+ current = { doc: { ...parsed, text: "" }, indent, inline: rest.length > 0, lines: rest };
958
1087
  continue;
959
1088
  }
960
1089
  }
@@ -985,7 +1114,7 @@ function summaryOf(text) {
985
1114
  function parsePage(name, text) {
986
1115
  return { name, summary: summaryOf(text), options: parseOptions(text) };
987
1116
  }
988
- function loadPage(name, env = process14.env) {
1117
+ function loadPage(name, env = process15.env) {
989
1118
  const text = pageText(name, env);
990
1119
  return text === undefined ? undefined : parsePage(name, text);
991
1120
  }
@@ -1016,7 +1145,7 @@ function helpOf(path, args, env) {
1016
1145
  ${result.stderr.toString()}`);
1017
1146
  return text.trim() === "" ? undefined : text;
1018
1147
  }
1019
- function loadHelp(name, subcommand, env = process15.env) {
1148
+ function loadHelp(name, subcommand, env = process16.env) {
1020
1149
  if (!SAFE_NAME2.test(name))
1021
1150
  return;
1022
1151
  const path = Bun.which(name, { PATH: env.PATH ?? "" });
@@ -1366,7 +1495,7 @@ function rows(entries, stream, depth) {
1366
1495
  return out;
1367
1496
  }
1368
1497
  function painter(kind, stream) {
1369
- const roles = { option: "label", value: "value", argument: "path", unknown: "warn" };
1498
+ const roles = { option: "id", value: "value", argument: "path", unknown: "warn" };
1370
1499
  return role(roles[kind], stream);
1371
1500
  }
1372
1501
  function noteText(note) {
@@ -1384,7 +1513,7 @@ function block(gloss, stream, depth) {
1384
1513
  const origin = gloss.source === "help" ? " (from --help)" : "";
1385
1514
  out.push(`${margin}${role("accent", stream)(colors.bold(gloss.name))}${summary === undefined ? "" : colors.dim(` ${summary}`)}${colors.dim(origin)}`);
1386
1515
  const entries = [
1387
- ...gloss.assigns.map((assign) => ({ token: assign, paintToken: role("id", stream), text: "sets this variable for the command only" })),
1516
+ ...gloss.assigns.map((assign) => ({ token: assign, paintToken: role("value", stream), text: "sets this variable for the command only" })),
1388
1517
  ...gloss.notes.map((note) => ({ token: note.token, paintToken: painter(note.kind, stream), text: noteText(note) })),
1389
1518
  ...gloss.redirects.map((redirect) => ({ ...redirect, paintToken: role("path", stream) }))
1390
1519
  ];
@@ -1423,15 +1552,15 @@ function quote(word) {
1423
1552
  async function main(args) {
1424
1553
  const { values, positionals, rest } = parse(args, USAGE, OPTIONS, { rest: true, exits: EXITS, replaces: "explainshell in a browser, reading man pages for each flag", examples: ["gloss 'tar -xzvf a.tgz -C /tmp'", "gloss -- git commit -am fix"] });
1425
1554
  const typed = [...positionals.map(String), ...(rest ?? []).map(quote)].join(" ");
1426
- const line = typed === "" && !process16.stdin.isTTY ? (await Bun.stdin.text()).trim() : typed;
1555
+ const line = typed === "" && !process17.stdin.isTTY ? (await Bun.stdin.text()).trim() : typed;
1427
1556
  if (line === "")
1428
1557
  badUsage("give the command line to explain, quoted or after --");
1429
1558
  const result = analyze(line, { runHelp: values["run-help"] === true });
1430
1559
  if (values.json === true)
1431
1560
  printJson(result);
1432
1561
  else
1433
- console.log(render2(result, process16.stdout).join(`
1562
+ console.log(render2(result, process17.stdout).join(`
1434
1563
  `));
1435
1564
  return 0;
1436
1565
  }
1437
- process16.exitCode = await runMain({ name: "gloss", run: main });
1566
+ process17.exitCode = await runMain({ name: "gloss", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-gloss",
3
3
  "type": "module",
4
- "version": "0.0.1",
4
+ "version": "0.0.3",
5
5
  "description": "gloss: explains a shell command line, each word matched to what its man page says.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "gloss": "$npm_execpath src/gloss.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.38.2"
38
+ "@kaynooo/cli-kit": "0.41.0"
39
39
  }
40
40
  }