@kaynooo/cli-code 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,7 +36,7 @@ hotspots --since '3 months ago' --limit 10
36
36
 
37
37
  ## hotspots
38
38
 
39
- - `hotspots [dir]` ranks the source files by complexity times churn, so the files both hard to read and often edited come first: rank, score, churn, complexity, lines, file. The files are the ones git keeps (`.gitignore` honoured).
40
- - Churn is the commits touching the file since `--since` (any date git reads, `6 months ago` by default), counted from one `git log`. Complexity is the decision points of the file (`if`, loops, `case`, `catch`, `&&`, `||`, `??`, ternaries, `and`/`or`) plus one, counted with comments and strings blanked; it is computed in-house so the bin needs no dependency and reads any language the same way.
41
- - `--limit <n>` (`-n`) sets how many files are listed (20, the count of the rest after them), `--full` lists all, `--json` is never cut unless `--limit` is given. `--all` keeps test files and generated files (`dist/`, `*.d.ts`, `*.min.js`, snapshots, files whose first lines say generated), `--json` prints `[{rank, path, score, churn, complexity, lines}]`.
39
+ - `hotspots [dir]` ranks the source files by complexity times churn, so the files both hard to read and often edited come first: rank, score, churn, recent, complexity, lines, file and the file's most complex declaration. The files are the ones git keeps (`.gitignore` honoured).
40
+ - Churn is the commits touching the file since `--since` (any date git reads, `6 months ago` by default), counted from one `git log`. The score uses `recent`, the commits weighted by age (half as much every `--half-life`, `90d` by default, `0` to count them alike), and leaves out the commits touching more than `--bulk` files (25), the format and rename sweeps. Complexity is the decision points of the file (`if`, loops, `case`, `catch`, `&&`, `||`, `??`, ternaries, `and`/`or`) plus one, counted with comments and strings blanked; it is computed in-house so the bin needs no dependency and reads any language the same way.
41
+ - `--limit <n>` (`-n`) sets how many files are listed (20, the count of the rest after them), `--full` lists all, `--json` is never cut unless `--limit` is given. `--all` keeps test files and generated files (`dist/`, `*.d.ts`, `*.min.js`, snapshots, files whose first lines say generated), `--json` prints `[{rank, path, score, churn, recent, complexity, worst, lines}]`. The most complex declaration is found from the indentation alone (a class is opened into its methods), so it reads any language the same way.
42
42
  - Exits 1 when no file has commits in the window, 2 on a usage error or outside a git repository.
package/dist/hotspots.js CHANGED
@@ -2,12 +2,11 @@
2
2
  // @bun
3
3
 
4
4
  // src/hotspots.ts
5
- import { join as join2 } from "path";
6
- import process7 from "process";
5
+ import { join as join3 } from "path";
6
+ import process9 from "process";
7
7
 
8
8
  // ../kit/src/args.ts
9
- import { fstatSync } from "fs";
10
- import process3 from "process";
9
+ import process4 from "process";
11
10
  import { parseArgs } from "util";
12
11
 
13
12
  // ../kit/src/format.ts
@@ -360,6 +359,55 @@ function printJson(value) {
360
359
  console.log(JSON.stringify(value, undefined, 2));
361
360
  }
362
361
 
362
+ // ../kit/src/help.ts
363
+ import process3 from "process";
364
+ var OPTIONAL = /\[[^\]]+\]/g;
365
+ var USAGE_PREFIX = /^usage:\s*/i;
366
+ var FULL_STOP = /\.$/;
367
+ function usageLine(usage, colors = paint(process3.stdout)) {
368
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
369
+ }
370
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
371
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
372
+ `);
373
+ }
374
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
375
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
376
+ }
377
+ function wantsHelpJson(env = process3.env) {
378
+ return env.KIT_HELP === "json";
379
+ }
380
+ function description(usage, { examples = [], replaces } = {}) {
381
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
382
+ `);
383
+ const first = lines[0];
384
+ const colon = first.indexOf(": ");
385
+ const prose = lines[lines.indexOf("") + 1] ?? "";
386
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
387
+ return {
388
+ synopsis: colon === -1 ? first : first.slice(0, colon),
389
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
390
+ ...replaces === undefined ? {} : { replaces },
391
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
392
+ };
393
+ }
394
+ function exampleRows(examples, colors = paint(process3.stdout)) {
395
+ if (examples.length === 0)
396
+ return [];
397
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
398
+ }
399
+ function optionRows(options, colors = paint(process3.stdout)) {
400
+ const rows = Object.entries(options).map(([name, option]) => {
401
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
402
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
403
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
404
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
405
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
406
+ });
407
+ const width = Math.max(0, ...rows.map((row) => row.width));
408
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
409
+ }
410
+
363
411
  // ../kit/src/text.ts
364
412
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
365
413
  function distance(a, b) {
@@ -379,8 +427,35 @@ function closest(name, names) {
379
427
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
380
428
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
381
429
  }
430
+ // ../kit/src/input.ts
431
+ import { fstatSync } from "fs";
432
+ var WHOLE = /^\d+$/;
433
+ function wholeNumber(value, name, fallback, min = 1) {
434
+ if (value === undefined)
435
+ return fallback;
436
+ const number = Number(value);
437
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
438
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
439
+ return number;
440
+ }
441
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
442
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
443
+ function duration(value, name, fallback, unit = "s") {
444
+ if (value === undefined)
445
+ return fallback;
446
+ const match = DURATION.exec(value.trim());
447
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
448
+ if (ms < 1)
449
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
450
+ return ms;
451
+ }
452
+ function isStdinPiped() {
453
+ const stat = fstatSync(0);
454
+ return stat.isFIFO() || stat.isFile();
455
+ }
382
456
 
383
457
  // ../kit/src/args.ts
458
+ var DASHES = /^-+/;
384
459
  function jsonOption(holds) {
385
460
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
386
461
  }
@@ -424,58 +499,11 @@ class Completing {
424
499
  }
425
500
  }
426
501
  var completion = { active: false };
427
- var OPTIONAL = /\[[^\]]+\]/g;
428
- var USAGE_PREFIX = /^usage:\s*/i;
429
- var FULL_STOP = /\.$/;
430
- var DASHES = /^-+/;
431
- function usageLine(usage, colors = paint(process3.stdout)) {
432
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
433
- }
434
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
435
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
436
- `);
437
- }
438
- function replacesRows(replaces, colors = paint(process3.stdout)) {
439
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
440
- }
441
- function wantsHelpJson(env = process3.env) {
442
- return env.KIT_HELP === "json";
443
- }
444
- function description(usage, { examples = [], replaces } = {}) {
445
- const lines = usage.replace(USAGE_PREFIX, "").split(`
446
- `);
447
- const first = lines[0];
448
- const colon = first.indexOf(": ");
449
- const prose = lines[lines.indexOf("") + 1] ?? "";
450
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
451
- return {
452
- synopsis: colon === -1 ? first : first.slice(0, colon),
453
- summary: colon === -1 ? fallback : first.slice(colon + 2),
454
- ...replaces === undefined ? {} : { replaces },
455
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
456
- };
457
- }
458
- function exampleRows(examples, colors = paint(process3.stdout)) {
459
- if (examples.length === 0)
460
- return [];
461
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
462
- }
463
- function optionRows(options, colors = paint(process3.stdout)) {
464
- const rows = Object.entries(options).map(([name, option]) => {
465
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
466
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
467
- const placeholder = option.optional === undefined ? named : `[${named}]`;
468
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
469
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
470
- });
471
- const width = Math.max(0, ...rows.map((row) => row.width));
472
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
473
- }
474
502
  var OUTPUT_OPTIONS = {
475
503
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
476
504
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
477
505
  };
478
- function applyOutput(color, plain, env = process3.env) {
506
+ function applyOutput(color, plain, env = process4.env) {
479
507
  const when = plain === true ? "never" : color ?? "auto";
480
508
  if (when === "auto")
481
509
  return;
@@ -632,22 +660,9 @@ function nearestOption(message, options, allowNegative) {
632
660
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
633
661
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
634
662
  }
635
- var WHOLE = /^\d+$/;
636
- function wholeNumber(value, name, fallback, min = 1) {
637
- if (value === undefined)
638
- return fallback;
639
- const number = Number(value);
640
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
641
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
642
- return number;
643
- }
644
- function isStdinPiped() {
645
- const stat = fstatSync(0);
646
- return stat.isFIFO() || stat.isFile();
647
- }
648
663
  // ../kit/src/process.ts
649
664
  import { constants } from "os";
650
- import process4 from "process";
665
+ import process5 from "process";
651
666
  var KILL_GRACE_MS = 2000;
652
667
  function exitCodeOf(code, signal) {
653
668
  if (code !== null)
@@ -667,7 +682,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
667
682
  return;
668
683
  try {
669
684
  if (grouped)
670
- process4.kill(-proc.pid, killing);
685
+ process5.kill(-proc.pid, killing);
671
686
  else
672
687
  proc.kill(killing);
673
688
  } catch {}
@@ -741,15 +756,67 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
741
756
  var RESET_STYLE = `${ESC}[0m`;
742
757
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
743
758
  // ../kit/src/cli.ts
744
- import process5 from "process";
759
+ import process7 from "process";
760
+
761
+ // ../kit/src/usage.ts
762
+ import { appendFileSync, mkdirSync } from "fs";
763
+ import { homedir } from "os";
764
+ import { dirname, isAbsolute, join } from "path";
765
+ import process6 from "process";
766
+
767
+ // ../kit/src/logs.ts
768
+ var DAY_MS = 24 * 60 * 60 * 1000;
769
+ var CLI_FOLDER = "kaynooo-cli";
770
+
771
+ // ../kit/src/usage.ts
772
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
773
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
774
+ var LONGEST_NAME = 40;
775
+ var usageError;
776
+ function noteUsageError(message) {
777
+ usageError = message;
778
+ }
779
+ function stateHome(env = process6.env) {
780
+ const dir = env.XDG_STATE_HOME;
781
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
782
+ }
783
+ function usagePath(env = process6.env) {
784
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
785
+ }
786
+ function usageRecorded(env = process6.env) {
787
+ const off = env.KAYNOOO_CLI_NO_USAGE;
788
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
789
+ }
790
+ function flagNames(argv) {
791
+ const end = argv.indexOf("--");
792
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
793
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
794
+ }
795
+ function usageEntry(bin, command, argv, code, now = new Date) {
796
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
797
+ usageError = undefined;
798
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
799
+ }
800
+ function recordUsage(entry, env = process6.env) {
801
+ if (!usageRecorded(env))
802
+ return;
803
+ try {
804
+ const path = usagePath(env);
805
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
806
+ appendFileSync(path, `${JSON.stringify(entry)}
807
+ `, { mode: 384 });
808
+ } catch {}
809
+ }
810
+
811
+ // ../kit/src/cli.ts
745
812
  var LEVEL_OPTIONS = {
746
813
  ...OUTPUT_OPTIONS,
747
814
  help: { type: "boolean", short: "h", description: "show this help" }
748
815
  };
749
816
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
750
817
  function printError(prefix, message, hint, cause) {
751
- const colors = paint(process5.stderr);
752
- const styled = takesControlCodes(process5.stderr);
818
+ const colors = paint(process7.stderr);
819
+ const styled = takesControlCodes(process7.stderr);
753
820
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
754
821
  const under = (label, text, tint) => text === undefined ? "" : `
755
822
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -768,6 +835,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
768
835
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
769
836
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
770
837
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
838
+ if (error instanceof UsageError)
839
+ noteUsageError(error.message);
771
840
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
772
841
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
773
842
  return error instanceof Exit ? error.code : 1;
@@ -829,18 +898,22 @@ async function printCandidates(found) {
829
898
  console.log(line);
830
899
  return 0;
831
900
  }
832
- async function runMain({ name, version, run, redact }, argv = process5.argv.slice(2)) {
901
+ async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
833
902
  if (argv[0] === COMPLETE)
834
903
  return printCandidates(leafCandidates(run, argv.slice(1)));
835
904
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
836
905
  console.log(version);
837
906
  return 0;
838
907
  }
908
+ let code;
839
909
  try {
840
- return await run(argv);
910
+ code = await run(argv);
841
911
  } catch (error) {
842
- return reportThrown(name, error, redact, wantsJson(argv));
912
+ code = reportThrown(name, error, redact, wantsJson(argv));
843
913
  }
914
+ if (usage !== false)
915
+ recordUsage(usageEntry(name, undefined, argv, code));
916
+ return code;
844
917
  }
845
918
  // ../kit/src/limit.ts
846
919
  function limitOptions(fallback) {
@@ -863,8 +936,6 @@ function capped(rows, limit) {
863
936
  const more = rows.length - limit;
864
937
  return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
865
938
  }
866
- // ../kit/src/logs.ts
867
- var DAY_MS = 24 * 60 * 60 * 1000;
868
939
  // ../kit/src/secrets.ts
869
940
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
870
941
  // ../kit/src/sessions.ts
@@ -872,12 +943,13 @@ var {Glob } = globalThis.Bun;
872
943
  var SESSION_FILES = new Glob("*.json");
873
944
  var ACCOUNT_DIRS = new Glob("*/sessions");
874
945
  // package.json
875
- var version = "0.6.0";
946
+ var version = "0.7.0";
876
947
 
877
948
  // src/churn.ts
878
949
  var SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|py|go|rs|rb|php|java|kt|swift|cs|c|cc|cpp|h|hpp|scala|dart|lua|sh|zsh|fish)$/;
879
950
  var TESTS = /(?:^|\/)(?:tests?|__tests__|spec|e2e|__mocks__|fixtures)\/|\.(?:test|spec|bench)\.[^/]+$|(?:^|\/)test_[^/]+$|_test\.(?:go|py)$/;
880
951
  var GENERATED = /(?:^|\/)(?:dist|build|out|generated|\.nuxt|\.output|\.next)\/|\.min\.[cm]?js$|\.d\.ts$|\.(?:generated|gen)\.[^/]+$|\.pb\.go$|\.snap$/;
952
+ var LEADING_NEWLINE = /^\n/;
881
953
  var GENERATED_HEADER = /@generated|generated by|do not edit/i;
882
954
  var DECISION = /\b(?:if|elif|elsif|for|foreach|while|until|case|when|catch|except|rescue|match|guard|and|or)\b|&&|\|\||\?\?|\?(?=[^.?:])/g;
883
955
  var COMMENT = /\/\*[\s\S]*?\*\/|\/\/[^\n]*|^[ \t]*#[^\n]*/gm;
@@ -891,21 +963,29 @@ function isGenerated(text) {
891
963
  function complexityOf(text) {
892
964
  return 1 + (text.replace(COMMENT, "").replace(STRING, '""').match(DECISION)?.length ?? 0);
893
965
  }
894
- async function churnSince(cwd, since) {
895
- const log = await runCommand(["git", "log", `--since=${since}`, "--no-renames", "--relative", "--name-only", "--format=", "-z"], { cwd });
966
+ async function churnSince(cwd, since, { bulk, halfLifeMs, now = Date.now() }) {
967
+ const log = await runCommand(["git", "log", `--since=${since}`, "--no-renames", "--relative", "--name-only", "--format=%x01%ct", "-z"], { cwd });
896
968
  if (log.code !== 0)
897
969
  return;
898
970
  const churn = new Map;
899
- for (const path of log.text.split("\x00")) {
900
- if (path !== "")
901
- churn.set(path, (churn.get(path) ?? 0) + 1);
971
+ for (const commit of log.text.split("\x01").slice(1)) {
972
+ const [stamp = "", ...names] = commit.split("\x00");
973
+ const paths = names.map((name) => name.replace(LEADING_NEWLINE, "")).filter((name) => name !== "");
974
+ if (paths.length > bulk)
975
+ continue;
976
+ const age = Math.max(0, now - Number(stamp) * 1000);
977
+ const weight = halfLifeMs === 0 ? 1 : 0.5 ** (age / halfLifeMs);
978
+ for (const path of paths) {
979
+ const seen = churn.get(path) ?? { commits: 0, weight: 0 };
980
+ churn.set(path, { commits: seen.commits + 1, weight: seen.weight + weight });
981
+ }
902
982
  }
903
983
  return churn;
904
984
  }
905
985
 
906
986
  // src/files.ts
907
987
  import { existsSync, readdirSync, statSync } from "fs";
908
- import { join, relative } from "path";
988
+ import { join as join2, relative } from "path";
909
989
  var MAX_BYTES = 2000000;
910
990
  var SNIFF_BYTES = 8000;
911
991
  var SKIPPED = new Set(["node_modules", "dist", "build", "vendor", "target", "coverage"]);
@@ -920,17 +1000,17 @@ function walk(dir, found) {
920
1000
  if (entry.name.startsWith(".") || SKIPPED.has(entry.name))
921
1001
  continue;
922
1002
  if (entry.isDirectory())
923
- walk(join(dir, entry.name), found);
1003
+ walk(join2(dir, entry.name), found);
924
1004
  else if (entry.isFile())
925
- found.push(join(dir, entry.name));
1005
+ found.push(join2(dir, entry.name));
926
1006
  }
927
1007
  return found;
928
1008
  }
929
1009
  async function listFiles(paths, cwd) {
930
1010
  const listed = await runCommand(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], { cwd });
931
1011
  if (listed.code === 0)
932
- return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join(cwd, path))).sort();
933
- const roots = paths.length === 0 ? [cwd] : paths.map((path) => join(cwd, path));
1012
+ return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join2(cwd, path))).sort();
1013
+ const roots = paths.length === 0 ? [cwd] : paths.map((path) => join2(cwd, path));
934
1014
  return roots.flatMap((root) => statSync(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [])).map((path) => relative(cwd, path)).sort();
935
1015
  }
936
1016
  async function readText(path) {
@@ -944,29 +1024,77 @@ async function readText(path) {
944
1024
  }
945
1025
  }
946
1026
 
1027
+ // src/units.ts
1028
+ var CONTAINER = /\b(?:class|impl|trait|interface|namespace|module|object|mod|struct|enum)\b/;
1029
+ var CLOSER = /^[\s)\]};]*$|^\s*(?:\/\/|\/\*|\*|#)/;
1030
+ var LONGEST_NAME2 = 60;
1031
+ function indentOf(line) {
1032
+ return line.length - line.trimStart().length;
1033
+ }
1034
+ function opens(line, indent) {
1035
+ return line.trim() !== "" && indentOf(line) === indent && !CLOSER.test(line);
1036
+ }
1037
+ function unitsAt(lines, from, to, indent) {
1038
+ const starts = [];
1039
+ for (let at = from;at < to; at++) {
1040
+ if (opens(lines[at], indent))
1041
+ starts.push(at);
1042
+ }
1043
+ return starts.flatMap((start, index) => {
1044
+ const end = starts[index + 1] ?? to;
1045
+ const header = lines[start].trim();
1046
+ if (CONTAINER.test(header)) {
1047
+ const inner = lines.slice(start + 1, end).filter((line) => line.trim() !== "").map(indentOf).filter((each) => each > indent);
1048
+ const next = inner.length === 0 ? undefined : Math.min(...inner);
1049
+ if (next !== undefined) {
1050
+ const members = unitsAt(lines, start + 1, end, next);
1051
+ if (members.length > 0)
1052
+ return members;
1053
+ }
1054
+ }
1055
+ return [{ name: header.length > LONGEST_NAME2 ? `${header.slice(0, LONGEST_NAME2 - 1)}\u2026` : header, line: start + 1, complexity: complexityOf(lines.slice(start, end).join(`
1056
+ `)) }];
1057
+ });
1058
+ }
1059
+ function worstUnit(text) {
1060
+ const lines = text.split(`
1061
+ `);
1062
+ const top = unitsAt(lines, 0, lines.length, 0);
1063
+ return top.reduce((worst, unit) => worst === undefined || unit.complexity > worst.complexity ? unit : worst, undefined);
1064
+ }
1065
+
947
1066
  // src/hotspots.ts
948
1067
  var DEFAULT_SINCE = "6 months ago";
1068
+ var DEFAULT_BULK = 25;
1069
+ var DAY_MS2 = 86400000;
1070
+ var DEFAULT_HALF_LIFE = "90d";
949
1071
  var DEFAULT_COUNT = 20;
950
1072
  var USAGE = `hotspots [options] [dir]: ranks the source files under dir (here by default) by complexity times churn, the ones both hard to read and often edited first, honouring .gitignore
951
1073
 
952
- Complexity is the count of decision points in the file (branches, loops, cases, catches, boolean operators, ternaries) plus one, churn the commits touching it since --since (${DEFAULT_SINCE}), score their product. Test files and generated or built files are left out unless --all.
1074
+ Complexity is the count of decision points in the file (branches, loops, cases, catches, boolean operators, ternaries) plus one, churn the commits touching it since --since (${DEFAULT_SINCE}), score their product. A commit counts for less the older it is (half as much every --half-life, 0 for all alike) and a commit touching more than --bulk files, a format or rename sweep, is left out. Each file also shows its most complex declaration, found by indentation. Test files and generated or built files are left out unless --all.
953
1075
 
954
1076
  Lists at most ${DEFAULT_COUNT} files, the count of the rest after them (--limit <n>, --full for all); --json is never cut unless --limit is given.
955
1077
 
956
1078
  Exits 0 when it ranked the files, 1 when no file has commits in the window, 2 on a usage error or outside a git repository.`;
957
1079
  var OPTIONS = {
958
1080
  since: { type: "string", short: "s", description: `only count the commits since this date, as git reads it (${DEFAULT_SINCE})` },
1081
+ "half-life": { type: "string", description: `how long until a commit counts half as much (${DEFAULT_HALF_LIFE}), 0 for no decay` },
1082
+ bulk: { type: "string", description: `leave out the commits touching more files than this (${DEFAULT_BULK})` },
959
1083
  ...limitOptions(DEFAULT_COUNT),
960
1084
  all: { type: "boolean", short: "a", description: "keep test files and generated files" },
961
- json: jsonOption("[{rank, path, score, churn, complexity, lines}], never cut unless --limit is given")
1085
+ json: jsonOption("[{rank, path, score, churn, recent, complexity, worst, lines}], never cut unless --limit is given")
962
1086
  };
963
1087
  async function main(args) {
964
1088
  const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[dir]"], replaces: "guessing which files are worth splitting first", examples: ["hotspots", 'hotspots src --since "3 months ago" --limit 10'] });
965
1089
  if (positionals.length > 1)
966
1090
  badUsage("give one folder");
967
1091
  const count = limitOf(values, DEFAULT_COUNT);
968
- const cwd = process7.cwd();
969
- const churn = await churnSince(cwd, values.since ?? DEFAULT_SINCE);
1092
+ const cwd = process9.cwd();
1093
+ const bulk = Number(values.bulk ?? DEFAULT_BULK);
1094
+ if (!Number.isInteger(bulk) || bulk < 1)
1095
+ badUsage(`--bulk takes a number of files, not ${values.bulk}`);
1096
+ const halfLifeMs = values["half-life"] === "0" ? 0 : duration(values["half-life"], "half-life", 90 * DAY_MS2);
1097
+ const churn = await churnSince(cwd, values.since ?? DEFAULT_SINCE, { bulk, halfLifeMs });
970
1098
  if (churn === undefined)
971
1099
  fail("not a git repository, churn comes from its log");
972
1100
  const ranked = [];
@@ -974,11 +1102,12 @@ async function main(args) {
974
1102
  const touched = churn.get(path);
975
1103
  if (touched === undefined || values.all !== true && !isCandidate(path))
976
1104
  continue;
977
- const text = await readText(join2(cwd, path));
1105
+ const text = await readText(join3(cwd, path));
978
1106
  if (text === undefined || values.all !== true && isGenerated(text))
979
1107
  continue;
980
1108
  const complexity = complexityOf(text);
981
- ranked.push({ path, score: complexity * touched, churn: touched, complexity, lines: text.split(`
1109
+ const worst = worstUnit(text);
1110
+ ranked.push({ path, score: Math.round(complexity * touched.weight), churn: touched.commits, recent: Math.round(touched.weight * 10) / 10, complexity, worst: worst === undefined ? undefined : { name: worst.name, line: worst.line, complexity: worst.complexity }, lines: text.split(`
982
1111
  `).length - (text.endsWith(`
983
1112
  `) ? 1 : 0) });
984
1113
  }
@@ -991,9 +1120,9 @@ async function main(args) {
991
1120
  printJson(shown);
992
1121
  return 0;
993
1122
  }
994
- console.log(table([["rank", "score", "churn", "complexity", "lines", "file"], ...shown.map((row) => [row.rank, row.score, row.churn, row.complexity, row.lines, row.path].map(String))], { header: true, align: ["right", "right", "right", "right", "right", "left"] }));
1123
+ console.log(table([["rank", "score", "churn", "recent", "complexity", "lines", "file", "most complex declaration"], ...shown.map((row) => [row.rank, row.score, row.churn, row.recent, row.complexity, row.lines, row.path, row.worst === undefined ? "" : `${row.worst.name} (${row.worst.complexity}, line ${row.worst.line})`].map(String))], { header: true, align: ["right", "right", "right", "right", "right", "right", "left", "left"] }));
995
1124
  if (footer !== undefined)
996
1125
  console.log(footer);
997
1126
  return 0;
998
1127
  }
999
- process7.exitCode = await runMain({ name: "hotspots", version, run: main });
1128
+ process9.exitCode = await runMain({ name: "hotspots", version, run: main });
package/dist/peek.js CHANGED
@@ -3,12 +3,11 @@
3
3
 
4
4
  // src/peek.ts
5
5
  import { realpathSync } from "fs";
6
- import { isAbsolute, join as join2, relative as relative2, resolve, sep } from "path";
7
- import process7 from "process";
6
+ import { isAbsolute as isAbsolute2, join as join3, relative as relative2, resolve, sep } from "path";
7
+ import process9 from "process";
8
8
 
9
9
  // ../kit/src/args.ts
10
- import { fstatSync } from "fs";
11
- import process3 from "process";
10
+ import process4 from "process";
12
11
  import { parseArgs } from "util";
13
12
 
14
13
  // ../kit/src/format.ts
@@ -361,6 +360,55 @@ function printJson(value) {
361
360
  console.log(JSON.stringify(value, undefined, 2));
362
361
  }
363
362
 
363
+ // ../kit/src/help.ts
364
+ import process3 from "process";
365
+ var OPTIONAL = /\[[^\]]+\]/g;
366
+ var USAGE_PREFIX = /^usage:\s*/i;
367
+ var FULL_STOP = /\.$/;
368
+ function usageLine(usage, colors = paint(process3.stdout)) {
369
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
370
+ }
371
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
372
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
373
+ `);
374
+ }
375
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
376
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
377
+ }
378
+ function wantsHelpJson(env = process3.env) {
379
+ return env.KIT_HELP === "json";
380
+ }
381
+ function description(usage, { examples = [], replaces } = {}) {
382
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
383
+ `);
384
+ const first = lines[0];
385
+ const colon = first.indexOf(": ");
386
+ const prose = lines[lines.indexOf("") + 1] ?? "";
387
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
388
+ return {
389
+ synopsis: colon === -1 ? first : first.slice(0, colon),
390
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
391
+ ...replaces === undefined ? {} : { replaces },
392
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
393
+ };
394
+ }
395
+ function exampleRows(examples, colors = paint(process3.stdout)) {
396
+ if (examples.length === 0)
397
+ return [];
398
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
399
+ }
400
+ function optionRows(options, colors = paint(process3.stdout)) {
401
+ const rows = Object.entries(options).map(([name, option]) => {
402
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
403
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
404
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
405
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
406
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
407
+ });
408
+ const width = Math.max(0, ...rows.map((row) => row.width));
409
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
410
+ }
411
+
364
412
  // ../kit/src/text.ts
365
413
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
366
414
  function distance(a, b) {
@@ -380,8 +428,35 @@ function closest(name, names) {
380
428
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
381
429
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
382
430
  }
431
+ // ../kit/src/input.ts
432
+ import { fstatSync } from "fs";
433
+ var WHOLE = /^\d+$/;
434
+ function wholeNumber(value, name, fallback, min = 1) {
435
+ if (value === undefined)
436
+ return fallback;
437
+ const number = Number(value);
438
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
439
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
440
+ return number;
441
+ }
442
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
443
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
444
+ function duration(value, name, fallback, unit = "s") {
445
+ if (value === undefined)
446
+ return fallback;
447
+ const match = DURATION.exec(value.trim());
448
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
449
+ if (ms < 1)
450
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
451
+ return ms;
452
+ }
453
+ function isStdinPiped() {
454
+ const stat = fstatSync(0);
455
+ return stat.isFIFO() || stat.isFile();
456
+ }
383
457
 
384
458
  // ../kit/src/args.ts
459
+ var DASHES = /^-+/;
385
460
  function jsonOption(holds) {
386
461
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
387
462
  }
@@ -425,58 +500,11 @@ class Completing {
425
500
  }
426
501
  }
427
502
  var completion = { active: false };
428
- var OPTIONAL = /\[[^\]]+\]/g;
429
- var USAGE_PREFIX = /^usage:\s*/i;
430
- var FULL_STOP = /\.$/;
431
- var DASHES = /^-+/;
432
- function usageLine(usage, colors = paint(process3.stdout)) {
433
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
434
- }
435
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
436
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
437
- `);
438
- }
439
- function replacesRows(replaces, colors = paint(process3.stdout)) {
440
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
441
- }
442
- function wantsHelpJson(env = process3.env) {
443
- return env.KIT_HELP === "json";
444
- }
445
- function description(usage, { examples = [], replaces } = {}) {
446
- const lines = usage.replace(USAGE_PREFIX, "").split(`
447
- `);
448
- const first = lines[0];
449
- const colon = first.indexOf(": ");
450
- const prose = lines[lines.indexOf("") + 1] ?? "";
451
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
452
- return {
453
- synopsis: colon === -1 ? first : first.slice(0, colon),
454
- summary: colon === -1 ? fallback : first.slice(colon + 2),
455
- ...replaces === undefined ? {} : { replaces },
456
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
457
- };
458
- }
459
- function exampleRows(examples, colors = paint(process3.stdout)) {
460
- if (examples.length === 0)
461
- return [];
462
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
463
- }
464
- function optionRows(options, colors = paint(process3.stdout)) {
465
- const rows = Object.entries(options).map(([name, option]) => {
466
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
467
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
468
- const placeholder = option.optional === undefined ? named : `[${named}]`;
469
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
470
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
471
- });
472
- const width = Math.max(0, ...rows.map((row) => row.width));
473
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
474
- }
475
503
  var OUTPUT_OPTIONS = {
476
504
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
477
505
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
478
506
  };
479
- function applyOutput(color, plain, env = process3.env) {
507
+ function applyOutput(color, plain, env = process4.env) {
480
508
  const when = plain === true ? "never" : color ?? "auto";
481
509
  if (when === "auto")
482
510
  return;
@@ -633,22 +661,9 @@ function nearestOption(message, options, allowNegative) {
633
661
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
634
662
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
635
663
  }
636
- var WHOLE = /^\d+$/;
637
- function wholeNumber(value, name, fallback, min = 1) {
638
- if (value === undefined)
639
- return fallback;
640
- const number = Number(value);
641
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
642
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
643
- return number;
644
- }
645
- function isStdinPiped() {
646
- const stat = fstatSync(0);
647
- return stat.isFIFO() || stat.isFile();
648
- }
649
664
  // ../kit/src/process.ts
650
665
  import { constants } from "os";
651
- import process4 from "process";
666
+ import process5 from "process";
652
667
  var KILL_GRACE_MS = 2000;
653
668
  function exitCodeOf(code, signal) {
654
669
  if (code !== null)
@@ -668,7 +683,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
668
683
  return;
669
684
  try {
670
685
  if (grouped)
671
- process4.kill(-proc.pid, killing);
686
+ process5.kill(-proc.pid, killing);
672
687
  else
673
688
  proc.kill(killing);
674
689
  } catch {}
@@ -742,15 +757,67 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
742
757
  var RESET_STYLE = `${ESC}[0m`;
743
758
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
744
759
  // ../kit/src/cli.ts
745
- import process5 from "process";
760
+ import process7 from "process";
761
+
762
+ // ../kit/src/usage.ts
763
+ import { appendFileSync, mkdirSync } from "fs";
764
+ import { homedir } from "os";
765
+ import { dirname, isAbsolute, join } from "path";
766
+ import process6 from "process";
767
+
768
+ // ../kit/src/logs.ts
769
+ var DAY_MS = 24 * 60 * 60 * 1000;
770
+ var CLI_FOLDER = "kaynooo-cli";
771
+
772
+ // ../kit/src/usage.ts
773
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
774
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
775
+ var LONGEST_NAME = 40;
776
+ var usageError;
777
+ function noteUsageError(message) {
778
+ usageError = message;
779
+ }
780
+ function stateHome(env = process6.env) {
781
+ const dir = env.XDG_STATE_HOME;
782
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
783
+ }
784
+ function usagePath(env = process6.env) {
785
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
786
+ }
787
+ function usageRecorded(env = process6.env) {
788
+ const off = env.KAYNOOO_CLI_NO_USAGE;
789
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
790
+ }
791
+ function flagNames(argv) {
792
+ const end = argv.indexOf("--");
793
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
794
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
795
+ }
796
+ function usageEntry(bin, command, argv, code, now = new Date) {
797
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
798
+ usageError = undefined;
799
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
800
+ }
801
+ function recordUsage(entry, env = process6.env) {
802
+ if (!usageRecorded(env))
803
+ return;
804
+ try {
805
+ const path = usagePath(env);
806
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
807
+ appendFileSync(path, `${JSON.stringify(entry)}
808
+ `, { mode: 384 });
809
+ } catch {}
810
+ }
811
+
812
+ // ../kit/src/cli.ts
746
813
  var LEVEL_OPTIONS = {
747
814
  ...OUTPUT_OPTIONS,
748
815
  help: { type: "boolean", short: "h", description: "show this help" }
749
816
  };
750
817
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
751
818
  function printError(prefix, message, hint, cause) {
752
- const colors = paint(process5.stderr);
753
- const styled = takesControlCodes(process5.stderr);
819
+ const colors = paint(process7.stderr);
820
+ const styled = takesControlCodes(process7.stderr);
754
821
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
755
822
  const under = (label, text, tint) => text === undefined ? "" : `
756
823
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -769,6 +836,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
769
836
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
770
837
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
771
838
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
839
+ if (error instanceof UsageError)
840
+ noteUsageError(error.message);
772
841
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
773
842
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
774
843
  return error instanceof Exit ? error.code : 1;
@@ -830,18 +899,22 @@ async function printCandidates(found) {
830
899
  console.log(line);
831
900
  return 0;
832
901
  }
833
- async function runMain({ name, version, run, redact }, argv = process5.argv.slice(2)) {
902
+ async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
834
903
  if (argv[0] === COMPLETE)
835
904
  return printCandidates(leafCandidates(run, argv.slice(1)));
836
905
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
837
906
  console.log(version);
838
907
  return 0;
839
908
  }
909
+ let code;
840
910
  try {
841
- return await run(argv);
911
+ code = await run(argv);
842
912
  } catch (error) {
843
- return reportThrown(name, error, redact, wantsJson(argv));
913
+ code = reportThrown(name, error, redact, wantsJson(argv));
844
914
  }
915
+ if (usage !== false)
916
+ recordUsage(usageEntry(name, undefined, argv, code));
917
+ return code;
845
918
  }
846
919
  // ../kit/src/limit.ts
847
920
  function limitOptions(fallback) {
@@ -864,8 +937,6 @@ function capped(rows, limit) {
864
937
  const more = rows.length - limit;
865
938
  return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
866
939
  }
867
- // ../kit/src/logs.ts
868
- var DAY_MS = 24 * 60 * 60 * 1000;
869
940
  // ../kit/src/secrets.ts
870
941
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
871
942
  // ../kit/src/sessions.ts
@@ -873,11 +944,11 @@ var {Glob } = globalThis.Bun;
873
944
  var SESSION_FILES = new Glob("*.json");
874
945
  var ACCOUNT_DIRS = new Glob("*/sessions");
875
946
  // package.json
876
- var version = "0.6.0";
947
+ var version = "0.7.0";
877
948
 
878
949
  // src/files.ts
879
950
  import { existsSync, readdirSync, statSync } from "fs";
880
- import { join, relative } from "path";
951
+ import { join as join2, relative } from "path";
881
952
  var MAX_BYTES = 2000000;
882
953
  var SNIFF_BYTES = 8000;
883
954
  var SKIPPED = new Set(["node_modules", "dist", "build", "vendor", "target", "coverage"]);
@@ -892,17 +963,17 @@ function walk(dir, found) {
892
963
  if (entry.name.startsWith(".") || SKIPPED.has(entry.name))
893
964
  continue;
894
965
  if (entry.isDirectory())
895
- walk(join(dir, entry.name), found);
966
+ walk(join2(dir, entry.name), found);
896
967
  else if (entry.isFile())
897
- found.push(join(dir, entry.name));
968
+ found.push(join2(dir, entry.name));
898
969
  }
899
970
  return found;
900
971
  }
901
972
  async function listFiles(paths, cwd) {
902
973
  const listed = await runCommand(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], { cwd });
903
974
  if (listed.code === 0)
904
- return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join(cwd, path))).sort();
905
- const roots = paths.length === 0 ? [cwd] : paths.map((path) => join(cwd, path));
975
+ return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join2(cwd, path))).sort();
976
+ const roots = paths.length === 0 ? [cwd] : paths.map((path) => join2(cwd, path));
906
977
  return roots.flatMap((root) => statSync(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [])).map((path) => relative(cwd, path)).sort();
907
978
  }
908
979
  async function readText(path) {
@@ -1120,18 +1191,18 @@ function cut(text) {
1120
1191
  return text.length > LONGEST_LINE ? `${text.slice(0, LONGEST_LINE - 1)}\u2026` : text;
1121
1192
  }
1122
1193
  async function readableRoot() {
1123
- const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process7.cwd() });
1124
- return realpathSync(ran.code === 0 ? ran.text.trim() : process7.cwd());
1194
+ const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process9.cwd() });
1195
+ return realpathSync(ran.code === 0 ? ran.text.trim() : process9.cwd());
1125
1196
  }
1126
1197
  async function isOutside(path) {
1127
1198
  let real;
1128
1199
  try {
1129
- real = realpathSync(resolve(process7.cwd(), path));
1200
+ real = realpathSync(resolve(process9.cwd(), path));
1130
1201
  } catch {
1131
1202
  return false;
1132
1203
  }
1133
1204
  const inRoot = relative2(await readableRoot(), real);
1134
- return inRoot === ".." || inRoot.startsWith(PARENT) || isAbsolute(inRoot);
1205
+ return inRoot === ".." || inRoot.startsWith(PARENT) || isAbsolute2(inRoot);
1135
1206
  }
1136
1207
  async function checkInside(path) {
1137
1208
  if (await isOutside(path))
@@ -1140,7 +1211,7 @@ async function checkInside(path) {
1140
1211
  async function pipedSpans(text, context) {
1141
1212
  const spans = [];
1142
1213
  for (const [path, numbers] of locations(text)) {
1143
- const source = await isOutside(path) ? undefined : await readText(resolve(process7.cwd(), path));
1214
+ const source = await isOutside(path) ? undefined : await readText(resolve(process9.cwd(), path));
1144
1215
  if (source !== undefined)
1145
1216
  spans.push(...spansAround(path, source.replace(TRAILING_NEWLINE2, "").split(`
1146
1217
  `).length, numbers, context));
@@ -1149,7 +1220,7 @@ async function pipedSpans(text, context) {
1149
1220
  }
1150
1221
  async function textOf(path) {
1151
1222
  await checkInside(path);
1152
- const text = await readText(resolve(process7.cwd(), path));
1223
+ const text = await readText(resolve(process9.cwd(), path));
1153
1224
  if (text === undefined)
1154
1225
  fail(`cannot read ${path} (missing, binary or too large)`, 1);
1155
1226
  return text;
@@ -1198,8 +1269,8 @@ async function spanOf(target) {
1198
1269
  async function* sources(paths) {
1199
1270
  for (const path of paths)
1200
1271
  await checkInside(path);
1201
- for (const path of await listFiles(paths, process7.cwd())) {
1202
- const text = await readText(join2(process7.cwd(), path));
1272
+ for (const path of await listFiles(paths, process9.cwd())) {
1273
+ const text = await readText(join3(process9.cwd(), path));
1203
1274
  if (text !== undefined)
1204
1275
  yield { path, text };
1205
1276
  }
@@ -1283,4 +1354,4 @@ async function main(args) {
1283
1354
  await printSpans(await Promise.all(positionals.map(spanOf)), json);
1284
1355
  return 0;
1285
1356
  }
1286
- process7.exitCode = await runMain({ name: "peek", version, run: main });
1357
+ process9.exitCode = await runMain({ name: "peek", version, run: main });
package/dist/todo-scan.js CHANGED
@@ -2,12 +2,11 @@
2
2
  // @bun
3
3
 
4
4
  // src/todo-scan.ts
5
- import { join as join2 } from "path";
6
- import process7 from "process";
5
+ import { join as join3 } from "path";
6
+ import process9 from "process";
7
7
 
8
8
  // ../kit/src/args.ts
9
- import { fstatSync } from "fs";
10
- import process3 from "process";
9
+ import process4 from "process";
11
10
  import { parseArgs } from "util";
12
11
 
13
12
  // ../kit/src/format.ts
@@ -360,6 +359,55 @@ function printJson(value) {
360
359
  console.log(JSON.stringify(value, undefined, 2));
361
360
  }
362
361
 
362
+ // ../kit/src/help.ts
363
+ import process3 from "process";
364
+ var OPTIONAL = /\[[^\]]+\]/g;
365
+ var USAGE_PREFIX = /^usage:\s*/i;
366
+ var FULL_STOP = /\.$/;
367
+ function usageLine(usage, colors = paint(process3.stdout)) {
368
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
369
+ }
370
+ function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
371
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
372
+ `);
373
+ }
374
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
375
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
376
+ }
377
+ function wantsHelpJson(env = process3.env) {
378
+ return env.KIT_HELP === "json";
379
+ }
380
+ function description(usage, { examples = [], replaces } = {}) {
381
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
382
+ `);
383
+ const first = lines[0];
384
+ const colon = first.indexOf(": ");
385
+ const prose = lines[lines.indexOf("") + 1] ?? "";
386
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
387
+ return {
388
+ synopsis: colon === -1 ? first : first.slice(0, colon),
389
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
390
+ ...replaces === undefined ? {} : { replaces },
391
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
392
+ };
393
+ }
394
+ function exampleRows(examples, colors = paint(process3.stdout)) {
395
+ if (examples.length === 0)
396
+ return [];
397
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
398
+ }
399
+ function optionRows(options, colors = paint(process3.stdout)) {
400
+ const rows = Object.entries(options).map(([name, option]) => {
401
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
402
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
403
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
404
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
405
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
406
+ });
407
+ const width = Math.max(0, ...rows.map((row) => row.width));
408
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
409
+ }
410
+
363
411
  // ../kit/src/text.ts
364
412
  var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
365
413
  function distance(a, b) {
@@ -379,8 +427,35 @@ function closest(name, names) {
379
427
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
380
428
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
381
429
  }
430
+ // ../kit/src/input.ts
431
+ import { fstatSync } from "fs";
432
+ var WHOLE = /^\d+$/;
433
+ function wholeNumber(value, name, fallback, min = 1) {
434
+ if (value === undefined)
435
+ return fallback;
436
+ const number = Number(value);
437
+ if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
438
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
439
+ return number;
440
+ }
441
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
442
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
443
+ function duration(value, name, fallback, unit = "s") {
444
+ if (value === undefined)
445
+ return fallback;
446
+ const match = DURATION.exec(value.trim());
447
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
448
+ if (ms < 1)
449
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
450
+ return ms;
451
+ }
452
+ function isStdinPiped() {
453
+ const stat = fstatSync(0);
454
+ return stat.isFIFO() || stat.isFile();
455
+ }
382
456
 
383
457
  // ../kit/src/args.ts
458
+ var DASHES = /^-+/;
384
459
  function jsonOption(holds) {
385
460
  return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
386
461
  }
@@ -424,58 +499,11 @@ class Completing {
424
499
  }
425
500
  }
426
501
  var completion = { active: false };
427
- var OPTIONAL = /\[[^\]]+\]/g;
428
- var USAGE_PREFIX = /^usage:\s*/i;
429
- var FULL_STOP = /\.$/;
430
- var DASHES = /^-+/;
431
- function usageLine(usage, colors = paint(process3.stdout)) {
432
- return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
433
- }
434
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
435
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
436
- `);
437
- }
438
- function replacesRows(replaces, colors = paint(process3.stdout)) {
439
- return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
440
- }
441
- function wantsHelpJson(env = process3.env) {
442
- return env.KIT_HELP === "json";
443
- }
444
- function description(usage, { examples = [], replaces } = {}) {
445
- const lines = usage.replace(USAGE_PREFIX, "").split(`
446
- `);
447
- const first = lines[0];
448
- const colon = first.indexOf(": ");
449
- const prose = lines[lines.indexOf("") + 1] ?? "";
450
- const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
451
- return {
452
- synopsis: colon === -1 ? first : first.slice(0, colon),
453
- summary: colon === -1 ? fallback : first.slice(colon + 2),
454
- ...replaces === undefined ? {} : { replaces },
455
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
456
- };
457
- }
458
- function exampleRows(examples, colors = paint(process3.stdout)) {
459
- if (examples.length === 0)
460
- return [];
461
- return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
462
- }
463
- function optionRows(options, colors = paint(process3.stdout)) {
464
- const rows = Object.entries(options).map(([name, option]) => {
465
- const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
466
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
467
- const placeholder = option.optional === undefined ? named : `[${named}]`;
468
- const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
469
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
470
- });
471
- const width = Math.max(0, ...rows.map((row) => row.width));
472
- return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
473
- }
474
502
  var OUTPUT_OPTIONS = {
475
503
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
476
504
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
477
505
  };
478
- function applyOutput(color, plain, env = process3.env) {
506
+ function applyOutput(color, plain, env = process4.env) {
479
507
  const when = plain === true ? "never" : color ?? "auto";
480
508
  if (when === "auto")
481
509
  return;
@@ -632,22 +660,9 @@ function nearestOption(message, options, allowNegative) {
632
660
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
633
661
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
634
662
  }
635
- var WHOLE = /^\d+$/;
636
- function wholeNumber(value, name, fallback, min = 1) {
637
- if (value === undefined)
638
- return fallback;
639
- const number = Number(value);
640
- if (!WHOLE.test(value) || !Number.isSafeInteger(number) || number < min)
641
- badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
642
- return number;
643
- }
644
- function isStdinPiped() {
645
- const stat = fstatSync(0);
646
- return stat.isFIFO() || stat.isFile();
647
- }
648
663
  // ../kit/src/process.ts
649
664
  import { constants } from "os";
650
- import process4 from "process";
665
+ import process5 from "process";
651
666
  var KILL_GRACE_MS = 2000;
652
667
  function exitCodeOf(code, signal) {
653
668
  if (code !== null)
@@ -667,7 +682,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
667
682
  return;
668
683
  try {
669
684
  if (grouped)
670
- process4.kill(-proc.pid, killing);
685
+ process5.kill(-proc.pid, killing);
671
686
  else
672
687
  proc.kill(killing);
673
688
  } catch {}
@@ -741,15 +756,67 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
741
756
  var RESET_STYLE = `${ESC}[0m`;
742
757
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
743
758
  // ../kit/src/cli.ts
744
- import process5 from "process";
759
+ import process7 from "process";
760
+
761
+ // ../kit/src/usage.ts
762
+ import { appendFileSync, mkdirSync } from "fs";
763
+ import { homedir } from "os";
764
+ import { dirname, isAbsolute, join } from "path";
765
+ import process6 from "process";
766
+
767
+ // ../kit/src/logs.ts
768
+ var DAY_MS = 24 * 60 * 60 * 1000;
769
+ var CLI_FOLDER = "kaynooo-cli";
770
+
771
+ // ../kit/src/usage.ts
772
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
773
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
774
+ var LONGEST_NAME = 40;
775
+ var usageError;
776
+ function noteUsageError(message) {
777
+ usageError = message;
778
+ }
779
+ function stateHome(env = process6.env) {
780
+ const dir = env.XDG_STATE_HOME;
781
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
782
+ }
783
+ function usagePath(env = process6.env) {
784
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
785
+ }
786
+ function usageRecorded(env = process6.env) {
787
+ const off = env.KAYNOOO_CLI_NO_USAGE;
788
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
789
+ }
790
+ function flagNames(argv) {
791
+ const end = argv.indexOf("--");
792
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
793
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
794
+ }
795
+ function usageEntry(bin, command, argv, code, now = new Date) {
796
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
797
+ usageError = undefined;
798
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
799
+ }
800
+ function recordUsage(entry, env = process6.env) {
801
+ if (!usageRecorded(env))
802
+ return;
803
+ try {
804
+ const path = usagePath(env);
805
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
806
+ appendFileSync(path, `${JSON.stringify(entry)}
807
+ `, { mode: 384 });
808
+ } catch {}
809
+ }
810
+
811
+ // ../kit/src/cli.ts
745
812
  var LEVEL_OPTIONS = {
746
813
  ...OUTPUT_OPTIONS,
747
814
  help: { type: "boolean", short: "h", description: "show this help" }
748
815
  };
749
816
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
750
817
  function printError(prefix, message, hint, cause) {
751
- const colors = paint(process5.stderr);
752
- const styled = takesControlCodes(process5.stderr);
818
+ const colors = paint(process7.stderr);
819
+ const styled = takesControlCodes(process7.stderr);
753
820
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
754
821
  const under = (label, text, tint) => text === undefined ? "" : `
755
822
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -768,6 +835,8 @@ function reportThrown(prefix, error, redact = (text) => text, json = false) {
768
835
  const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
769
836
  const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
770
837
  const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
838
+ if (error instanceof UsageError)
839
+ noteUsageError(error.message);
771
840
  const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
772
841
  report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
773
842
  return error instanceof Exit ? error.code : 1;
@@ -829,18 +898,22 @@ async function printCandidates(found) {
829
898
  console.log(line);
830
899
  return 0;
831
900
  }
832
- async function runMain({ name, version, run, redact }, argv = process5.argv.slice(2)) {
901
+ async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
833
902
  if (argv[0] === COMPLETE)
834
903
  return printCandidates(leafCandidates(run, argv.slice(1)));
835
904
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
836
905
  console.log(version);
837
906
  return 0;
838
907
  }
908
+ let code;
839
909
  try {
840
- return await run(argv);
910
+ code = await run(argv);
841
911
  } catch (error) {
842
- return reportThrown(name, error, redact, wantsJson(argv));
912
+ code = reportThrown(name, error, redact, wantsJson(argv));
843
913
  }
914
+ if (usage !== false)
915
+ recordUsage(usageEntry(name, undefined, argv, code));
916
+ return code;
844
917
  }
845
918
  // ../kit/src/limit.ts
846
919
  function limitOptions(fallback) {
@@ -863,8 +936,6 @@ function capped(rows, limit) {
863
936
  const more = rows.length - limit;
864
937
  return more > 0 ? { shown: rows.slice(0, limit), footer: moreFooter(more) } : { shown: [...rows], footer: undefined };
865
938
  }
866
- // ../kit/src/logs.ts
867
- var DAY_MS = 24 * 60 * 60 * 1000;
868
939
  // ../kit/src/secrets.ts
869
940
  var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
870
941
  // ../kit/src/sessions.ts
@@ -872,11 +943,11 @@ var {Glob } = globalThis.Bun;
872
943
  var SESSION_FILES = new Glob("*.json");
873
944
  var ACCOUNT_DIRS = new Glob("*/sessions");
874
945
  // package.json
875
- var version = "0.6.0";
946
+ var version = "0.7.0";
876
947
 
877
948
  // src/files.ts
878
949
  import { existsSync, readdirSync, statSync } from "fs";
879
- import { join, relative } from "path";
950
+ import { join as join2, relative } from "path";
880
951
  var MAX_BYTES = 2000000;
881
952
  var SNIFF_BYTES = 8000;
882
953
  var SKIPPED = new Set(["node_modules", "dist", "build", "vendor", "target", "coverage"]);
@@ -891,17 +962,17 @@ function walk(dir, found) {
891
962
  if (entry.name.startsWith(".") || SKIPPED.has(entry.name))
892
963
  continue;
893
964
  if (entry.isDirectory())
894
- walk(join(dir, entry.name), found);
965
+ walk(join2(dir, entry.name), found);
895
966
  else if (entry.isFile())
896
- found.push(join(dir, entry.name));
967
+ found.push(join2(dir, entry.name));
897
968
  }
898
969
  return found;
899
970
  }
900
971
  async function listFiles(paths, cwd) {
901
972
  const listed = await runCommand(["git", "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", ...paths], { cwd });
902
973
  if (listed.code === 0)
903
- return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join(cwd, path))).sort();
904
- const roots = paths.length === 0 ? [cwd] : paths.map((path) => join(cwd, path));
974
+ return [...new Set(listed.text.split("\x00"))].filter((path) => path !== "" && existsSync(join2(cwd, path))).sort();
975
+ const roots = paths.length === 0 ? [cwd] : paths.map((path) => join2(cwd, path));
905
976
  return roots.flatMap((root) => statSync(root, { throwIfNoEntry: false })?.isFile() === true ? [root] : walk(root, [])).map((path) => relative(cwd, path)).sort();
906
977
  }
907
978
  async function readText(path) {
@@ -1005,11 +1076,11 @@ function printLines(lines, footer) {
1005
1076
  }
1006
1077
  async function main(args) {
1007
1078
  const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["[path...]"], replaces: "grep -rn TODO, then opening each issue it names", examples: ["todo-scan src", ["todo-scan --stale", "only the comments naming a closed issue"]] });
1008
- const cwd = process7.cwd();
1079
+ const cwd = process9.cwd();
1009
1080
  const limit = limitOf(values, LIST_LIMIT);
1010
1081
  const marks = [];
1011
1082
  for (const path of await listFiles(positionals, cwd)) {
1012
- const text = await readText(join2(cwd, path));
1083
+ const text = await readText(join3(cwd, path));
1013
1084
  if (text !== undefined)
1014
1085
  marks.push(...marksIn(text, path));
1015
1086
  }
@@ -1034,4 +1105,4 @@ async function main(args) {
1034
1105
  return 1;
1035
1106
  return failed.size > 0 ? 2 : 0;
1036
1107
  }
1037
- process7.exitCode = await runMain({ name: "todo-scan", version, run: main });
1108
+ process9.exitCode = await runMain({ name: "todo-scan", version, run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-code",
3
3
  "type": "module",
4
- "version": "0.6.0",
4
+ "version": "0.7.0",
5
5
  "description": "peek, todo-scan and hotspots: source read by spans, symbols and outlines in one call, the TODO and issue-reference comments of a repository with stale ones flagged, and the files ranked by complexity times git churn.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -41,6 +41,6 @@
41
41
  "hotspots": "$npm_execpath src/hotspots.ts"
42
42
  },
43
43
  "devDependencies": {
44
- "@kaynooo/cli-kit": "0.19.0"
44
+ "@kaynooo/cli-kit": "0.20.0"
45
45
  }
46
46
  }