@kaynooo/cli-view 0.6.1 → 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 +270 -37
  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 process16 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,7 +392,7 @@ 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)) {
@@ -414,32 +431,44 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
414
431
  return [];
415
432
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
416
433
  }
434
+ var MAX_INLINE_CHOICES = 24;
417
435
  function optionRows(options, colors = paint(process8.stdout)) {
418
436
  const rows = Object.entries(options).map(([name, option]) => {
419
437
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
420
- 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>";
421
441
  const placeholder = option.optional === undefined ? named : `[${named}]`;
422
442
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
423
- 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 };
424
445
  });
425
446
  const width = Math.max(0, ...rows.map((row) => row.width));
426
447
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
427
448
  }
428
449
 
429
450
  // ../kit/src/text.ts
430
- 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;
431
452
  function stripAnsi(text) {
432
453
  return text.replace(ANSI, "");
433
454
  }
434
455
  function distance(a, b) {
435
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
436
- 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()) {
437
461
  const current = [i + 1];
438
- for (const [j, right] of [...b].entries())
439
- 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;
440
469
  previous = current;
441
470
  }
442
- return previous[b.length] ?? 0;
471
+ return previous[right.length] ?? 0;
443
472
  }
444
473
  function closest(name, names) {
445
474
  const started = names.find((known) => known.startsWith(name));
@@ -516,7 +545,7 @@ class Completing {
516
545
  }
517
546
  var completion = { active: false };
518
547
  var OUTPUT_OPTIONS = {
519
- 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" },
520
549
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
521
550
  };
522
551
  function applyOutput(color, plain, env = process10.env) {
@@ -720,13 +749,91 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
720
749
  // ../kit/src/cli.ts
721
750
  import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
722
751
  import { dirname as dirname3, join as join5 } from "path";
723
- import process13 from "process";
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
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
+ }
724
831
 
725
832
  // ../kit/src/usage.ts
726
833
  import { appendFileSync, mkdirSync } from "fs";
727
834
  import { homedir as homedir3 } from "os";
728
835
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
729
- import process12 from "process";
836
+ import process13 from "process";
730
837
 
731
838
  // ../kit/src/logs.ts
732
839
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -740,14 +847,14 @@ var usageError;
740
847
  function noteUsageError(message) {
741
848
  usageError = message;
742
849
  }
743
- function stateHome(env = process12.env) {
850
+ function stateHome(env = process13.env) {
744
851
  const dir = env.XDG_STATE_HOME;
745
852
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
746
853
  }
747
- function usagePath(env = process12.env) {
854
+ function usagePath(env = process13.env) {
748
855
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
749
856
  }
750
- function usageRecorded(env = process12.env) {
857
+ function usageRecorded(env = process13.env) {
751
858
  const off = env.KAYNOOO_CLI_NO_USAGE;
752
859
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
753
860
  }
@@ -761,7 +868,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
761
868
  usageError = undefined;
762
869
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
763
870
  }
764
- function recordUsage(entry, env = process12.env) {
871
+ function recordUsage(entry, env = process13.env) {
765
872
  if (!usageRecorded(env))
766
873
  return;
767
874
  try {
@@ -777,10 +884,14 @@ var LEVEL_OPTIONS = {
777
884
  ...OUTPUT_OPTIONS,
778
885
  help: { type: "boolean", short: "h", description: "show this help" }
779
886
  };
780
- 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
+ };
781
892
  function printError(prefix, message, hint, cause) {
782
- const colors = paint(process13.stderr);
783
- const styled = takesControlCodes(process13.stderr);
893
+ const colors = paint(process14.stderr);
894
+ const styled = takesControlCodes(process14.stderr);
784
895
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
785
896
  const under = (label, text, tint) => text === undefined ? "" : `
786
897
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -857,6 +968,19 @@ async function leafCandidates(run, words) {
857
968
  const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
858
969
  return values === undefined ? [FILES] : values.map(candidateLine);
859
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
+ }
860
984
  async function printCandidates(found) {
861
985
  for (const line of await found)
862
986
  console.log(line);
@@ -880,16 +1004,20 @@ function packageVersion(entry = Bun.main) {
880
1004
  async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
881
1005
  if (argv[0] === COMPLETE)
882
1006
  return printCandidates(leafCandidates(run, argv.slice(1)));
1007
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1008
+ return printCompletionScript(name, flagValue(argv));
883
1009
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
884
1010
  console.log(version ?? packageVersion());
885
1011
  return 0;
886
1012
  }
887
1013
  let code;
1014
+ const started = performance.now();
888
1015
  try {
889
1016
  code = await run(argv);
890
1017
  } catch (error) {
891
1018
  code = reportThrown(name, error, redact, wantsJson(argv));
892
1019
  }
1020
+ notifyEnd(name, code, performance.now() - started);
893
1021
  if (usage !== false) {
894
1022
  try {
895
1023
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1099,19 +1227,88 @@ function renderCode(source, name, theme, lineNumbers) {
1099
1227
  var TRAILING_NEWLINE2 = /\n$/;
1100
1228
  var HUNK = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@(.*)$/;
1101
1229
  var FILE_HEADER = /^diff --git a\/(.*) b\/(.*)$/;
1230
+ var NEW_FILE = /^\+\+\+ (?:b\/)?([^\t]*)/;
1102
1231
  var COMMIT = /^(commit )([0-9a-f]{7,40})(.*)$/;
1103
1232
  var HUNK_LINE = new Set([" ", "+", "-", "\\"]);
1104
1233
  var MARKERS = /^(?:--- |\+\+\+ )/;
1105
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)/;
1106
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;
1107
1241
  function looksLikeDiff(text) {
1108
1242
  const first = stripAnsi(text).split(`
1109
1243
  `).find((line) => line.trim() !== "") ?? "";
1110
1244
  return first.startsWith("diff --git ") || first.startsWith("--- ") || first.startsWith("@@ ") || first.startsWith("Index: ") || COMMIT.test(first);
1111
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
+ }
1112
1308
  function renderDiff(text, theme) {
1113
1309
  let oldLeft = 0;
1114
1310
  let newLeft = 0;
1311
+ let language;
1115
1312
  const lines = stripAnsi(text).replaceAll("\r", "").replace(TRAILING_NEWLINE2, "").split(`
1116
1313
  `).map((line) => {
1117
1314
  if ((oldLeft > 0 || newLeft > 0) && line !== "" && !HUNK_LINE.has(line[0] ?? ""))
@@ -1120,11 +1317,11 @@ function renderDiff(text, theme) {
1120
1317
  const mark = line[0];
1121
1318
  if (mark === "+") {
1122
1319
  newLeft--;
1123
- return theme.added(line);
1320
+ return { mark, text: line, language };
1124
1321
  }
1125
1322
  if (mark === "-") {
1126
1323
  oldLeft--;
1127
- return theme.removed(line);
1324
+ return { mark, text: line, language };
1128
1325
  }
1129
1326
  if (mark === "\\")
1130
1327
  return theme.dim(line);
@@ -1139,14 +1336,42 @@ function renderDiff(text, theme) {
1139
1336
  return `${theme.accent(line.slice(0, line.length - (hunk[3] ?? "").length))}${theme.dim(hunk[3] ?? "")}`;
1140
1337
  }
1141
1338
  const file = FILE_HEADER.exec(line);
1142
- if (file !== null)
1339
+ if (file !== null) {
1340
+ language = languageOf(file[2] ?? "");
1143
1341
  return `${theme.dim("diff")} ${theme.bold(theme.path(file[2] ?? ""))}`;
1342
+ }
1144
1343
  const commit = COMMIT.exec(line);
1145
1344
  if (commit !== null)
1146
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);
1147
1349
  return MARKERS.test(line) || META.test(line) || COMMIT_META.test(line) ? theme.dim(line) : line;
1148
1350
  });
1149
- 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(`
1150
1375
  `)}
1151
1376
  `;
1152
1377
  }
@@ -1339,8 +1564,8 @@ ${theme.dim("\u2500".repeat(rule))}
1339
1564
  }
1340
1565
 
1341
1566
  // src/theme.ts
1342
- import process15 from "process";
1343
- function themeFor(stream = process15.stdout, env = process15.env) {
1567
+ import process16 from "process";
1568
+ function themeFor(stream = process16.stdout, env = process16.env) {
1344
1569
  const colors = paint(stream, env);
1345
1570
  const accent = role("accent", stream, env);
1346
1571
  const path = role("path", stream, env);
@@ -1353,6 +1578,7 @@ function themeFor(stream = process15.stdout, env = process15.env) {
1353
1578
  bold: colors.bold,
1354
1579
  italic: colors.italic,
1355
1580
  strike: colors.strikethrough,
1581
+ changed: colors.inverse,
1356
1582
  added: colors.green,
1357
1583
  removed: colors.red,
1358
1584
  accent,
@@ -1370,8 +1596,8 @@ var MARKDOWN_FILE = /\.(?:md|markdown|mdx)$/i;
1370
1596
  var DIFF_FILE = /\.(?:diff|patch)$/i;
1371
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
1372
1598
 
1373
- 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.
1374
- 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.`;
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.`;
1375
1601
  var EXITS = [[0, "it showed the text"], [1, "there is nothing to show"], [2, "a usage error or a file that is missing"]];
1376
1602
  var OPTIONS = {
1377
1603
  diff: { type: "boolean", description: "show the text as a diff" },
@@ -1382,16 +1608,23 @@ var OPTIONS = {
1382
1608
  pager: { type: "boolean", description: "page a long output on a terminal (--no-pager turns it off)" },
1383
1609
  json: jsonOption("{kind: code, diff or markdown, language, text}, the text rendered without colour")
1384
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
+ }
1385
1618
  async function page(text) {
1386
1619
  try {
1387
- const pager = Bun.spawn(["less", "-FRX"], { stdin: "pipe", stdout: "inherit", stderr: "inherit" });
1620
+ const pager = Bun.spawn(pagerCommand(), { stdin: "pipe", stdout: "inherit", stderr: "inherit" });
1388
1621
  try {
1389
1622
  pager.stdin.write(text);
1390
1623
  await pager.stdin.end();
1391
1624
  } catch {}
1392
1625
  await pager.exited;
1393
1626
  } catch {
1394
- process16.stdout.write(text);
1627
+ process17.stdout.write(text);
1395
1628
  }
1396
1629
  }
1397
1630
  async function main(args) {
@@ -1404,8 +1637,8 @@ async function main(args) {
1404
1637
  const text = await readInput(path, { noStdin: "give a file, or pipe the text on stdin" });
1405
1638
  if (text.trim() === "")
1406
1639
  fail("nothing to show", 1);
1407
- const width = wholeNumber(values.width, "width", process16.stdout.isTTY === true ? process16.stdout.columns || DEFAULT_WIDTH : DEFAULT_WIDTH, 20);
1408
- const theme = themeFor(process16.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);
1409
1642
  const language = values.lang === undefined ? languageOf(path) : languageOf(values.lang);
1410
1643
  if (values.lang !== undefined && language === undefined)
1411
1644
  badUsage(`unknown language ${values.lang}`);
@@ -1422,12 +1655,12 @@ async function main(args) {
1422
1655
  printJson({ kind: isCode ? "code" : kind, language: isCode ? language ?? null : null, text: stripAnsi(render(themeFor({ isTTY: false }), values.lines ?? false)) });
1423
1656
  return 0;
1424
1657
  }
1425
- const shown = render(theme, values.lines ?? process16.stdout.isTTY === true);
1426
- if (process16.stdout.isTTY === true && values.pager !== false && shown.split(`
1427
- `).length > (process16.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))
1428
1661
  await page(shown);
1429
1662
  else
1430
- process16.stdout.write(shown);
1663
+ process17.stdout.write(shown);
1431
1664
  return 0;
1432
1665
  }
1433
- process16.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.1",
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.38.3"
38
+ "@kaynooo/cli-kit": "0.41.0"
39
39
  }
40
40
  }