@kaynooo/cli-code 0.6.1 → 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
@@ -438,6 +438,17 @@ function wholeNumber(value, name, fallback, min = 1) {
438
438
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
439
439
  return number;
440
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
+ }
441
452
  function isStdinPiped() {
442
453
  const stat = fstatSync(0);
443
454
  return stat.isFIFO() || stat.isFile();
@@ -932,12 +943,13 @@ var {Glob } = globalThis.Bun;
932
943
  var SESSION_FILES = new Glob("*.json");
933
944
  var ACCOUNT_DIRS = new Glob("*/sessions");
934
945
  // package.json
935
- var version = "0.6.1";
946
+ var version = "0.7.0";
936
947
 
937
948
  // src/churn.ts
938
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)$/;
939
950
  var TESTS = /(?:^|\/)(?:tests?|__tests__|spec|e2e|__mocks__|fixtures)\/|\.(?:test|spec|bench)\.[^/]+$|(?:^|\/)test_[^/]+$|_test\.(?:go|py)$/;
940
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/;
941
953
  var GENERATED_HEADER = /@generated|generated by|do not edit/i;
942
954
  var DECISION = /\b(?:if|elif|elsif|for|foreach|while|until|case|when|catch|except|rescue|match|guard|and|or)\b|&&|\|\||\?\?|\?(?=[^.?:])/g;
943
955
  var COMMENT = /\/\*[\s\S]*?\*\/|\/\/[^\n]*|^[ \t]*#[^\n]*/gm;
@@ -951,14 +963,22 @@ function isGenerated(text) {
951
963
  function complexityOf(text) {
952
964
  return 1 + (text.replace(COMMENT, "").replace(STRING, '""').match(DECISION)?.length ?? 0);
953
965
  }
954
- async function churnSince(cwd, since) {
955
- 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 });
956
968
  if (log.code !== 0)
957
969
  return;
958
970
  const churn = new Map;
959
- for (const path of log.text.split("\x00")) {
960
- if (path !== "")
961
- 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
+ }
962
982
  }
963
983
  return churn;
964
984
  }
@@ -1004,21 +1024,65 @@ async function readText(path) {
1004
1024
  }
1005
1025
  }
1006
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
+
1007
1066
  // src/hotspots.ts
1008
1067
  var DEFAULT_SINCE = "6 months ago";
1068
+ var DEFAULT_BULK = 25;
1069
+ var DAY_MS2 = 86400000;
1070
+ var DEFAULT_HALF_LIFE = "90d";
1009
1071
  var DEFAULT_COUNT = 20;
1010
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
1011
1073
 
1012
- 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.
1013
1075
 
1014
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.
1015
1077
 
1016
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.`;
1017
1079
  var OPTIONS = {
1018
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})` },
1019
1083
  ...limitOptions(DEFAULT_COUNT),
1020
1084
  all: { type: "boolean", short: "a", description: "keep test files and generated files" },
1021
- 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")
1022
1086
  };
1023
1087
  async function main(args) {
1024
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'] });
@@ -1026,7 +1090,11 @@ async function main(args) {
1026
1090
  badUsage("give one folder");
1027
1091
  const count = limitOf(values, DEFAULT_COUNT);
1028
1092
  const cwd = process9.cwd();
1029
- const churn = await churnSince(cwd, values.since ?? DEFAULT_SINCE);
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 });
1030
1098
  if (churn === undefined)
1031
1099
  fail("not a git repository, churn comes from its log");
1032
1100
  const ranked = [];
@@ -1038,7 +1106,8 @@ async function main(args) {
1038
1106
  if (text === undefined || values.all !== true && isGenerated(text))
1039
1107
  continue;
1040
1108
  const complexity = complexityOf(text);
1041
- 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(`
1042
1111
  `).length - (text.endsWith(`
1043
1112
  `) ? 1 : 0) });
1044
1113
  }
@@ -1051,7 +1120,7 @@ async function main(args) {
1051
1120
  printJson(shown);
1052
1121
  return 0;
1053
1122
  }
1054
- 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"] }));
1055
1124
  if (footer !== undefined)
1056
1125
  console.log(footer);
1057
1126
  return 0;
package/dist/peek.js CHANGED
@@ -439,6 +439,17 @@ function wholeNumber(value, name, fallback, min = 1) {
439
439
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
440
440
  return number;
441
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
+ }
442
453
  function isStdinPiped() {
443
454
  const stat = fstatSync(0);
444
455
  return stat.isFIFO() || stat.isFile();
@@ -933,7 +944,7 @@ var {Glob } = globalThis.Bun;
933
944
  var SESSION_FILES = new Glob("*.json");
934
945
  var ACCOUNT_DIRS = new Glob("*/sessions");
935
946
  // package.json
936
- var version = "0.6.1";
947
+ var version = "0.7.0";
937
948
 
938
949
  // src/files.ts
939
950
  import { existsSync, readdirSync, statSync } from "fs";
package/dist/todo-scan.js CHANGED
@@ -438,6 +438,17 @@ function wholeNumber(value, name, fallback, min = 1) {
438
438
  badUsage(`${name.startsWith("<") ? name : `--${name}`} takes a whole number from ${min}, not ${value}`);
439
439
  return number;
440
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
+ }
441
452
  function isStdinPiped() {
442
453
  const stat = fstatSync(0);
443
454
  return stat.isFIFO() || stat.isFile();
@@ -932,7 +943,7 @@ var {Glob } = globalThis.Bun;
932
943
  var SESSION_FILES = new Glob("*.json");
933
944
  var ACCOUNT_DIRS = new Glob("*/sessions");
934
945
  // package.json
935
- var version = "0.6.1";
946
+ var version = "0.7.0";
936
947
 
937
948
  // src/files.ts
938
949
  import { existsSync, readdirSync, statSync } from "fs";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-code",
3
3
  "type": "module",
4
- "version": "0.6.1",
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",