@kaynooo/cli-view 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/view.js +66 -43
  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 process16 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process10 from "process";
8
8
  import { parseArgs } from "util";
@@ -381,18 +381,14 @@ var FULL_STOP = /\.$/;
381
381
  function usageLine(usage, colors = paint(process8.stdout)) {
382
382
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
383
383
  }
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(`
384
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
385
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
386
386
  `);
387
387
  }
388
388
  function exitRows(exits, colors = paint(process8.stdout)) {
389
389
  if (exits.length === 0)
390
390
  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}`];
391
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
396
392
  }
397
393
  function wantsHelpJson(env = process8.env) {
398
394
  return env.KIT_HELP === "json";
@@ -692,21 +688,45 @@ function nearestOption(message, options, allowNegative) {
692
688
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
693
689
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
694
690
  }
691
+ // ../kit/src/argv.ts
692
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
693
+ import { resolve as resolve3 } from "path";
694
+ import process11 from "process";
695
+ function commandLine() {
696
+ try {
697
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
698
+ } catch {
699
+ return;
700
+ }
701
+ }
702
+ function realPath(word) {
703
+ try {
704
+ return realpathSync(resolve3(word));
705
+ } catch {
706
+ return;
707
+ }
708
+ }
709
+ function scriptArgs(argv = process11.argv.slice(2), cmdline = commandLine(), script = process11.argv[1]) {
710
+ const target = script === undefined ? undefined : realPath(script) ?? script;
711
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
712
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
713
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
714
+ }
695
715
  // ../kit/src/progress.ts
696
716
  var ESC = String.fromCharCode(27);
697
717
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
698
718
  var RESET_STYLE = `${ESC}[0m`;
699
719
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
700
720
  // ../kit/src/cli.ts
701
- import { readFileSync as readFileSync2, realpathSync } from "fs";
721
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
702
722
  import { dirname as dirname3, join as join5 } from "path";
703
- import process12 from "process";
723
+ import process13 from "process";
704
724
 
705
725
  // ../kit/src/usage.ts
706
726
  import { appendFileSync, mkdirSync } from "fs";
707
727
  import { homedir as homedir3 } from "os";
708
728
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
709
- import process11 from "process";
729
+ import process12 from "process";
710
730
 
711
731
  // ../kit/src/logs.ts
712
732
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -720,14 +740,14 @@ var usageError;
720
740
  function noteUsageError(message) {
721
741
  usageError = message;
722
742
  }
723
- function stateHome(env = process11.env) {
743
+ function stateHome(env = process12.env) {
724
744
  const dir = env.XDG_STATE_HOME;
725
745
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
726
746
  }
727
- function usagePath(env = process11.env) {
747
+ function usagePath(env = process12.env) {
728
748
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
729
749
  }
730
- function usageRecorded(env = process11.env) {
750
+ function usageRecorded(env = process12.env) {
731
751
  const off = env.KAYNOOO_CLI_NO_USAGE;
732
752
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
733
753
  }
@@ -741,7 +761,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
741
761
  usageError = undefined;
742
762
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
743
763
  }
744
- function recordUsage(entry, env = process11.env) {
764
+ function recordUsage(entry, env = process12.env) {
745
765
  if (!usageRecorded(env))
746
766
  return;
747
767
  try {
@@ -759,8 +779,8 @@ var LEVEL_OPTIONS = {
759
779
  };
760
780
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
761
781
  function printError(prefix, message, hint, cause) {
762
- const colors = paint(process12.stderr);
763
- const styled = takesControlCodes(process12.stderr);
782
+ const colors = paint(process13.stderr);
783
+ const styled = takesControlCodes(process13.stderr);
764
784
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
765
785
  const under = (label, text, tint) => text === undefined ? "" : `
766
786
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -804,24 +824,24 @@ function candidateLine(candidate) {
804
824
  }
805
825
  function positionalBeingTyped(before, { options, positionals }) {
806
826
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
807
- let index = 0;
827
+ const typed = [];
808
828
  let at = 0;
809
829
  while (at < before.length) {
810
830
  const word = before[at];
811
831
  if (word === "--") {
812
- index += before.length - at - 1;
832
+ typed.push(...before.slice(at + 1));
813
833
  break;
814
834
  }
815
835
  if (!word.startsWith("-"))
816
- index++;
836
+ typed.push(word);
817
837
  else if (takesValue(word))
818
838
  at++;
819
839
  at++;
820
840
  }
821
841
  const last = positionals.at(-1);
822
- if (index < positionals.length)
823
- return positionals[index];
824
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
842
+ if (typed.length < positionals.length)
843
+ return { name: positionals[typed.length], typed };
844
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
825
845
  }
826
846
  async function leafCandidates(run, words) {
827
847
  const completing = await completingOf(run);
@@ -829,12 +849,12 @@ async function leafCandidates(run, words) {
829
849
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
830
850
  const flag = words.at(-2);
831
851
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
852
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
832
853
  if (option?.type === "string") {
833
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
854
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
834
855
  return values === undefined ? [FILES] : values.map(candidateLine);
835
856
  }
836
- const name = positionalBeingTyped(words.slice(0, -1), completing);
837
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
857
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
838
858
  return values === undefined ? [FILES] : values.map(candidateLine);
839
859
  }
840
860
  async function printCandidates(found) {
@@ -843,9 +863,13 @@ async function printCandidates(found) {
843
863
  return 0;
844
864
  }
845
865
  function packageVersion(entry = Bun.main) {
846
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
866
+ let resolved = entry;
867
+ try {
868
+ resolved = realpathSync2(entry);
869
+ } catch {}
870
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
847
871
  try {
848
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
872
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
849
873
  if (typeof version === "string")
850
874
  return version;
851
875
  } catch {}
@@ -853,7 +877,7 @@ function packageVersion(entry = Bun.main) {
853
877
  return "0.0.0";
854
878
  }
855
879
  }
856
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
880
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
857
881
  if (argv[0] === COMPLETE)
858
882
  return printCandidates(leafCandidates(run, argv.slice(1)));
859
883
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1315,8 +1339,8 @@ ${theme.dim("\u2500".repeat(rule))}
1315
1339
  }
1316
1340
 
1317
1341
  // src/theme.ts
1318
- import process14 from "process";
1319
- function themeFor(stream = process14.stdout, env = process14.env) {
1342
+ import process15 from "process";
1343
+ function themeFor(stream = process15.stdout, env = process15.env) {
1320
1344
  const colors = paint(stream, env);
1321
1345
  const accent = role("accent", stream, env);
1322
1346
  const path = role("path", stream, env);
@@ -1347,9 +1371,8 @@ var DIFF_FILE = /\.(?:diff|patch)$/i;
1347
1371
  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
1372
 
1349
1373
  A file, or what is piped on stdin (or - for stdin). A source file (ts, js, json, yaml, toml, py, sh, css, sql, rs, go and more) is highlighted behind line numbers, by its extension or --lang. A diff, a \`git log -p\` or a \`git show\` is recognised by its first line or a .diff or .patch name, anything else is markdown; --diff and --markdown force one. Code blocks in markdown are highlighted by their language.
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.`;
1374
+ Lines wrap to the terminal width (80 when it is not a terminal) and a long output on a terminal goes through \`less -FRX\` unless --no-pager. No colour with NO_COLOR, a pipe or --plain.`;
1375
+ var EXITS = [[0, "it showed the text"], [1, "there is nothing to show"], [2, "a usage error or a file that is missing"]];
1353
1376
  var OPTIONS = {
1354
1377
  diff: { type: "boolean", description: "show the text as a diff" },
1355
1378
  markdown: { type: "boolean", description: "show the text as markdown" },
@@ -1368,11 +1391,11 @@ async function page(text) {
1368
1391
  } catch {}
1369
1392
  await pager.exited;
1370
1393
  } catch {
1371
- process15.stdout.write(text);
1394
+ process16.stdout.write(text);
1372
1395
  }
1373
1396
  }
1374
1397
  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"] });
1398
+ 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
1399
  if (positionals.length > 1)
1377
1400
  badUsage("give one file");
1378
1401
  if (values.diff === true && values.markdown === true)
@@ -1381,8 +1404,8 @@ async function main(args) {
1381
1404
  const text = await readInput(path, { noStdin: "give a file, or pipe the text on stdin" });
1382
1405
  if (text.trim() === "")
1383
1406
  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);
1407
+ const width = wholeNumber(values.width, "width", process16.stdout.isTTY === true ? process16.stdout.columns || DEFAULT_WIDTH : DEFAULT_WIDTH, 20);
1408
+ const theme = themeFor(process16.stdout);
1386
1409
  const language = values.lang === undefined ? languageOf(path) : languageOf(values.lang);
1387
1410
  if (values.lang !== undefined && language === undefined)
1388
1411
  badUsage(`unknown language ${values.lang}`);
@@ -1399,12 +1422,12 @@ async function main(args) {
1399
1422
  printJson({ kind: isCode ? "code" : kind, language: isCode ? language ?? null : null, text: stripAnsi(render(themeFor({ isTTY: false }), values.lines ?? false)) });
1400
1423
  return 0;
1401
1424
  }
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))
1425
+ const shown = render(theme, values.lines ?? process16.stdout.isTTY === true);
1426
+ if (process16.stdout.isTTY === true && values.pager !== false && shown.split(`
1427
+ `).length > (process16.stdout.rows || 24))
1405
1428
  await page(shown);
1406
1429
  else
1407
- process15.stdout.write(shown);
1430
+ process16.stdout.write(shown);
1408
1431
  return 0;
1409
1432
  }
1410
- process15.exitCode = await runMain({ name: "view", run: main });
1433
+ process16.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.6.1",
5
5
  "description": "view: markdown files and git diffs shown in the colours of the other @kaynooo CLIs, paged when long.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "view": "$npm_execpath src/view.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.36.0"
38
+ "@kaynooo/cli-kit": "0.38.3"
39
39
  }
40
40
  }