@kaynooo/cli-view 0.1.1 → 0.2.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.
- package/README.md +6 -2
- package/dist/view.js +283 -55
- 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
|
-
|
|
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
|
@@ -1,15 +1,14 @@
|
|
|
1
|
-
#!/usr/bin/env bun
|
|
1
|
+
#!/usr/bin/env -S bun --no-env-file
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/view.ts
|
|
5
|
-
import
|
|
6
|
-
|
|
5
|
+
import process10 from "process";
|
|
7
6
|
// ../kit/src/args.ts
|
|
8
|
-
import
|
|
7
|
+
import process5 from "process";
|
|
9
8
|
import { parseArgs } from "util";
|
|
10
9
|
|
|
11
10
|
// ../kit/src/style.ts
|
|
12
|
-
import
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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 =
|
|
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})`;
|
|
@@ -314,24 +313,30 @@ function textWidth(text) {
|
|
|
314
313
|
}
|
|
315
314
|
|
|
316
315
|
// ../kit/src/help.ts
|
|
317
|
-
import
|
|
316
|
+
import process3 from "process";
|
|
318
317
|
var OPTIONAL = /\[[^\]]+\]/g;
|
|
319
318
|
var USAGE_PREFIX = /^usage:\s*/i;
|
|
320
319
|
var FULL_STOP = /\.$/;
|
|
321
|
-
function usageLine(usage, colors = paint(
|
|
320
|
+
function usageLine(usage, colors = paint(process3.stdout)) {
|
|
322
321
|
return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
|
|
323
322
|
}
|
|
324
|
-
function helpText(usage, options, colors = paint(
|
|
325
|
-
return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
|
|
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(`
|
|
326
325
|
`);
|
|
327
326
|
}
|
|
328
|
-
function
|
|
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)) {
|
|
329
334
|
return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
|
|
330
335
|
}
|
|
331
|
-
function wantsHelpJson(env =
|
|
336
|
+
function wantsHelpJson(env = process3.env) {
|
|
332
337
|
return env.KIT_HELP === "json";
|
|
333
338
|
}
|
|
334
|
-
function description(usage, { examples = [], replaces } = {}) {
|
|
339
|
+
function description(usage, { examples = [], replaces, exits } = {}, options) {
|
|
335
340
|
const lines = usage.replace(USAGE_PREFIX, "").split(`
|
|
336
341
|
`);
|
|
337
342
|
const first = lines[0];
|
|
@@ -342,15 +347,17 @@ function description(usage, { examples = [], replaces } = {}) {
|
|
|
342
347
|
synopsis: colon === -1 ? first : first.slice(0, colon),
|
|
343
348
|
summary: colon === -1 ? fallback : first.slice(colon + 2),
|
|
344
349
|
...replaces === undefined ? {} : { replaces },
|
|
345
|
-
examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
|
|
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 } })) }
|
|
346
353
|
};
|
|
347
354
|
}
|
|
348
|
-
function exampleRows(examples, colors = paint(
|
|
355
|
+
function exampleRows(examples, colors = paint(process3.stdout)) {
|
|
349
356
|
if (examples.length === 0)
|
|
350
357
|
return [];
|
|
351
358
|
return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
|
|
352
359
|
}
|
|
353
|
-
function optionRows(options, colors = paint(
|
|
360
|
+
function optionRows(options, colors = paint(process3.stdout)) {
|
|
354
361
|
const rows = Object.entries(options).map(([name, option]) => {
|
|
355
362
|
const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
|
|
356
363
|
const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
|
|
@@ -385,7 +392,7 @@ function closest(name, names) {
|
|
|
385
392
|
return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
|
|
386
393
|
}
|
|
387
394
|
// ../kit/src/input.ts
|
|
388
|
-
import
|
|
395
|
+
import process4 from "process";
|
|
389
396
|
var WHOLE = /^\d+$/;
|
|
390
397
|
function wholeNumber(value, name, fallback, min = 1) {
|
|
391
398
|
if (value === undefined)
|
|
@@ -397,7 +404,7 @@ function wholeNumber(value, name, fallback, min = 1) {
|
|
|
397
404
|
}
|
|
398
405
|
async function readInput(path, { noStdin = "nothing is piped on stdin" } = {}) {
|
|
399
406
|
if (path === "-") {
|
|
400
|
-
if (
|
|
407
|
+
if (process4.stdin.isTTY)
|
|
401
408
|
fail(noStdin);
|
|
402
409
|
return Bun.stdin.text();
|
|
403
410
|
}
|
|
@@ -452,7 +459,7 @@ var OUTPUT_OPTIONS = {
|
|
|
452
459
|
color: { type: "string", description: "auto (on a terminal alone), always or never" },
|
|
453
460
|
plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
|
|
454
461
|
};
|
|
455
|
-
function applyOutput(color, plain, env =
|
|
462
|
+
function applyOutput(color, plain, env = process5.env) {
|
|
456
463
|
const when = plain === true ? "never" : color ?? "auto";
|
|
457
464
|
if (when === "auto")
|
|
458
465
|
return;
|
|
@@ -475,7 +482,7 @@ function parse(args, usage, options, settings = {}) {
|
|
|
475
482
|
const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
|
|
476
483
|
let parsed;
|
|
477
484
|
try {
|
|
478
|
-
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 });
|
|
479
486
|
} catch (error) {
|
|
480
487
|
const message = parseError(error);
|
|
481
488
|
throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
|
|
@@ -483,7 +490,7 @@ function parse(args, usage, options, settings = {}) {
|
|
|
483
490
|
const values = parsed.values;
|
|
484
491
|
applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
|
|
485
492
|
if (values.help === true) {
|
|
486
|
-
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));
|
|
487
494
|
throw new HelpShown;
|
|
488
495
|
}
|
|
489
496
|
checkChoices(parsed.values, all);
|
|
@@ -525,6 +532,18 @@ function listed(options, allowNegative) {
|
|
|
525
532
|
return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
|
|
526
533
|
}));
|
|
527
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
|
+
}
|
|
528
547
|
function withBare(args, options) {
|
|
529
548
|
const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
|
|
530
549
|
if (bare.size === 0)
|
|
@@ -615,13 +634,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
|
|
|
615
634
|
var RESET_STYLE = `${ESC}[0m`;
|
|
616
635
|
var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
|
|
617
636
|
// ../kit/src/cli.ts
|
|
618
|
-
import
|
|
637
|
+
import { readFileSync, realpathSync } from "fs";
|
|
638
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
639
|
+
import process7 from "process";
|
|
619
640
|
|
|
620
641
|
// ../kit/src/usage.ts
|
|
621
642
|
import { appendFileSync, mkdirSync } from "fs";
|
|
622
643
|
import { homedir } from "os";
|
|
623
644
|
import { dirname, isAbsolute, join } from "path";
|
|
624
|
-
import
|
|
645
|
+
import process6 from "process";
|
|
625
646
|
|
|
626
647
|
// ../kit/src/logs.ts
|
|
627
648
|
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -635,14 +656,14 @@ var usageError;
|
|
|
635
656
|
function noteUsageError(message) {
|
|
636
657
|
usageError = message;
|
|
637
658
|
}
|
|
638
|
-
function stateHome(env =
|
|
659
|
+
function stateHome(env = process6.env) {
|
|
639
660
|
const dir = env.XDG_STATE_HOME;
|
|
640
661
|
return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
|
|
641
662
|
}
|
|
642
|
-
function usagePath(env =
|
|
663
|
+
function usagePath(env = process6.env) {
|
|
643
664
|
return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
644
665
|
}
|
|
645
|
-
function usageRecorded(env =
|
|
666
|
+
function usageRecorded(env = process6.env) {
|
|
646
667
|
const off = env.KAYNOOO_CLI_NO_USAGE;
|
|
647
668
|
return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
|
|
648
669
|
}
|
|
@@ -656,7 +677,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
|
|
|
656
677
|
usageError = undefined;
|
|
657
678
|
return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
|
|
658
679
|
}
|
|
659
|
-
function recordUsage(entry, env =
|
|
680
|
+
function recordUsage(entry, env = process6.env) {
|
|
660
681
|
if (!usageRecorded(env))
|
|
661
682
|
return;
|
|
662
683
|
try {
|
|
@@ -674,8 +695,8 @@ var LEVEL_OPTIONS = {
|
|
|
674
695
|
};
|
|
675
696
|
var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
|
|
676
697
|
function printError(prefix, message, hint, cause) {
|
|
677
|
-
const colors = paint(
|
|
678
|
-
const styled = takesControlCodes(
|
|
698
|
+
const colors = paint(process7.stderr);
|
|
699
|
+
const styled = takesControlCodes(process7.stderr);
|
|
679
700
|
const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
|
|
680
701
|
const under = (label, text, tint) => text === undefined ? "" : `
|
|
681
702
|
${styled ? tint(label) : `${label}:`} ${text}`;
|
|
@@ -757,11 +778,22 @@ async function printCandidates(found) {
|
|
|
757
778
|
console.log(line);
|
|
758
779
|
return 0;
|
|
759
780
|
}
|
|
760
|
-
|
|
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)) {
|
|
761
793
|
if (argv[0] === COMPLETE)
|
|
762
794
|
return printCandidates(leafCandidates(run, argv.slice(1)));
|
|
763
795
|
if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
|
|
764
|
-
console.log(version);
|
|
796
|
+
console.log(version ?? packageVersion());
|
|
765
797
|
return 0;
|
|
766
798
|
}
|
|
767
799
|
let code;
|
|
@@ -770,8 +802,11 @@ async function runMain({ name, version, run, redact, usage }, argv = process6.ar
|
|
|
770
802
|
} catch (error) {
|
|
771
803
|
code = reportThrown(name, error, redact, wantsJson(argv));
|
|
772
804
|
}
|
|
773
|
-
if (usage !== false)
|
|
774
|
-
|
|
805
|
+
if (usage !== false) {
|
|
806
|
+
try {
|
|
807
|
+
recordUsage(usageEntry(name, undefined, argv, code));
|
|
808
|
+
} catch {}
|
|
809
|
+
}
|
|
775
810
|
return code;
|
|
776
811
|
}
|
|
777
812
|
// ../kit/src/secrets.ts
|
|
@@ -780,11 +815,184 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
|
|
|
780
815
|
var {Glob } = globalThis.Bun;
|
|
781
816
|
var SESSION_FILES = new Glob("*.json");
|
|
782
817
|
var ACCOUNT_DIRS = new Glob("*/sessions");
|
|
783
|
-
//
|
|
784
|
-
var
|
|
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
|
+
}
|
|
785
993
|
|
|
786
994
|
// src/diff.ts
|
|
787
|
-
var
|
|
995
|
+
var TRAILING_NEWLINE2 = /\n$/;
|
|
788
996
|
var HUNK = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@(.*)$/;
|
|
789
997
|
var FILE_HEADER = /^diff --git a\/(.*) b\/(.*)$/;
|
|
790
998
|
var COMMIT = /^(commit )([0-9a-f]{7,40})(.*)$/;
|
|
@@ -800,7 +1008,7 @@ function looksLikeDiff(text) {
|
|
|
800
1008
|
function renderDiff(text, theme) {
|
|
801
1009
|
let oldLeft = 0;
|
|
802
1010
|
let newLeft = 0;
|
|
803
|
-
const lines = stripAnsi(text).replaceAll("\r", "").replace(
|
|
1011
|
+
const lines = stripAnsi(text).replaceAll("\r", "").replace(TRAILING_NEWLINE2, "").split(`
|
|
804
1012
|
`).map((line) => {
|
|
805
1013
|
if ((oldLeft > 0 || newLeft > 0) && line !== "" && !HUNK_LINE.has(line[0] ?? ""))
|
|
806
1014
|
oldLeft = newLeft = 0;
|
|
@@ -944,11 +1152,15 @@ function renderMarkdown(source, { theme, width }) {
|
|
|
944
1152
|
html: (children) => block(`${theme.dim(trimmed(children))}
|
|
945
1153
|
|
|
946
1154
|
`),
|
|
947
|
-
code: (children) =>
|
|
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(`
|
|
948
1159
|
`).map((line) => `${bar}${line}`).join(`
|
|
949
1160
|
`)}
|
|
950
1161
|
|
|
951
|
-
`)
|
|
1162
|
+
`);
|
|
1163
|
+
},
|
|
952
1164
|
blockquote: (children) => block(`${indent(trimmed(children.replaceAll(BLOCK, "")), quote, quote)}
|
|
953
1165
|
|
|
954
1166
|
`),
|
|
@@ -997,8 +1209,8 @@ function renderMarkdown(source, { theme, width }) {
|
|
|
997
1209
|
}
|
|
998
1210
|
|
|
999
1211
|
// src/theme.ts
|
|
1000
|
-
import
|
|
1001
|
-
function themeFor(stream =
|
|
1212
|
+
import process9 from "process";
|
|
1213
|
+
function themeFor(stream = process9.stdout, env = process9.env) {
|
|
1002
1214
|
const colors = paint(stream, env);
|
|
1003
1215
|
const accent = role("accent", stream, env);
|
|
1004
1216
|
const path = role("path", stream, env);
|
|
@@ -1014,6 +1226,9 @@ function themeFor(stream = process8.stdout, env = process8.env) {
|
|
|
1014
1226
|
added: colors.green,
|
|
1015
1227
|
removed: colors.red,
|
|
1016
1228
|
accent,
|
|
1229
|
+
keyword: colors.magenta,
|
|
1230
|
+
string: colors.green,
|
|
1231
|
+
number: colors.yellow,
|
|
1017
1232
|
link: (text, url) => path(colors.underline(link(text, url, stream, env)))
|
|
1018
1233
|
};
|
|
1019
1234
|
}
|
|
@@ -1022,15 +1237,17 @@ function themeFor(stream = process8.stdout, env = process8.env) {
|
|
|
1022
1237
|
var DEFAULT_WIDTH = 80;
|
|
1023
1238
|
var MARKDOWN_FILE = /\.(?:md|markdown|mdx)$/i;
|
|
1024
1239
|
var DIFF_FILE = /\.(?:diff|patch)$/i;
|
|
1025
|
-
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
|
|
1026
1241
|
|
|
1027
|
-
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.
|
|
1028
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.
|
|
1029
1244
|
|
|
1030
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.`;
|
|
1031
1246
|
var OPTIONS = {
|
|
1032
1247
|
diff: { type: "boolean", description: "show the text as a diff" },
|
|
1033
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)" },
|
|
1034
1251
|
width: { type: "string", short: "w", description: "columns to wrap to, instead of the terminal's" },
|
|
1035
1252
|
pager: { type: "boolean", description: "page a long output on a terminal (--no-pager turns it off)" }
|
|
1036
1253
|
};
|
|
@@ -1043,7 +1260,7 @@ async function page(text) {
|
|
|
1043
1260
|
} catch {}
|
|
1044
1261
|
await pager.exited;
|
|
1045
1262
|
} catch {
|
|
1046
|
-
|
|
1263
|
+
process10.stdout.write(text);
|
|
1047
1264
|
}
|
|
1048
1265
|
}
|
|
1049
1266
|
async function main(args) {
|
|
@@ -1056,15 +1273,26 @@ async function main(args) {
|
|
|
1056
1273
|
const text = await readInput(path, { noStdin: "give a file, or pipe the text on stdin" });
|
|
1057
1274
|
if (text.trim() === "")
|
|
1058
1275
|
fail("nothing to show", 1);
|
|
1059
|
-
const width = wholeNumber(values.width, "width",
|
|
1060
|
-
const theme = themeFor(
|
|
1061
|
-
const
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
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))
|
|
1065
1293
|
await page(shown);
|
|
1066
1294
|
else
|
|
1067
|
-
|
|
1295
|
+
process10.stdout.write(shown);
|
|
1068
1296
|
return 0;
|
|
1069
1297
|
}
|
|
1070
|
-
|
|
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.
|
|
4
|
+
"version": "0.2.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
|
+
"@kaynooo/cli-kit": "0.21.0"
|
|
39
39
|
}
|
|
40
40
|
}
|