@kaynooo/cli-view 0.6.0 → 0.7.1

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/view.js +315 -59
  2. package/package.json +2 -2
package/dist/view.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/view.ts
5
- import process15 from "process";
5
+ import process17 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process10 from "process";
8
8
  import { parseArgs } from "util";
@@ -358,6 +358,23 @@ function link(text, url, stream, env = process6.env) {
358
358
  }
359
359
 
360
360
  // ../kit/src/format.ts
361
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
362
+ function formatSeconds(total) {
363
+ let rest = Math.max(0, Math.round(total));
364
+ const amounts = UNITS.map(([unit, size]) => {
365
+ const amount = Math.floor(rest / size);
366
+ rest -= amount * size;
367
+ return `${amount}${unit}`;
368
+ });
369
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
370
+ if (first === -1)
371
+ return "0s";
372
+ const next = amounts[first + 1];
373
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
374
+ }
375
+ function formatDuration(ms) {
376
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
377
+ }
361
378
  function upTo(text, separator) {
362
379
  const end = text.indexOf(separator);
363
380
  return end === -1 ? text : text.slice(0, end);
@@ -375,24 +392,20 @@ function printJson(value) {
375
392
 
376
393
  // ../kit/src/help.ts
377
394
  import process8 from "process";
378
- var OPTIONAL = /\[[^\]]+\]/g;
395
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
379
396
  var USAGE_PREFIX = /^usage:\s*/i;
380
397
  var FULL_STOP = /\.$/;
381
398
  function usageLine(usage, colors = paint(process8.stdout)) {
382
399
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
383
400
  }
384
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
385
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
401
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
402
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
386
403
  `);
387
404
  }
388
405
  function exitRows(exits, colors = paint(process8.stdout)) {
389
406
  if (exits.length === 0)
390
407
  return [];
391
- const width = Math.max(...exits.map(([code]) => String(code).length));
392
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
393
- }
394
- function replacesRows(replaces, colors = paint(process8.stdout)) {
395
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
408
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
396
409
  }
397
410
  function wantsHelpJson(env = process8.env) {
398
411
  return env.KIT_HELP === "json";
@@ -418,32 +431,44 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
418
431
  return [];
419
432
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
420
433
  }
434
+ var MAX_INLINE_CHOICES = 24;
421
435
  function optionRows(options, colors = paint(process8.stdout)) {
422
436
  const rows = Object.entries(options).map(([name, option]) => {
423
437
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
424
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
438
+ const choices = option.choices?.join("|");
439
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
440
+ const named = inline ? `<${choices}>` : "<value>";
425
441
  const placeholder = option.optional === undefined ? named : `[${named}]`;
426
442
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
427
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
443
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
444
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
428
445
  });
429
446
  const width = Math.max(0, ...rows.map((row) => row.width));
430
447
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
431
448
  }
432
449
 
433
450
  // ../kit/src/text.ts
434
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
451
+ var ANSI = /\x1B(?:\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[\x40-\x5A\x5C-\x5F])/g;
435
452
  function stripAnsi(text) {
436
453
  return text.replace(ANSI, "");
437
454
  }
438
455
  function distance(a, b) {
439
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
440
- for (const [i, left] of [...a].entries()) {
456
+ const left = [...a];
457
+ const right = [...b];
458
+ let before = [];
459
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
460
+ for (const [i, x] of left.entries()) {
441
461
  const current = [i + 1];
442
- for (const [j, right] of [...b].entries())
443
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
462
+ for (const [j, y] of right.entries()) {
463
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
464
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
465
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
466
+ current.push(cost);
467
+ }
468
+ before = previous;
444
469
  previous = current;
445
470
  }
446
- return previous[b.length] ?? 0;
471
+ return previous[right.length] ?? 0;
447
472
  }
448
473
  function closest(name, names) {
449
474
  const started = names.find((known) => known.startsWith(name));
@@ -520,7 +545,7 @@ class Completing {
520
545
  }
521
546
  var completion = { active: false };
522
547
  var OUTPUT_OPTIONS = {
523
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
548
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
524
549
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
525
550
  };
526
551
  function applyOutput(color, plain, env = process10.env) {
@@ -692,21 +717,123 @@ function nearestOption(message, options, allowNegative) {
692
717
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
693
718
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
694
719
  }
720
+ // ../kit/src/argv.ts
721
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
722
+ import { resolve as resolve3 } from "path";
723
+ import process11 from "process";
724
+ function commandLine() {
725
+ try {
726
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
727
+ } catch {
728
+ return;
729
+ }
730
+ }
731
+ function realPath(word) {
732
+ try {
733
+ return realpathSync(resolve3(word));
734
+ } catch {
735
+ return;
736
+ }
737
+ }
738
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
739
+ const target = script === undefined ? undefined : realPath(script) ?? script;
740
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
741
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
742
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
743
+ }
695
744
  // ../kit/src/progress.ts
696
745
  var ESC = String.fromCharCode(27);
697
746
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
698
747
  var RESET_STYLE = `${ESC}[0m`;
699
748
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
700
749
  // ../kit/src/cli.ts
701
- import { readFileSync as readFileSync2, realpathSync } from "fs";
750
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
702
751
  import { dirname as dirname3, join as join5 } from "path";
752
+ import process14 from "process";
753
+
754
+ // ../kit/src/completions.ts
755
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
756
+ 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'
757
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
758
+ set -l current (commandline -ct)
759
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
760
+ if test "$line" = __files__
761
+ __fish_complete_path $current
762
+ else
763
+ echo $line
764
+ end
765
+ end
766
+ end`;
767
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
768
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
769
+ local -a lines
770
+ COMPREPLY=()
771
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
772
+ for line in "\${lines[@]}"; do
773
+ if [[ $line == __files__ ]]; then
774
+ COMPREPLY+=($(compgen -f -- "$cur"))
775
+ else
776
+ words+="\${line%%$'\\t'*}"$'\\n'
777
+ fi
778
+ done
779
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
780
+ }`;
781
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
782
+ local line
783
+ local -a described plain
784
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
785
+ if [[ $line == __files__ ]]; then
786
+ _files
787
+ elif [[ $line == *$'\\t'* ]]; then
788
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
789
+ else
790
+ plain+=("$line")
791
+ fi
792
+ done
793
+ (( \${#described} )) && _describe -V value described
794
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
795
+ return 0
796
+ }`;
797
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
798
+ if (shell === "fish")
799
+ return `${header}
800
+ ${FISH_FUNCTION}
801
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
802
+ `).join("")}`;
803
+ if (shell === "bash")
804
+ return `${header}
805
+ ${BASH_FUNCTION}
806
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
807
+ `;
808
+ return `${header}
809
+ ${ZSH_FUNCTION}
810
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
811
+ `;
812
+ }
813
+
814
+ // ../kit/src/notify.ts
703
815
  import process12 from "process";
816
+ var NOTIFY_AFTER_MS = 1e4;
817
+ var CANCELLED = 130;
818
+ function base64(text) {
819
+ return Buffer.from(text).toString("base64");
820
+ }
821
+ function notification(title, body, env = process12.env) {
822
+ const id = `kit${process12.pid}`;
823
+ 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\\`];
824
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
825
+ }
826
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
827
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
828
+ return;
829
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
830
+ }
704
831
 
705
832
  // ../kit/src/usage.ts
706
833
  import { appendFileSync, mkdirSync } from "fs";
707
834
  import { homedir as homedir3 } from "os";
708
835
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
709
- import process11 from "process";
836
+ import process13 from "process";
710
837
 
711
838
  // ../kit/src/logs.ts
712
839
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -720,14 +847,14 @@ var usageError;
720
847
  function noteUsageError(message) {
721
848
  usageError = message;
722
849
  }
723
- function stateHome(env = process11.env) {
850
+ function stateHome(env = process13.env) {
724
851
  const dir = env.XDG_STATE_HOME;
725
852
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
726
853
  }
727
- function usagePath(env = process11.env) {
854
+ function usagePath(env = process13.env) {
728
855
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
729
856
  }
730
- function usageRecorded(env = process11.env) {
857
+ function usageRecorded(env = process13.env) {
731
858
  const off = env.KAYNOOO_CLI_NO_USAGE;
732
859
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
733
860
  }
@@ -741,7 +868,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
741
868
  usageError = undefined;
742
869
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
743
870
  }
744
- function recordUsage(entry, env = process11.env) {
871
+ function recordUsage(entry, env = process13.env) {
745
872
  if (!usageRecorded(env))
746
873
  return;
747
874
  try {
@@ -757,10 +884,14 @@ var LEVEL_OPTIONS = {
757
884
  ...OUTPUT_OPTIONS,
758
885
  help: { type: "boolean", short: "h", description: "show this help" }
759
886
  };
760
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
887
+ var TOP_OPTIONS = {
888
+ ...LEVEL_OPTIONS,
889
+ version: { type: "boolean", short: "v", description: "print the version" },
890
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
891
+ };
761
892
  function printError(prefix, message, hint, cause) {
762
- const colors = paint(process12.stderr);
763
- const styled = takesControlCodes(process12.stderr);
893
+ const colors = paint(process14.stderr);
894
+ const styled = takesControlCodes(process14.stderr);
764
895
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
765
896
  const under = (label, text, tint) => text === undefined ? "" : `
766
897
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -804,24 +935,24 @@ function candidateLine(candidate) {
804
935
  }
805
936
  function positionalBeingTyped(before, { options, positionals }) {
806
937
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
807
- let index = 0;
938
+ const typed = [];
808
939
  let at = 0;
809
940
  while (at < before.length) {
810
941
  const word = before[at];
811
942
  if (word === "--") {
812
- index += before.length - at - 1;
943
+ typed.push(...before.slice(at + 1));
813
944
  break;
814
945
  }
815
946
  if (!word.startsWith("-"))
816
- index++;
947
+ typed.push(word);
817
948
  else if (takesValue(word))
818
949
  at++;
819
950
  at++;
820
951
  }
821
952
  const last = positionals.at(-1);
822
- if (index < positionals.length)
823
- return positionals[index];
824
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
953
+ if (typed.length < positionals.length)
954
+ return { name: positionals[typed.length], typed };
955
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
825
956
  }
826
957
  async function leafCandidates(run, words) {
827
958
  const completing = await completingOf(run);
@@ -829,23 +960,40 @@ async function leafCandidates(run, words) {
829
960
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
830
961
  const flag = words.at(-2);
831
962
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
963
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
832
964
  if (option?.type === "string") {
833
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
965
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
834
966
  return values === undefined ? [FILES] : values.map(candidateLine);
835
967
  }
836
- const name = positionalBeingTyped(words.slice(0, -1), completing);
837
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
968
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
838
969
  return values === undefined ? [FILES] : values.map(candidateLine);
839
970
  }
971
+ var COMPLETIONS = "--completions";
972
+ function flagValue([flag = "", ...rest]) {
973
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
974
+ }
975
+ function printCompletionScript(name, args) {
976
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
977
+ if (shell === undefined || args.length !== 1) {
978
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
979
+ return 2;
980
+ }
981
+ console.log(completionScript(shell, [name]).trimEnd());
982
+ return 0;
983
+ }
840
984
  async function printCandidates(found) {
841
985
  for (const line of await found)
842
986
  console.log(line);
843
987
  return 0;
844
988
  }
845
989
  function packageVersion(entry = Bun.main) {
846
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
990
+ let resolved = entry;
991
+ try {
992
+ resolved = realpathSync2(entry);
993
+ } catch {}
994
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
847
995
  try {
848
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
996
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
849
997
  if (typeof version === "string")
850
998
  return version;
851
999
  } catch {}
@@ -853,19 +1001,23 @@ function packageVersion(entry = Bun.main) {
853
1001
  return "0.0.0";
854
1002
  }
855
1003
  }
856
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1004
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
857
1005
  if (argv[0] === COMPLETE)
858
1006
  return printCandidates(leafCandidates(run, argv.slice(1)));
1007
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1008
+ return printCompletionScript(name, flagValue(argv));
859
1009
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
860
1010
  console.log(version ?? packageVersion());
861
1011
  return 0;
862
1012
  }
863
1013
  let code;
1014
+ const started = performance.now();
864
1015
  try {
865
1016
  code = await run(argv);
866
1017
  } catch (error) {
867
1018
  code = reportThrown(name, error, redact, wantsJson(argv));
868
1019
  }
1020
+ notifyEnd(name, code, performance.now() - started);
869
1021
  if (usage !== false) {
870
1022
  try {
871
1023
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1075,19 +1227,88 @@ function renderCode(source, name, theme, lineNumbers) {
1075
1227
  var TRAILING_NEWLINE2 = /\n$/;
1076
1228
  var HUNK = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@(.*)$/;
1077
1229
  var FILE_HEADER = /^diff --git a\/(.*) b\/(.*)$/;
1230
+ var NEW_FILE = /^\+\+\+ (?:b\/)?([^\t]*)/;
1078
1231
  var COMMIT = /^(commit )([0-9a-f]{7,40})(.*)$/;
1079
1232
  var HUNK_LINE = new Set([" ", "+", "-", "\\"]);
1080
1233
  var MARKERS = /^(?:--- |\+\+\+ )/;
1081
1234
  var META = /^(?:index |old mode |new mode |deleted file mode |new file mode |similarity index |dissimilarity index |rename from |rename to |copy from |copy to |Binary files |GIT binary patch)/;
1082
1235
  var COMMIT_META = /^(?:Author|Date|Merge|AuthorDate|Commit|CommitDate):/;
1236
+ var TOKEN = /\w+|\s+|[^\w\s]/g;
1237
+ var WORD_CHAR = /\w/;
1238
+ var ESCAPE2 = /\x1B\[([0-9;]*)m/g;
1239
+ var CLOSING = new Set(["0", "22", "23", "24", "27", "29", "39", "49"]);
1240
+ var MAX_TOKENS = 300;
1083
1241
  function looksLikeDiff(text) {
1084
1242
  const first = stripAnsi(text).split(`
1085
1243
  `).find((line) => line.trim() !== "") ?? "";
1086
1244
  return first.startsWith("diff --git ") || first.startsWith("--- ") || first.startsWith("@@ ") || first.startsWith("Index: ") || COMMIT.test(first);
1087
1245
  }
1246
+ function changedChars(a, b) {
1247
+ const left = a.match(TOKEN) ?? [];
1248
+ const right = b.match(TOKEN) ?? [];
1249
+ if (left.length > MAX_TOKENS || right.length > MAX_TOKENS)
1250
+ return;
1251
+ const common = Array.from({ length: left.length + 1 }, () => Array.from({ length: right.length + 1 }).fill(0));
1252
+ for (let i = left.length - 1;i >= 0; i--) {
1253
+ for (let j = right.length - 1;j >= 0; j--)
1254
+ common[i][j] = left[i] === right[j] ? common[i + 1][j + 1] + 1 : Math.max(common[i + 1][j], common[i][j + 1]);
1255
+ }
1256
+ const flags = (tokens) => tokens.flatMap((token) => Array.from({ length: token.length }).fill(true));
1257
+ const changedLeft = flags(left);
1258
+ const changedRight = flags(right);
1259
+ let shared = false;
1260
+ let i = 0;
1261
+ let j = 0;
1262
+ let at = 0;
1263
+ let to = 0;
1264
+ while (i < left.length && j < right.length) {
1265
+ if (left[i] === right[j]) {
1266
+ shared ||= WORD_CHAR.test(left[i]);
1267
+ changedLeft.fill(false, at, at + left[i].length);
1268
+ changedRight.fill(false, to, to + right[j].length);
1269
+ at += left[i].length;
1270
+ to += right[j].length;
1271
+ i++;
1272
+ j++;
1273
+ } else if (common[i + 1][j] >= common[i][j + 1]) {
1274
+ at += left[i++].length;
1275
+ } else {
1276
+ to += right[j++].length;
1277
+ }
1278
+ }
1279
+ return shared ? [changedLeft, changedRight] : undefined;
1280
+ }
1281
+ function paintContent({ mark, text, language }, theme, changed) {
1282
+ const tone = mark === "+" ? theme.added : theme.removed;
1283
+ const code = text.slice(1);
1284
+ const source = language === undefined ? code : highlight(code, language, theme);
1285
+ const cells = [{ char: mark, style: "", changed: false }];
1286
+ let style = "";
1287
+ let from = 0;
1288
+ for (const escape of source.matchAll(ESCAPE2)) {
1289
+ for (const char of source.slice(from, escape.index).split(""))
1290
+ cells.push({ char, style, changed: changed?.[cells.length - 1] ?? false });
1291
+ style = CLOSING.has(escape[1]) ? "" : style + escape[0];
1292
+ from = escape.index + escape[0].length;
1293
+ }
1294
+ for (const char of source.slice(from).split(""))
1295
+ cells.push({ char, style, changed: changed?.[cells.length - 1] ?? false });
1296
+ let out = "";
1297
+ for (let at = 0;at < cells.length; ) {
1298
+ let end = at + 1;
1299
+ while (end < cells.length && cells[end].style === cells[at].style && cells[end].changed === cells[at].changed)
1300
+ end++;
1301
+ const run = cells.slice(at, end).map((cell) => cell.char).join("");
1302
+ const shown = cells[at].style === "" ? tone(run) : `${cells[at].style}${run}\x1B[0m`;
1303
+ out += cells[at].changed ? theme.changed(shown) : shown;
1304
+ at = end;
1305
+ }
1306
+ return out;
1307
+ }
1088
1308
  function renderDiff(text, theme) {
1089
1309
  let oldLeft = 0;
1090
1310
  let newLeft = 0;
1311
+ let language;
1091
1312
  const lines = stripAnsi(text).replaceAll("\r", "").replace(TRAILING_NEWLINE2, "").split(`
1092
1313
  `).map((line) => {
1093
1314
  if ((oldLeft > 0 || newLeft > 0) && line !== "" && !HUNK_LINE.has(line[0] ?? ""))
@@ -1096,11 +1317,11 @@ function renderDiff(text, theme) {
1096
1317
  const mark = line[0];
1097
1318
  if (mark === "+") {
1098
1319
  newLeft--;
1099
- return theme.added(line);
1320
+ return { mark, text: line, language };
1100
1321
  }
1101
1322
  if (mark === "-") {
1102
1323
  oldLeft--;
1103
- return theme.removed(line);
1324
+ return { mark, text: line, language };
1104
1325
  }
1105
1326
  if (mark === "\\")
1106
1327
  return theme.dim(line);
@@ -1115,14 +1336,42 @@ function renderDiff(text, theme) {
1115
1336
  return `${theme.accent(line.slice(0, line.length - (hunk[3] ?? "").length))}${theme.dim(hunk[3] ?? "")}`;
1116
1337
  }
1117
1338
  const file = FILE_HEADER.exec(line);
1118
- if (file !== null)
1339
+ if (file !== null) {
1340
+ language = languageOf(file[2] ?? "");
1119
1341
  return `${theme.dim("diff")} ${theme.bold(theme.path(file[2] ?? ""))}`;
1342
+ }
1120
1343
  const commit = COMMIT.exec(line);
1121
1344
  if (commit !== null)
1122
1345
  return `${theme.dim(commit[1] ?? "")}${theme.id(commit[2] ?? "")}${theme.dim(commit[3] ?? "")}`;
1346
+ const target = NEW_FILE.exec(line)?.[1];
1347
+ if (target !== undefined && target !== "/dev/null")
1348
+ language = languageOf(target);
1123
1349
  return MARKERS.test(line) || META.test(line) || COMMIT_META.test(line) ? theme.dim(line) : line;
1124
1350
  });
1125
- return `${lines.join(`
1351
+ const changes = new Map;
1352
+ for (let at = 0;at < lines.length; ) {
1353
+ const first = lines[at];
1354
+ const isRemoved = typeof first === "object" && first.mark === "-";
1355
+ if (!isRemoved) {
1356
+ at++;
1357
+ continue;
1358
+ }
1359
+ let split = at;
1360
+ while (typeof lines[split] === "object" && lines[split].mark === "-")
1361
+ split++;
1362
+ let end = split;
1363
+ while (typeof lines[end] === "object" && lines[end].mark === "+")
1364
+ end++;
1365
+ for (let pair = 0;pair < Math.min(split - at, end - split); pair++) {
1366
+ const flags = changedChars(lines[at + pair].text.slice(1), lines[split + pair].text.slice(1));
1367
+ if (flags !== undefined) {
1368
+ changes.set(at + pair, flags[0]);
1369
+ changes.set(split + pair, flags[1]);
1370
+ }
1371
+ }
1372
+ at = Math.max(end, at + 1);
1373
+ }
1374
+ return `${lines.map((line, index) => typeof line === "string" ? line : paintContent(line, theme, changes.get(index))).join(`
1126
1375
  `)}
1127
1376
  `;
1128
1377
  }
@@ -1315,8 +1564,8 @@ ${theme.dim("\u2500".repeat(rule))}
1315
1564
  }
1316
1565
 
1317
1566
  // src/theme.ts
1318
- import process14 from "process";
1319
- function themeFor(stream = process14.stdout, env = process14.env) {
1567
+ import process16 from "process";
1568
+ function themeFor(stream = process16.stdout, env = process16.env) {
1320
1569
  const colors = paint(stream, env);
1321
1570
  const accent = role("accent", stream, env);
1322
1571
  const path = role("path", stream, env);
@@ -1329,6 +1578,7 @@ function themeFor(stream = process14.stdout, env = process14.env) {
1329
1578
  bold: colors.bold,
1330
1579
  italic: colors.italic,
1331
1580
  strike: colors.strikethrough,
1581
+ changed: colors.inverse,
1332
1582
  added: colors.green,
1333
1583
  removed: colors.red,
1334
1584
  accent,
@@ -1346,10 +1596,9 @@ var MARKDOWN_FILE = /\.(?:md|markdown|mdx)$/i;
1346
1596
  var DIFF_FILE = /\.(?:diff|patch)$/i;
1347
1597
  var USAGE = `view [options] [file]: shows a markdown file, a source file or a git diff in the colours of the other @kaynooo CLIs
1348
1598
 
1349
- A file, or what is piped on stdin (or - for stdin). A source file (ts, js, json, yaml, toml, py, sh, css, sql, rs, go and more) is highlighted behind line numbers, by its extension or --lang. A diff, a \`git log -p\` or a \`git show\` is recognised by its first line or a .diff or .patch name, anything else is markdown; --diff and --markdown force one. Code blocks in markdown are highlighted by their language.
1350
- Lines wrap to the terminal width (80 when it is not a terminal) and a long output on a terminal goes through \`less -FRX\` unless --no-pager. No colour with NO_COLOR, a pipe or --plain.
1351
-
1352
- Exits 0 when it showed the text, 1 when there is nothing to show, 2 on a usage error or a file that is missing.`;
1599
+ A file, or what is piped on stdin (or - for stdin). A source file (ts, js, json, yaml, toml, py, sh, css, sql, rs, go and more) is highlighted behind line numbers, by its extension or --lang. A diff, a \`git log -p\` or a \`git show\` is recognised by its first line or a .diff or .patch name, in a diff the code is highlighted by the file's extension and the changed words of a paired removed and added line are reversed; anything else is markdown; --diff and --markdown force one. Code blocks in markdown are highlighted by their language.
1600
+ Lines wrap to the terminal width (COLUMNS or 80 when it is not a terminal) and a long output on a terminal goes through $PAGER, or \`less -FRX\` when it is unset or less, unless --no-pager. No colour with NO_COLOR, a pipe or --plain.`;
1601
+ var EXITS = [[0, "it showed the text"], [1, "there is nothing to show"], [2, "a usage error or a file that is missing"]];
1353
1602
  var OPTIONS = {
1354
1603
  diff: { type: "boolean", description: "show the text as a diff" },
1355
1604
  markdown: { type: "boolean", description: "show the text as markdown" },
@@ -1359,20 +1608,27 @@ var OPTIONS = {
1359
1608
  pager: { type: "boolean", description: "page a long output on a terminal (--no-pager turns it off)" },
1360
1609
  json: jsonOption("{kind: code, diff or markdown, language, text}, the text rendered without colour")
1361
1610
  };
1611
+ function columnsOf(variable) {
1612
+ const columns = Number(variable);
1613
+ return Number.isInteger(columns) && columns >= 20 ? columns : DEFAULT_WIDTH;
1614
+ }
1615
+ function pagerCommand(pager = process17.env.PAGER) {
1616
+ return pager === undefined || pager.trim() === "" || pager.trim() === "less" ? ["less", "-FRX"] : ["sh", "-c", pager];
1617
+ }
1362
1618
  async function page(text) {
1363
1619
  try {
1364
- const pager = Bun.spawn(["less", "-FRX"], { stdin: "pipe", stdout: "inherit", stderr: "inherit" });
1620
+ const pager = Bun.spawn(pagerCommand(), { stdin: "pipe", stdout: "inherit", stderr: "inherit" });
1365
1621
  try {
1366
1622
  pager.stdin.write(text);
1367
1623
  await pager.stdin.end();
1368
1624
  } catch {}
1369
1625
  await pager.exited;
1370
1626
  } catch {
1371
- process15.stdout.write(text);
1627
+ process17.stdout.write(text);
1372
1628
  }
1373
1629
  }
1374
1630
  async function main(args) {
1375
- const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[file]"], allowNegative: true, replaces: "cat, bat or less on a markdown file, delta on a diff", examples: ["view README.md", "git diff | view"] });
1631
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ["[file]"], allowNegative: true, replaces: "cat, bat or less on a markdown file, delta on a diff", examples: ["view README.md", "git diff | view"] });
1376
1632
  if (positionals.length > 1)
1377
1633
  badUsage("give one file");
1378
1634
  if (values.diff === true && values.markdown === true)
@@ -1381,8 +1637,8 @@ async function main(args) {
1381
1637
  const text = await readInput(path, { noStdin: "give a file, or pipe the text on stdin" });
1382
1638
  if (text.trim() === "")
1383
1639
  fail("nothing to show", 1);
1384
- const width = wholeNumber(values.width, "width", process15.stdout.isTTY === true ? process15.stdout.columns || DEFAULT_WIDTH : DEFAULT_WIDTH, 20);
1385
- const theme = themeFor(process15.stdout);
1640
+ const width = wholeNumber(values.width, "width", process17.stdout.isTTY === true ? process17.stdout.columns || DEFAULT_WIDTH : columnsOf(process17.env.COLUMNS), 20);
1641
+ const theme = themeFor(process17.stdout);
1386
1642
  const language = values.lang === undefined ? languageOf(path) : languageOf(values.lang);
1387
1643
  if (values.lang !== undefined && language === undefined)
1388
1644
  badUsage(`unknown language ${values.lang}`);
@@ -1399,12 +1655,12 @@ async function main(args) {
1399
1655
  printJson({ kind: isCode ? "code" : kind, language: isCode ? language ?? null : null, text: stripAnsi(render(themeFor({ isTTY: false }), values.lines ?? false)) });
1400
1656
  return 0;
1401
1657
  }
1402
- const shown = render(theme, values.lines ?? process15.stdout.isTTY === true);
1403
- if (process15.stdout.isTTY === true && values.pager !== false && shown.split(`
1404
- `).length > (process15.stdout.rows || 24))
1658
+ const shown = render(theme, values.lines ?? process17.stdout.isTTY === true);
1659
+ if (process17.stdout.isTTY === true && values.pager !== false && shown.split(`
1660
+ `).length > (process17.stdout.rows || 24))
1405
1661
  await page(shown);
1406
1662
  else
1407
- process15.stdout.write(shown);
1663
+ process17.stdout.write(shown);
1408
1664
  return 0;
1409
1665
  }
1410
- process15.exitCode = await runMain({ name: "view", run: main });
1666
+ process17.exitCode = await runMain({ name: "view", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-view",
3
3
  "type": "module",
4
- "version": "0.6.0",
4
+ "version": "0.7.1",
5
5
  "description": "view: markdown files and git diffs shown in the colours of the other @kaynooo CLIs, paged when long.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "view": "$npm_execpath src/view.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.36.0"
38
+ "@kaynooo/cli-kit": "0.41.0"
39
39
  }
40
40
  }