@kaynooo/cli-view 0.6.0 → 0.7.0

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 +234 -57
  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));
@@ -692,21 +717,63 @@ 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/notify.ts
703
755
  import process12 from "process";
756
+ var NOTIFY_AFTER_MS = 1e4;
757
+ var CANCELLED = 130;
758
+ function base64(text) {
759
+ return Buffer.from(text).toString("base64");
760
+ }
761
+ function notification(title, body, env = process12.env) {
762
+ const id = `kit${process12.pid}`;
763
+ 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\\`];
764
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
765
+ }
766
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
767
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
768
+ return;
769
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
770
+ }
704
771
 
705
772
  // ../kit/src/usage.ts
706
773
  import { appendFileSync, mkdirSync } from "fs";
707
774
  import { homedir as homedir3 } from "os";
708
775
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
709
- import process11 from "process";
776
+ import process13 from "process";
710
777
 
711
778
  // ../kit/src/logs.ts
712
779
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -720,14 +787,14 @@ var usageError;
720
787
  function noteUsageError(message) {
721
788
  usageError = message;
722
789
  }
723
- function stateHome(env = process11.env) {
790
+ function stateHome(env = process13.env) {
724
791
  const dir = env.XDG_STATE_HOME;
725
792
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
726
793
  }
727
- function usagePath(env = process11.env) {
794
+ function usagePath(env = process13.env) {
728
795
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
729
796
  }
730
- function usageRecorded(env = process11.env) {
797
+ function usageRecorded(env = process13.env) {
731
798
  const off = env.KAYNOOO_CLI_NO_USAGE;
732
799
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
733
800
  }
@@ -741,7 +808,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
741
808
  usageError = undefined;
742
809
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
743
810
  }
744
- function recordUsage(entry, env = process11.env) {
811
+ function recordUsage(entry, env = process13.env) {
745
812
  if (!usageRecorded(env))
746
813
  return;
747
814
  try {
@@ -759,8 +826,8 @@ var LEVEL_OPTIONS = {
759
826
  };
760
827
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
761
828
  function printError(prefix, message, hint, cause) {
762
- const colors = paint(process12.stderr);
763
- const styled = takesControlCodes(process12.stderr);
829
+ const colors = paint(process14.stderr);
830
+ const styled = takesControlCodes(process14.stderr);
764
831
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
765
832
  const under = (label, text, tint) => text === undefined ? "" : `
766
833
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -804,24 +871,24 @@ function candidateLine(candidate) {
804
871
  }
805
872
  function positionalBeingTyped(before, { options, positionals }) {
806
873
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
807
- let index = 0;
874
+ const typed = [];
808
875
  let at = 0;
809
876
  while (at < before.length) {
810
877
  const word = before[at];
811
878
  if (word === "--") {
812
- index += before.length - at - 1;
879
+ typed.push(...before.slice(at + 1));
813
880
  break;
814
881
  }
815
882
  if (!word.startsWith("-"))
816
- index++;
883
+ typed.push(word);
817
884
  else if (takesValue(word))
818
885
  at++;
819
886
  at++;
820
887
  }
821
888
  const last = positionals.at(-1);
822
- if (index < positionals.length)
823
- return positionals[index];
824
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
889
+ if (typed.length < positionals.length)
890
+ return { name: positionals[typed.length], typed };
891
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
825
892
  }
826
893
  async function leafCandidates(run, words) {
827
894
  const completing = await completingOf(run);
@@ -829,12 +896,12 @@ async function leafCandidates(run, words) {
829
896
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
830
897
  const flag = words.at(-2);
831
898
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
899
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
832
900
  if (option?.type === "string") {
833
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
901
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
834
902
  return values === undefined ? [FILES] : values.map(candidateLine);
835
903
  }
836
- const name = positionalBeingTyped(words.slice(0, -1), completing);
837
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
904
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
838
905
  return values === undefined ? [FILES] : values.map(candidateLine);
839
906
  }
840
907
  async function printCandidates(found) {
@@ -843,9 +910,13 @@ async function printCandidates(found) {
843
910
  return 0;
844
911
  }
845
912
  function packageVersion(entry = Bun.main) {
846
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
913
+ let resolved = entry;
914
+ try {
915
+ resolved = realpathSync2(entry);
916
+ } catch {}
917
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
847
918
  try {
848
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
919
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
849
920
  if (typeof version === "string")
850
921
  return version;
851
922
  } catch {}
@@ -853,7 +924,7 @@ function packageVersion(entry = Bun.main) {
853
924
  return "0.0.0";
854
925
  }
855
926
  }
856
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
927
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
857
928
  if (argv[0] === COMPLETE)
858
929
  return printCandidates(leafCandidates(run, argv.slice(1)));
859
930
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -861,11 +932,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process12.a
861
932
  return 0;
862
933
  }
863
934
  let code;
935
+ const started = performance.now();
864
936
  try {
865
937
  code = await run(argv);
866
938
  } catch (error) {
867
939
  code = reportThrown(name, error, redact, wantsJson(argv));
868
940
  }
941
+ notifyEnd(name, code, performance.now() - started);
869
942
  if (usage !== false) {
870
943
  try {
871
944
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1075,19 +1148,88 @@ function renderCode(source, name, theme, lineNumbers) {
1075
1148
  var TRAILING_NEWLINE2 = /\n$/;
1076
1149
  var HUNK = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@(.*)$/;
1077
1150
  var FILE_HEADER = /^diff --git a\/(.*) b\/(.*)$/;
1151
+ var NEW_FILE = /^\+\+\+ (?:b\/)?([^\t]*)/;
1078
1152
  var COMMIT = /^(commit )([0-9a-f]{7,40})(.*)$/;
1079
1153
  var HUNK_LINE = new Set([" ", "+", "-", "\\"]);
1080
1154
  var MARKERS = /^(?:--- |\+\+\+ )/;
1081
1155
  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
1156
  var COMMIT_META = /^(?:Author|Date|Merge|AuthorDate|Commit|CommitDate):/;
1157
+ var TOKEN = /\w+|\s+|[^\w\s]/g;
1158
+ var WORD_CHAR = /\w/;
1159
+ var ESCAPE2 = /\x1B\[([0-9;]*)m/g;
1160
+ var CLOSING = new Set(["0", "22", "23", "24", "27", "29", "39", "49"]);
1161
+ var MAX_TOKENS = 300;
1083
1162
  function looksLikeDiff(text) {
1084
1163
  const first = stripAnsi(text).split(`
1085
1164
  `).find((line) => line.trim() !== "") ?? "";
1086
1165
  return first.startsWith("diff --git ") || first.startsWith("--- ") || first.startsWith("@@ ") || first.startsWith("Index: ") || COMMIT.test(first);
1087
1166
  }
1167
+ function changedChars(a, b) {
1168
+ const left = a.match(TOKEN) ?? [];
1169
+ const right = b.match(TOKEN) ?? [];
1170
+ if (left.length > MAX_TOKENS || right.length > MAX_TOKENS)
1171
+ return;
1172
+ const common = Array.from({ length: left.length + 1 }, () => Array.from({ length: right.length + 1 }).fill(0));
1173
+ for (let i = left.length - 1;i >= 0; i--) {
1174
+ for (let j = right.length - 1;j >= 0; j--)
1175
+ common[i][j] = left[i] === right[j] ? common[i + 1][j + 1] + 1 : Math.max(common[i + 1][j], common[i][j + 1]);
1176
+ }
1177
+ const flags = (tokens) => tokens.flatMap((token) => Array.from({ length: token.length }).fill(true));
1178
+ const changedLeft = flags(left);
1179
+ const changedRight = flags(right);
1180
+ let shared = false;
1181
+ let i = 0;
1182
+ let j = 0;
1183
+ let at = 0;
1184
+ let to = 0;
1185
+ while (i < left.length && j < right.length) {
1186
+ if (left[i] === right[j]) {
1187
+ shared ||= WORD_CHAR.test(left[i]);
1188
+ changedLeft.fill(false, at, at + left[i].length);
1189
+ changedRight.fill(false, to, to + right[j].length);
1190
+ at += left[i].length;
1191
+ to += right[j].length;
1192
+ i++;
1193
+ j++;
1194
+ } else if (common[i + 1][j] >= common[i][j + 1]) {
1195
+ at += left[i++].length;
1196
+ } else {
1197
+ to += right[j++].length;
1198
+ }
1199
+ }
1200
+ return shared ? [changedLeft, changedRight] : undefined;
1201
+ }
1202
+ function paintContent({ mark, text, language }, theme, changed) {
1203
+ const tone = mark === "+" ? theme.added : theme.removed;
1204
+ const code = text.slice(1);
1205
+ const source = language === undefined ? code : highlight(code, language, theme);
1206
+ const cells = [{ char: mark, style: "", changed: false }];
1207
+ let style = "";
1208
+ let from = 0;
1209
+ for (const escape of source.matchAll(ESCAPE2)) {
1210
+ for (const char of source.slice(from, escape.index).split(""))
1211
+ cells.push({ char, style, changed: changed?.[cells.length - 1] ?? false });
1212
+ style = CLOSING.has(escape[1]) ? "" : style + escape[0];
1213
+ from = escape.index + escape[0].length;
1214
+ }
1215
+ for (const char of source.slice(from).split(""))
1216
+ cells.push({ char, style, changed: changed?.[cells.length - 1] ?? false });
1217
+ let out = "";
1218
+ for (let at = 0;at < cells.length; ) {
1219
+ let end = at + 1;
1220
+ while (end < cells.length && cells[end].style === cells[at].style && cells[end].changed === cells[at].changed)
1221
+ end++;
1222
+ const run = cells.slice(at, end).map((cell) => cell.char).join("");
1223
+ const shown = cells[at].style === "" ? tone(run) : `${cells[at].style}${run}\x1B[0m`;
1224
+ out += cells[at].changed ? theme.changed(shown) : shown;
1225
+ at = end;
1226
+ }
1227
+ return out;
1228
+ }
1088
1229
  function renderDiff(text, theme) {
1089
1230
  let oldLeft = 0;
1090
1231
  let newLeft = 0;
1232
+ let language;
1091
1233
  const lines = stripAnsi(text).replaceAll("\r", "").replace(TRAILING_NEWLINE2, "").split(`
1092
1234
  `).map((line) => {
1093
1235
  if ((oldLeft > 0 || newLeft > 0) && line !== "" && !HUNK_LINE.has(line[0] ?? ""))
@@ -1096,11 +1238,11 @@ function renderDiff(text, theme) {
1096
1238
  const mark = line[0];
1097
1239
  if (mark === "+") {
1098
1240
  newLeft--;
1099
- return theme.added(line);
1241
+ return { mark, text: line, language };
1100
1242
  }
1101
1243
  if (mark === "-") {
1102
1244
  oldLeft--;
1103
- return theme.removed(line);
1245
+ return { mark, text: line, language };
1104
1246
  }
1105
1247
  if (mark === "\\")
1106
1248
  return theme.dim(line);
@@ -1115,14 +1257,42 @@ function renderDiff(text, theme) {
1115
1257
  return `${theme.accent(line.slice(0, line.length - (hunk[3] ?? "").length))}${theme.dim(hunk[3] ?? "")}`;
1116
1258
  }
1117
1259
  const file = FILE_HEADER.exec(line);
1118
- if (file !== null)
1260
+ if (file !== null) {
1261
+ language = languageOf(file[2] ?? "");
1119
1262
  return `${theme.dim("diff")} ${theme.bold(theme.path(file[2] ?? ""))}`;
1263
+ }
1120
1264
  const commit = COMMIT.exec(line);
1121
1265
  if (commit !== null)
1122
1266
  return `${theme.dim(commit[1] ?? "")}${theme.id(commit[2] ?? "")}${theme.dim(commit[3] ?? "")}`;
1267
+ const target = NEW_FILE.exec(line)?.[1];
1268
+ if (target !== undefined && target !== "/dev/null")
1269
+ language = languageOf(target);
1123
1270
  return MARKERS.test(line) || META.test(line) || COMMIT_META.test(line) ? theme.dim(line) : line;
1124
1271
  });
1125
- return `${lines.join(`
1272
+ const changes = new Map;
1273
+ for (let at = 0;at < lines.length; ) {
1274
+ const first = lines[at];
1275
+ const isRemoved = typeof first === "object" && first.mark === "-";
1276
+ if (!isRemoved) {
1277
+ at++;
1278
+ continue;
1279
+ }
1280
+ let split = at;
1281
+ while (typeof lines[split] === "object" && lines[split].mark === "-")
1282
+ split++;
1283
+ let end = split;
1284
+ while (typeof lines[end] === "object" && lines[end].mark === "+")
1285
+ end++;
1286
+ for (let pair = 0;pair < Math.min(split - at, end - split); pair++) {
1287
+ const flags = changedChars(lines[at + pair].text.slice(1), lines[split + pair].text.slice(1));
1288
+ if (flags !== undefined) {
1289
+ changes.set(at + pair, flags[0]);
1290
+ changes.set(split + pair, flags[1]);
1291
+ }
1292
+ }
1293
+ at = Math.max(end, at + 1);
1294
+ }
1295
+ return `${lines.map((line, index) => typeof line === "string" ? line : paintContent(line, theme, changes.get(index))).join(`
1126
1296
  `)}
1127
1297
  `;
1128
1298
  }
@@ -1315,8 +1485,8 @@ ${theme.dim("\u2500".repeat(rule))}
1315
1485
  }
1316
1486
 
1317
1487
  // src/theme.ts
1318
- import process14 from "process";
1319
- function themeFor(stream = process14.stdout, env = process14.env) {
1488
+ import process16 from "process";
1489
+ function themeFor(stream = process16.stdout, env = process16.env) {
1320
1490
  const colors = paint(stream, env);
1321
1491
  const accent = role("accent", stream, env);
1322
1492
  const path = role("path", stream, env);
@@ -1329,6 +1499,7 @@ function themeFor(stream = process14.stdout, env = process14.env) {
1329
1499
  bold: colors.bold,
1330
1500
  italic: colors.italic,
1331
1501
  strike: colors.strikethrough,
1502
+ changed: colors.inverse,
1332
1503
  added: colors.green,
1333
1504
  removed: colors.red,
1334
1505
  accent,
@@ -1346,10 +1517,9 @@ var MARKDOWN_FILE = /\.(?:md|markdown|mdx)$/i;
1346
1517
  var DIFF_FILE = /\.(?:diff|patch)$/i;
1347
1518
  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
1519
 
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.`;
1520
+ 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.
1521
+ 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.`;
1522
+ var EXITS = [[0, "it showed the text"], [1, "there is nothing to show"], [2, "a usage error or a file that is missing"]];
1353
1523
  var OPTIONS = {
1354
1524
  diff: { type: "boolean", description: "show the text as a diff" },
1355
1525
  markdown: { type: "boolean", description: "show the text as markdown" },
@@ -1359,20 +1529,27 @@ var OPTIONS = {
1359
1529
  pager: { type: "boolean", description: "page a long output on a terminal (--no-pager turns it off)" },
1360
1530
  json: jsonOption("{kind: code, diff or markdown, language, text}, the text rendered without colour")
1361
1531
  };
1532
+ function columnsOf(variable) {
1533
+ const columns = Number(variable);
1534
+ return Number.isInteger(columns) && columns >= 20 ? columns : DEFAULT_WIDTH;
1535
+ }
1536
+ function pagerCommand(pager = process17.env.PAGER) {
1537
+ return pager === undefined || pager.trim() === "" || pager.trim() === "less" ? ["less", "-FRX"] : ["sh", "-c", pager];
1538
+ }
1362
1539
  async function page(text) {
1363
1540
  try {
1364
- const pager = Bun.spawn(["less", "-FRX"], { stdin: "pipe", stdout: "inherit", stderr: "inherit" });
1541
+ const pager = Bun.spawn(pagerCommand(), { stdin: "pipe", stdout: "inherit", stderr: "inherit" });
1365
1542
  try {
1366
1543
  pager.stdin.write(text);
1367
1544
  await pager.stdin.end();
1368
1545
  } catch {}
1369
1546
  await pager.exited;
1370
1547
  } catch {
1371
- process15.stdout.write(text);
1548
+ process17.stdout.write(text);
1372
1549
  }
1373
1550
  }
1374
1551
  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"] });
1552
+ 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
1553
  if (positionals.length > 1)
1377
1554
  badUsage("give one file");
1378
1555
  if (values.diff === true && values.markdown === true)
@@ -1381,8 +1558,8 @@ async function main(args) {
1381
1558
  const text = await readInput(path, { noStdin: "give a file, or pipe the text on stdin" });
1382
1559
  if (text.trim() === "")
1383
1560
  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);
1561
+ const width = wholeNumber(values.width, "width", process17.stdout.isTTY === true ? process17.stdout.columns || DEFAULT_WIDTH : columnsOf(process17.env.COLUMNS), 20);
1562
+ const theme = themeFor(process17.stdout);
1386
1563
  const language = values.lang === undefined ? languageOf(path) : languageOf(values.lang);
1387
1564
  if (values.lang !== undefined && language === undefined)
1388
1565
  badUsage(`unknown language ${values.lang}`);
@@ -1399,12 +1576,12 @@ async function main(args) {
1399
1576
  printJson({ kind: isCode ? "code" : kind, language: isCode ? language ?? null : null, text: stripAnsi(render(themeFor({ isTTY: false }), values.lines ?? false)) });
1400
1577
  return 0;
1401
1578
  }
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))
1579
+ const shown = render(theme, values.lines ?? process17.stdout.isTTY === true);
1580
+ if (process17.stdout.isTTY === true && values.pager !== false && shown.split(`
1581
+ `).length > (process17.stdout.rows || 24))
1405
1582
  await page(shown);
1406
1583
  else
1407
- process15.stdout.write(shown);
1584
+ process17.stdout.write(shown);
1408
1585
  return 0;
1409
1586
  }
1410
- process15.exitCode = await runMain({ name: "view", run: main });
1587
+ 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.0",
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.40.0"
39
39
  }
40
40
  }