@kaynooo/cli-view 0.1.0 → 0.2.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 (3) hide show
  1. package/README.md +6 -2
  2. package/dist/view.js +395 -106
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @kaynooo/cli-view
2
2
 
3
- `view` shows a markdown file or a git diff in the colours of the other @kaynooo CLIs: the kit roles, wrapped to the terminal, paged through `less -FRX` when it is long.
3
+ `view` shows a markdown file or a git diff in the colours of the other @kaynooo CLIs: the kit roles, wrapped to the terminal, paged through `less -FRX` when it is long. It is for a person reading in a terminal, not for a Claude Code session, which reads files with its own tools.
4
4
 
5
5
  ```sh
6
6
  bun add -g @kaynooo/cli-view
@@ -9,10 +9,14 @@ bun add -g @kaynooo/cli-view
9
9
  | Command | What it does |
10
10
  | --- | --- |
11
11
  | `view README.md` | headings with their `#` marks, emphasis, lists with bullets by depth, numbers and task boxes, quotes and code blocks behind a bar, tables with wrapped cells, links as OSC 8 links |
12
+ | `view src/app.ts`, `view config.yaml` | source highlighted (comments, strings, numbers, keywords, keys) behind line numbers on a terminal; ts, js, json, yaml, toml, ini, py, sh, css, html, sql, rs, go, php, java, c, rb, lua, Dockerfile, Makefile |
13
+ | `view --lang ts`, `--no-lines` | read stdin as that language; leave the line numbers off |
12
14
  | `git diff \| view` | file headers, hunk ranges, added and removed lines coloured; a `git log -p` or `git show` too |
13
15
  | `view --diff`, `--markdown` | force the reading when the first line or the file name does not say |
14
16
  | `--width <n>`, `--no-pager` | wrap to a width instead of the terminal's, never page |
15
17
 
16
18
  The text is a file, or what is piped on stdin. A diff is recognised by its first line (`diff --git`, `--- `, `@@`, `commit <sha>`) or a `.diff` or `.patch` name; anything else is markdown. With `NO_COLOR`, a pipe or `--plain` it prints without colour: links as `text (url)`, images as `[image: alt]`.
17
19
 
18
- Not in v1: word-level diff highlighting and syntax highlighting of code blocks.
20
+ Code blocks in markdown are highlighted by their language too. The highlighting is a light tokenizer, not a parser: it gets comments, strings, numbers and keywords right for the common languages, and leaves a language it does not know uncoloured.
21
+
22
+ Not yet: word-level diff highlighting.
package/dist/view.js CHANGED
@@ -2,14 +2,13 @@
2
2
  // @bun
3
3
 
4
4
  // src/view.ts
5
- import process6 from "process";
6
-
5
+ import process10 from "process";
7
6
  // ../kit/src/args.ts
8
- import process2 from "process";
7
+ import process5 from "process";
9
8
  import { parseArgs } from "util";
10
9
 
11
10
  // ../kit/src/style.ts
12
- import process from "process";
11
+ import process2 from "process";
13
12
 
14
13
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
15
14
  function x(s) {
@@ -273,10 +272,10 @@ function le(i = {}) {
273
272
  var t = le();
274
273
 
275
274
  // ../kit/src/style.ts
276
- function takesControlCodes(stream, env = process.env) {
275
+ function takesControlCodes(stream, env = process2.env) {
277
276
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
278
277
  }
279
- function paint(stream, env = process.env) {
278
+ function paint(stream, env = process2.env) {
280
279
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
281
280
  }
282
281
  var ROLES = {
@@ -286,7 +285,7 @@ var ROLES = {
286
285
  label: (colors) => colors.dim,
287
286
  value: (colors) => colors.bold
288
287
  };
289
- function role(name, stream, env = process.env) {
288
+ function role(name, stream, env = process2.env) {
290
289
  return ROLES[name](paint(stream, env));
291
290
  }
292
291
  var STATUSES = {
@@ -297,7 +296,7 @@ var STATUSES = {
297
296
  skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
298
297
  };
299
298
  var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
300
- function link(text, url, stream, env = process.env) {
299
+ function link(text, url, stream, env = process2.env) {
301
300
  if (takesControlCodes(stream, env))
302
301
  return `\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`;
303
302
  return text === url ? text : `${text} (${url})`;
@@ -313,6 +312,63 @@ function textWidth(text) {
313
312
  return Bun.stringWidth(text);
314
313
  }
315
314
 
315
+ // ../kit/src/help.ts
316
+ import process3 from "process";
317
+ var OPTIONAL = /\[[^\]]+\]/g;
318
+ var USAGE_PREFIX = /^usage:\s*/i;
319
+ var FULL_STOP = /\.$/;
320
+ function usageLine(usage, colors = paint(process3.stdout)) {
321
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
322
+ }
323
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces, exits = [] } = {}) {
324
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
325
+ `);
326
+ }
327
+ function exitRows(exits, colors = paint(process3.stdout)) {
328
+ if (exits.length === 0)
329
+ return [];
330
+ const width = Math.max(...exits.map(([code]) => String(code).length));
331
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
332
+ }
333
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
334
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
335
+ }
336
+ function wantsHelpJson(env = process3.env) {
337
+ return env.KIT_HELP === "json";
338
+ }
339
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
340
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
341
+ `);
342
+ const first = lines[0];
343
+ const colon = first.indexOf(": ");
344
+ const prose = lines[lines.indexOf("") + 1] ?? "";
345
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
346
+ return {
347
+ synopsis: colon === -1 ? first : first.slice(0, colon),
348
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
349
+ ...replaces === undefined ? {} : { replaces },
350
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
351
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
352
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
353
+ };
354
+ }
355
+ function exampleRows(examples, colors = paint(process3.stdout)) {
356
+ if (examples.length === 0)
357
+ return [];
358
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
359
+ }
360
+ function optionRows(options, colors = paint(process3.stdout)) {
361
+ const rows = Object.entries(options).map(([name, option]) => {
362
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
363
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
364
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
365
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
366
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
367
+ });
368
+ const width = Math.max(0, ...rows.map((row) => row.width));
369
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
370
+ }
371
+
316
372
  // ../kit/src/text.ts
317
373
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
318
374
  function stripAnsi(text) {
@@ -335,8 +391,31 @@ function closest(name, names) {
335
391
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
336
392
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
337
393
  }
394
+ // ../kit/src/input.ts
395
+ import process4 from "process";
396
+ var WHOLE = /^\d+$/;
397
+ function wholeNumber(value, name, fallback, min = 1) {
398
+ if (value === undefined)
399
+ return fallback;
400
+ const number = Number(value);
401
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
402
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
403
+ return number;
404
+ }
405
+ async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
406
+ if (path === "-") {
407
+ if (process4.stdin.isTTY)
408
+ fail(noStdin);
409
+ return Bun.stdin.text();
410
+ }
411
+ const file = Bun.file(path);
412
+ if (!await file.exists())
413
+ fail(`no file ${path}`);
414
+ return file.text();
415
+ }
338
416
 
339
417
  // ../kit/src/args.ts
418
+ var DASHES = /^-+/;
340
419
  class Exit extends Error {
341
420
  code;
342
421
  hint;
@@ -376,58 +455,11 @@ class Completing {
376
455
  }
377
456
  }
378
457
  var completion = { active: false };
379
- var OPTIONAL = /\[[^\]]+\]/g;
380
- var USAGE_PREFIX = /^usage:\s*/i;
381
- var FULL_STOP = /\.$/;
382
- var DASHES = /^-+/;
383
- function usageLine(usage, colors = paint(process2.stdout)) {
384
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
385
- }
386
- function helpText(usage, options, colors = paint(process2.stdout), { examples = [], replaces } = {}) {
387
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
388
- `);
389
- }
390
- function replacesRows(replaces, colors = paint(process2.stdout)) {
391
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
392
- }
393
- function wantsHelpJson(env = process2.env) {
394
- return env.KIT_HELP === "json";
395
- }
396
- function description(usage, { examples = [], replaces } = {}) {
397
- const lines = usage.replace(USAGE_PREFIX, "").split(`
398
- `);
399
- const first = lines[0];
400
- const colon = first.indexOf(": ");
401
- const prose = lines[lines.indexOf("") + 1] ?? "";
402
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
403
- return {
404
- synopsis: colon === -1 ? first : first.slice(0, colon),
405
- summary: colon === -1 ? fallback : first.slice(colon + 2),
406
- ...replaces === undefined ? {} : { replaces },
407
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
408
- };
409
- }
410
- function exampleRows(examples, colors = paint(process2.stdout)) {
411
- if (examples.length === 0)
412
- return [];
413
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
414
- }
415
- function optionRows(options, colors = paint(process2.stdout)) {
416
- const rows = Object.entries(options).map(([name, option]) => {
417
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
418
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
419
- const placeholder = option.optional === undefined ? named : `[${named}]`;
420
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
421
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
422
- });
423
- const width = Math.max(0, ...rows.map((row) => row.width));
424
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
425
- }
426
458
  var OUTPUT_OPTIONS = {
427
459
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
428
460
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
429
461
  };
430
- function applyOutput(color, plain, env = process2.env) {
462
+ function applyOutput(color, plain, env = process5.env) {
431
463
  const when = plain === true ? "never" : color ?? "auto";
432
464
  if (when === "auto")
433
465
  return;
@@ -450,7 +482,7 @@ function parse(args, usage, options, settings = {}) {
450
482
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
451
483
  let parsed;
452
484
  try {
453
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
485
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
454
486
  } catch (error) {
455
487
  const message = parseError(error);
456
488
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -458,7 +490,7 @@ function parse(args, usage, options, settings = {}) {
458
490
  const values = parsed.values;
459
491
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
460
492
  if (values.help === true) {
461
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
493
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
462
494
  throw new HelpShown;
463
495
  }
464
496
  checkChoices(parsed.values, all);
@@ -500,6 +532,18 @@ function listed(options, allowNegative) {
500
532
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
501
533
  }));
502
534
  }
535
+ function withAliases(args, options) {
536
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
537
+ if (named.size === 0)
538
+ return args;
539
+ const separator = args.indexOf("--");
540
+ const own = separator === -1 ? args : args.slice(0, separator);
541
+ return [...own.map((arg) => {
542
+ const at = arg.indexOf("=");
543
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
544
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
545
+ }), ...separator === -1 ? [] : args.slice(separator)];
546
+ }
503
547
  function withBare(args, options) {
504
548
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
505
549
  if (bare.size === 0)
@@ -584,41 +628,75 @@ function nearestOption(message, options, allowNegative) {
584
628
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
585
629
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
586
630
  }
587
- var WHOLE = /^\d+$/;
588
- function wholeNumber(value, name, fallback, min = 1) {
589
- if (value === undefined)
590
- return fallback;
591
- const number = Number(value);
592
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
593
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
594
- return number;
595
- }
596
- async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
597
- if (path === "-") {
598
- if (process2.stdin.isTTY)
599
- fail(noStdin);
600
- return Bun.stdin.text();
601
- }
602
- const file = Bun.file(path);
603
- if (!await file.exists())
604
- fail(`no file ${path}`);
605
- return file.text();
606
- }
607
631
  // ../kit/src/progress.ts
608
632
  var ESC = String.fromCharCode(27);
609
633
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
610
634
  var RESET_STYLE = `${ESC}[0m`;
611
635
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
612
636
  // ../kit/src/cli.ts
613
- import process3 from "process";
637
+ import { readFileSync, realpathSync } from "fs";
638
+ import { dirname as dirname2, join as join2 } from "path";
639
+ import process7 from "process";
640
+
641
+ // ../kit/src/usage.ts
642
+ import { appendFileSync, mkdirSync } from "fs";
643
+ import { homedir } from "os";
644
+ import { dirname, isAbsolute, join } from "path";
645
+ import process6 from "process";
646
+
647
+ // ../kit/src/logs.ts
648
+ var DAY_MS = 24 * 60 * 60 * 1000;
649
+ var CLI_FOLDER = "kaynooo-cli";
650
+
651
+ // ../kit/src/usage.ts
652
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
653
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
654
+ var LONGEST_NAME = 40;
655
+ var usageError;
656
+ function noteUsageError(message) {
657
+ usageError = message;
658
+ }
659
+ function stateHome(env = process6.env) {
660
+ const dir = env.XDG_STATE_HOME;
661
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
662
+ }
663
+ function usagePath(env = process6.env) {
664
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
665
+ }
666
+ function usageRecorded(env = process6.env) {
667
+ const off = env.KAYNOOO_CLI_NO_USAGE;
668
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
669
+ }
670
+ function flagNames(argv) {
671
+ const end = argv.indexOf("--");
672
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
673
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
674
+ }
675
+ function usageEntry(bin, command, argv, code, now = new Date) {
676
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
677
+ usageError = undefined;
678
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
679
+ }
680
+ function recordUsage(entry, env = process6.env) {
681
+ if (!usageRecorded(env))
682
+ return;
683
+ try {
684
+ const path = usagePath(env);
685
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
686
+ appendFileSync(path, `${JSON.stringify(entry)}
687
+ `, { mode: 384 });
688
+ } catch {}
689
+ }
690
+
691
+ // ../kit/src/cli.ts
614
692
  var LEVEL_OPTIONS = {
615
693
  ...OUTPUT_OPTIONS,
616
694
  help: { type: "boolean", short: "h", description: "show this help" }
617
695
  };
618
696
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
619
697
  function printError(prefix, message, hint, cause) {
620
- const colors = paint(process3.stderr);
621
- const styled = takesControlCodes(process3.stderr);
698
+ const colors = paint(process7.stderr);
699
+ const styled = takesControlCodes(process7.stderr);
622
700
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
623
701
  const under = (label, text, tint) => text === undefined ? "" : `
624
702
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -637,6 +715,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
637
715
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
638
716
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
639
717
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
718
+ if (error instanceof UsageError)
719
+ noteUsageError(error.message);
640
720
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
641
721
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
642
722
  return error instanceof Exit ? error.code : 1;
@@ -698,32 +778,221 @@ async function printCandidates(found) {
698
778
  console.log(line);
699
779
  return 0;
700
780
  }
701
- async function runMain({ name, version, run, redact }, argv = process3.argv.slice(2)) {
781
+ function packageVersion(entry = Bun.main) {
782
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
783
+ try {
784
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
785
+ if (typeof version === "string")
786
+ return version;
787
+ } catch {}
788
+ if (dirname2(dir) === dir)
789
+ return "0.0.0";
790
+ }
791
+ }
792
+ async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
702
793
  if (argv[0] === COMPLETE)
703
794
  return printCandidates(leafCandidates(run, argv.slice(1)));
704
795
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
705
- console.log(version);
796
+ console.log(version ?? packageVersion());
706
797
  return 0;
707
798
  }
799
+ let code;
708
800
  try {
709
- return await run(argv);
801
+ code = await run(argv);
710
802
  } catch (error) {
711
- return reportThrown(name, error, redact, wantsJson(argv));
803
+ code = reportThrown(name, error, redact, wantsJson(argv));
804
+ }
805
+ if (usage !== false) {
806
+ try {
807
+ recordUsage(usageEntry(name, undefined, argv, code));
808
+ } catch {}
712
809
  }
810
+ return code;
713
811
  }
714
- // ../kit/src/logs.ts
715
- var DAY_MS = 24 * 60 * 60 * 1000;
716
812
  // ../kit/src/secrets.ts
717
813
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
718
814
  // ../kit/src/sessions.ts
719
815
  var {Glob } = globalThis.Bun;
720
816
  var SESSION_FILES = new Glob("*.json");
721
817
  var ACCOUNT_DIRS = new Glob("*/sessions");
722
- // package.json
723
- var version = "0.1.0";
818
+ // src/code.ts
819
+ var WORD_START = /[a-z_$]/i;
820
+ var WORD = /^[\w$-]+/;
821
+ var NUMBER = /^(?:0x[\da-f_]+|\d[\d_]*(?:\.\d[\d_]*)?(?:e[+-]?\d+)?)/i;
822
+ var PREVIOUS_WORD = /[\w$]$/;
823
+ var AFTER_KEY = /^\s*:/;
824
+ var YAML_KEY = /^(\s*(?:- )?)([\w.\-/]+)(?=:(?:\s|$))/;
825
+ var SETTING_KEY = /^(\s*)([\w.-]+)(?=\s*[=:])/;
826
+ var SECTION = /^\s*\[.*\]\s*$/;
827
+ var DIGIT = /\d/;
828
+ var TRAILING_NEWLINE = /\n$/;
829
+ var LEADING_DOT = /^\./;
830
+ var TRIPLE_QUOTES = ['"""', "'''"];
831
+ function words(list) {
832
+ return new Set(list.split(" "));
833
+ }
834
+ var SLASHES = { line: ["//"], block: ["/*", "*/"] };
835
+ var HASH = { line: ["#"] };
836
+ var CONSTANTS = "true false null undefined NaN Infinity";
837
+ var C_LIKE = "if else for while do switch case default break continue return throw try catch finally new delete typeof instanceof in of void yield await async static public private protected readonly abstract extends implements super this";
838
+ var SCRIPT = `${C_LIKE} const let var function class import export from as type interface enum namespace declare satisfies keyof is get set ${CONSTANTS}`;
839
+ var LANGUAGES = {
840
+ script: { ...SLASHES, quotes: "\"'`", keywords: words(SCRIPT) },
841
+ json: { line: [], quotes: '"', keywords: words("true false null"), quotedKeys: true },
842
+ jsonc: { ...SLASHES, quotes: '"', keywords: words("true false null"), quotedKeys: true },
843
+ python: { ...HASH, quotes: `"'`, keywords: words("def class return if elif else for while in not and or is import from as with try except finally raise pass break continue lambda yield async await global nonlocal del assert None True False self") },
844
+ shell: { ...HASH, quotes: "\"'`", keywords: words("if then else elif fi for while until do done case esac in function return exit local export set unset source alias echo cd end switch begin and or not") },
845
+ yaml: { ...HASH, quotes: `"'`, keywords: words("true false null yes no"), key: YAML_KEY, quotedKeys: true },
846
+ toml: { ...HASH, quotes: `"'`, keywords: words("true false"), key: SETTING_KEY, section: SECTION },
847
+ ini: { line: ["#", ";"], quotes: `"'`, keywords: words("true false yes no on off"), key: SETTING_KEY, section: SECTION },
848
+ css: { line: [], block: ["/*", "*/"], quotes: `"'`, keywords: words("important inherit initial unset auto none") },
849
+ html: { line: [], block: ["<!--", "-->"], quotes: `"'`, keywords: words("") },
850
+ sql: { line: ["--"], block: ["/*", "*/"], quotes: "\"'`", keywords: words("select from where and or not insert into values update set delete create alter drop table index view join left right inner outer full on group by order having limit offset as distinct union all null is in like between case when then else end primary key foreign references default unique with returning true false") },
851
+ rust: { ...SLASHES, quotes: '"', keywords: words("fn let mut const static struct enum impl trait pub use mod crate self super if else match for while loop break continue return as in ref move async await dyn where type unsafe true false None Some Ok Err") },
852
+ go: { ...SLASHES, quotes: "\"'`", keywords: words("func var const type struct interface map chan package import if else for range switch case default break continue return go defer select fallthrough goto nil true false") },
853
+ php: { ...SLASHES, line: ["//", "#"], quotes: `"'`, keywords: words(`${C_LIKE} function class interface trait namespace use public private protected static final echo array fn match list isset empty require include require_once include_once true false null`) },
854
+ java: { ...SLASHES, quotes: `"'`, keywords: words(`${C_LIKE} class interface enum package import final void int long double float boolean char byte short true false null var record`) },
855
+ c: { ...SLASHES, quotes: `"'`, keywords: words(`${C_LIKE} struct union typedef enum const volatile extern sizeof void int long double float char short unsigned signed auto register inline static include define ifdef ifndef endif pragma true false NULL nullptr class template typename namespace using bool`) },
856
+ ruby: { ...HASH, quotes: `"'`, keywords: words("def end class module if elsif else unless while until for in do begin rescue ensure return yield self nil true false and or not require require_relative include extend attr_accessor attr_reader puts then case when") },
857
+ lua: { line: ["--"], quotes: `"'`, keywords: words("function end if then else elseif for while do repeat until return local break in and or not nil true false") },
858
+ dockerfile: { ...HASH, quotes: `"'`, keywords: words("FROM RUN CMD LABEL EXPOSE ENV ADD COPY ENTRYPOINT VOLUME USER WORKDIR ARG ONBUILD STOPSIGNAL HEALTHCHECK SHELL AS") },
859
+ makefile: { ...HASH, quotes: `"'`, keywords: words("ifeq ifneq ifdef ifndef else endif include define endef export") }
860
+ };
861
+ var ALIASES = {
862
+ script: ["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs", "typescript", "javascript", "vue", "svelte"],
863
+ json: ["json", "jsonl", "ndjson"],
864
+ jsonc: ["jsonc", "json5"],
865
+ python: ["py", "python"],
866
+ shell: ["sh", "bash", "zsh", "fish", "shell", "console"],
867
+ yaml: ["yml", "yaml"],
868
+ toml: ["toml"],
869
+ ini: ["ini", "conf", "cfg", "properties", "editorconfig"],
870
+ css: ["css", "scss", "less"],
871
+ html: ["html", "htm", "xml", "svg"],
872
+ sql: ["sql"],
873
+ rust: ["rs", "rust"],
874
+ go: ["go", "golang"],
875
+ php: ["php"],
876
+ java: ["java", "kt", "kts", "cs", "swift", "dart", "scala"],
877
+ c: ["c", "h", "cpp", "cc", "hpp", "cxx"],
878
+ ruby: ["rb", "ruby"],
879
+ lua: ["lua"],
880
+ dockerfile: ["dockerfile", "containerfile"],
881
+ makefile: ["makefile", "mk", "just", "justfile"]
882
+ };
883
+ var BY_NAME = new Map(Object.entries(ALIASES).flatMap(([name, aliases]) => aliases.map((alias) => [alias, name])));
884
+ var EXTENSION = /\.([^./]+)$/;
885
+ var BASENAME = /[^/]*$/;
886
+ function languageOf(nameOrPath) {
887
+ const base = (BASENAME.exec(nameOrPath)?.[0] ?? "").toLowerCase();
888
+ const extension = EXTENSION.exec(base)?.[1];
889
+ return BY_NAME.get(extension ?? base) ?? BY_NAME.get(base.replace(LEADING_DOT, ""));
890
+ }
891
+ function paintLines(text, paint) {
892
+ return text.split(`
893
+ `).map((line) => line === "" ? line : paint(line)).join(`
894
+ `);
895
+ }
896
+ function stringEnd(source, start, quote) {
897
+ const triple = TRIPLE_QUOTES.find((each) => source.startsWith(each, start));
898
+ const multiline = quote === "`" || triple !== undefined;
899
+ const closer = triple ?? quote;
900
+ let at = start + closer.length;
901
+ while (at < source.length) {
902
+ const char = source.charAt(at);
903
+ if (char === "\\") {
904
+ at += 2;
905
+ } else if (source.startsWith(closer, at)) {
906
+ return at + closer.length;
907
+ } else if (char === `
908
+ ` && !multiline) {
909
+ return at;
910
+ } else {
911
+ at++;
912
+ }
913
+ }
914
+ return source.length;
915
+ }
916
+ function lineLead(line, language, theme) {
917
+ if (language.section?.test(line) === true)
918
+ return { done: theme.heading(line), rest: "" };
919
+ const match = language.key?.exec(line);
920
+ if (match === null || match === undefined)
921
+ return { done: "", rest: line };
922
+ return { done: `${match[1] ?? ""}${theme.accent(match[2] ?? "")}`, rest: line.slice(match[0].length) };
923
+ }
924
+ function highlight(source, name, theme) {
925
+ const language = LANGUAGES[name];
926
+ const text = source.replaceAll(`\r
927
+ `, `
928
+ `);
929
+ let out = "";
930
+ let at = 0;
931
+ while (at < text.length) {
932
+ const lineStart = at === 0 || text.charAt(at - 1) === `
933
+ `;
934
+ if (lineStart && (language.key !== undefined || language.section !== undefined)) {
935
+ const lineEnd = text.indexOf(`
936
+ `, at);
937
+ const line = text.slice(at, lineEnd === -1 ? text.length : lineEnd);
938
+ const { done, rest } = lineLead(line, language, theme);
939
+ if (done !== "") {
940
+ out += done;
941
+ at += line.length - rest.length;
942
+ continue;
943
+ }
944
+ }
945
+ const char = text.charAt(at);
946
+ const comment = language.line.find((each) => text.startsWith(each, at));
947
+ if (comment !== undefined) {
948
+ const end = text.indexOf(`
949
+ `, at);
950
+ const stop = end === -1 ? text.length : end;
951
+ out += paintLines(text.slice(at, stop), theme.dim);
952
+ at = stop;
953
+ } else if (language.block !== undefined && text.startsWith(language.block[0], at)) {
954
+ const end = text.indexOf(language.block[1], at + language.block[0].length);
955
+ const stop = end === -1 ? text.length : end + language.block[1].length;
956
+ out += paintLines(text.slice(at, stop), theme.dim);
957
+ at = stop;
958
+ } else if (language.quotes.includes(char)) {
959
+ const stop = stringEnd(text, at, char);
960
+ const isKey = language.quotedKeys === true && AFTER_KEY.test(text.slice(stop, !text.includes(`
961
+ `, stop) ? undefined : text.indexOf(`
962
+ `, stop)));
963
+ out += paintLines(text.slice(at, stop), isKey ? theme.accent : theme.string);
964
+ at = stop;
965
+ } else if (DIGIT.test(char) && !PREVIOUS_WORD.test(text.slice(Math.max(0, at - 1), at))) {
966
+ const number = NUMBER.exec(text.slice(at))?.[0] ?? char;
967
+ out += theme.number(number);
968
+ at += number.length;
969
+ } else if (WORD_START.test(char)) {
970
+ const word = WORD.exec(text.slice(at))?.[0] ?? char;
971
+ out += language.keywords.has(word) ? theme.keyword(word) : word;
972
+ at += word.length;
973
+ } else {
974
+ out += char;
975
+ at++;
976
+ }
977
+ }
978
+ return out;
979
+ }
980
+ function renderCode(source, name, theme, lineNumbers) {
981
+ const text = source.replace(TRAILING_NEWLINE, "");
982
+ const shown = name === undefined ? text : highlight(text, name, theme);
983
+ if (!lineNumbers)
984
+ return `${shown}
985
+ `;
986
+ const lines = shown.split(`
987
+ `);
988
+ const digits = String(lines.length).length;
989
+ return `${lines.map((line, index) => `${theme.dim(`${String(index + 1).padStart(digits)} \u2502`)} ${line}`.trimEnd()).join(`
990
+ `)}
991
+ `;
992
+ }
724
993
 
725
994
  // src/diff.ts
726
- var TRAILING_NEWLINE = /\n$/;
995
+ var TRAILING_NEWLINE2 = /\n$/;
727
996
  var HUNK = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@(.*)$/;
728
997
  var FILE_HEADER = /^diff --git a\/(.*) b\/(.*)$/;
729
998
  var COMMIT = /^(commit )([0-9a-f]{7,40})(.*)$/;
@@ -739,7 +1008,7 @@ function looksLikeDiff(text) {
739
1008
  function renderDiff(text, theme) {
740
1009
  let oldLeft = 0;
741
1010
  let newLeft = 0;
742
- const lines = stripAnsi(text).replaceAll("\r", "").replace(TRAILING_NEWLINE, "").split(`
1011
+ const lines = stripAnsi(text).replaceAll("\r", "").replace(TRAILING_NEWLINE2, "").split(`
743
1012
  `).map((line) => {
744
1013
  if ((oldLeft > 0 || newLeft > 0) && line !== "" && !HUNK_LINE.has(line[0] ?? ""))
745
1014
  oldLeft = newLeft = 0;
@@ -883,11 +1152,15 @@ function renderMarkdown(source, { theme, width }) {
883
1152
  html: (children) => block(`${theme.dim(trimmed(children))}
884
1153
 
885
1154
  `),
886
- code: (children) => block(`${trimmed(children).split(`
1155
+ code: (children, meta) => {
1156
+ const language = languageOf(meta?.language ?? "");
1157
+ const body = trimmed(children);
1158
+ return block(`${(language === undefined ? body : highlight(body, language, theme)).split(`
887
1159
  `).map((line) => `${bar}${line}`).join(`
888
1160
  `)}
889
1161
 
890
- `),
1162
+ `);
1163
+ },
891
1164
  blockquote: (children) => block(`${indent(trimmed(children.replaceAll(BLOCK, "")), quote, quote)}
892
1165
 
893
1166
  `),
@@ -936,8 +1209,8 @@ function renderMarkdown(source, { theme, width }) {
936
1209
  }
937
1210
 
938
1211
  // src/theme.ts
939
- import process5 from "process";
940
- function themeFor(stream = process5.stdout, env = process5.env) {
1212
+ import process9 from "process";
1213
+ function themeFor(stream = process9.stdout, env = process9.env) {
941
1214
  const colors = paint(stream, env);
942
1215
  const accent = role("accent", stream, env);
943
1216
  const path = role("path", stream, env);
@@ -953,6 +1226,9 @@ function themeFor(stream = process5.stdout, env = process5.env) {
953
1226
  added: colors.green,
954
1227
  removed: colors.red,
955
1228
  accent,
1229
+ keyword: colors.magenta,
1230
+ string: colors.green,
1231
+ number: colors.yellow,
956
1232
  link: (text, url) => path(colors.underline(link(text, url, stream, env)))
957
1233
  };
958
1234
  }
@@ -961,15 +1237,17 @@ function themeFor(stream = process5.stdout, env = process5.env) {
961
1237
  var DEFAULT_WIDTH = 80;
962
1238
  var MARKDOWN_FILE = /\.(?:md|markdown|mdx)$/i;
963
1239
  var DIFF_FILE = /\.(?:diff|patch)$/i;
964
- var USAGE = `view [options] [file]: shows a markdown file or a git diff in the colours of the other @kaynooo CLIs
1240
+ var USAGE = `view [options] [file]: shows a markdown file, a source file or a git diff in the colours of the other @kaynooo CLIs
965
1241
 
966
- A file, or what is piped on stdin (or - for stdin). 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.
1242
+ 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.
967
1243
  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.
968
1244
 
969
1245
  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.`;
970
1246
  var OPTIONS = {
971
1247
  diff: { type: "boolean", description: "show the text as a diff" },
972
1248
  markdown: { type: "boolean", description: "show the text as markdown" },
1249
+ lang: { type: "string", short: "l", description: "show the text as code in this language (ts, json, yaml, sh...)" },
1250
+ lines: { type: "boolean", description: "number the lines of code (--no-lines turns it off; on a terminal by default)" },
973
1251
  width: { type: "string", short: "w", description: "columns to wrap to, instead of the terminal's" },
974
1252
  pager: { type: "boolean", description: "page a long output on a terminal (--no-pager turns it off)" }
975
1253
  };
@@ -982,7 +1260,7 @@ async function page(text) {
982
1260
  } catch {}
983
1261
  await pager.exited;
984
1262
  } catch {
985
- process6.stdout.write(text);
1263
+ process10.stdout.write(text);
986
1264
  }
987
1265
  }
988
1266
  async function main(args) {
@@ -995,15 +1273,26 @@ async function main(args) {
995
1273
  const text = await readInput(path, { noStdin: "give a file, or pipe the text on stdin" });
996
1274
  if (text.trim() === "")
997
1275
  fail("nothing to show", 1);
998
- const width = wholeNumber(values.width, "width", process6.stdout.isTTY === true ? process6.stdout.columns || DEFAULT_WIDTH : DEFAULT_WIDTH, 20);
999
- const theme = themeFor(process6.stdout);
1000
- const isDiff = values.diff === true || values.markdown !== true && !MARKDOWN_FILE.test(path) && (DIFF_FILE.test(path) || looksLikeDiff(text));
1001
- const shown = isDiff ? renderDiff(text, theme) : renderMarkdown(text, { theme, width });
1002
- if (process6.stdout.isTTY === true && values.pager !== false && shown.split(`
1003
- `).length > (process6.stdout.rows || 24))
1276
+ const width = wholeNumber(values.width, "width", process10.stdout.isTTY === true ? process10.stdout.columns || DEFAULT_WIDTH : DEFAULT_WIDTH, 20);
1277
+ const theme = themeFor(process10.stdout);
1278
+ const language = values.lang === undefined ? languageOf(path) : languageOf(values.lang);
1279
+ if (values.lang !== undefined && language === undefined)
1280
+ badUsage(`unknown language ${values.lang}`);
1281
+ const forced = values.diff === true || values.markdown === true;
1282
+ const isCode = values.lang !== undefined || !forced && language !== undefined && !MARKDOWN_FILE.test(path) && !DIFF_FILE.test(path);
1283
+ const isDiff = !isCode && (values.diff === true || values.markdown !== true && !MARKDOWN_FILE.test(path) && (DIFF_FILE.test(path) || looksLikeDiff(text)));
1284
+ let shown;
1285
+ if (isCode)
1286
+ shown = renderCode(text, language, theme, values.lines ?? process10.stdout.isTTY === true);
1287
+ else if (isDiff)
1288
+ shown = renderDiff(text, theme);
1289
+ else
1290
+ shown = renderMarkdown(text, { theme, width });
1291
+ if (process10.stdout.isTTY === true && values.pager !== false && shown.split(`
1292
+ `).length > (process10.stdout.rows || 24))
1004
1293
  await page(shown);
1005
1294
  else
1006
- process6.stdout.write(shown);
1295
+ process10.stdout.write(shown);
1007
1296
  return 0;
1008
1297
  }
1009
- process6.exitCode = await runMain({ name: "view", version, run: main });
1298
+ process10.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.1.0",
4
+ "version": "0.2.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.19.0"
38
+ "@kaynooo/cli-kit": "0.21.0"
39
39
  }
40
40
  }