@kaynooo/cli-code 0.14.3 → 0.15.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.
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/todo-scan-cli.ts
5
- import process16 from "process";
5
+ import process17 from "process";
6
6
  // ../kit/src/args.ts
7
7
  import process9 from "process";
8
8
  import { parseArgs } from "util";
@@ -422,6 +422,23 @@ function fileLink(text, path, stream, from = process6.cwd(), env = process6.env)
422
422
  }
423
423
 
424
424
  // ../kit/src/format.ts
425
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
426
+ function formatSeconds(total) {
427
+ let rest = Math.max(0, Math.round(total));
428
+ const amounts = UNITS.map(([unit, size]) => {
429
+ const amount = Math.floor(rest / size);
430
+ rest -= amount * size;
431
+ return `${amount}${unit}`;
432
+ });
433
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
434
+ if (first === -1)
435
+ return "0s";
436
+ const next = amounts[first + 1];
437
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
438
+ }
439
+ function formatDuration(ms) {
440
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
441
+ }
425
442
  function upTo(text, separator) {
426
443
  const end = text.indexOf(separator);
427
444
  return end === -1 ? text : text.slice(0, end);
@@ -482,7 +499,7 @@ function printJson(value) {
482
499
 
483
500
  // ../kit/src/help.ts
484
501
  import process8 from "process";
485
- var OPTIONAL = /\[[^\]]+\]/g;
502
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
486
503
  var USAGE_PREFIX = /^usage:\s*/i;
487
504
  var FULL_STOP = /\.$/;
488
505
  function usageLine(usage, colors = paint(process8.stdout)) {
@@ -521,29 +538,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
521
538
  return [];
522
539
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
523
540
  }
541
+ var MAX_INLINE_CHOICES = 24;
524
542
  function optionRows(options, colors = paint(process8.stdout)) {
525
543
  const rows = Object.entries(options).map(([name, option]) => {
526
544
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
527
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
545
+ const choices = option.choices?.join("|");
546
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
547
+ const named = inline ? `<${choices}>` : "<value>";
528
548
  const placeholder = option.optional === undefined ? named : `[${named}]`;
529
549
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
530
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
550
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
551
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
531
552
  });
532
553
  const width = Math.max(0, ...rows.map((row) => row.width));
533
554
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
534
555
  }
535
556
 
536
557
  // ../kit/src/text.ts
537
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
538
558
  function distance(a, b) {
539
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
540
- for (const [i, left] of [...a].entries()) {
559
+ const left = [...a];
560
+ const right = [...b];
561
+ let before = [];
562
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
563
+ for (const [i, x] of left.entries()) {
541
564
  const current = [i + 1];
542
- for (const [j, right] of [...b].entries())
543
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
565
+ for (const [j, y] of right.entries()) {
566
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
567
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
568
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
569
+ current.push(cost);
570
+ }
571
+ before = previous;
544
572
  previous = current;
545
573
  }
546
- return previous[b.length] ?? 0;
574
+ return previous[right.length] ?? 0;
547
575
  }
548
576
  function closest(name, names) {
549
577
  const started = names.find((known) => known.startsWith(name));
@@ -918,13 +946,31 @@ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
918
946
  // ../kit/src/cli.ts
919
947
  import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
920
948
  import { dirname as dirname3, join as join5 } from "path";
921
- import process13 from "process";
949
+ import process14 from "process";
950
+
951
+ // ../kit/src/notify.ts
952
+ import process12 from "process";
953
+ var NOTIFY_AFTER_MS = 1e4;
954
+ var CANCELLED = 130;
955
+ function base64(text) {
956
+ return Buffer.from(text).toString("base64");
957
+ }
958
+ function notification(title, body, env = process12.env) {
959
+ const id = `kit${process12.pid}`;
960
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
961
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
962
+ }
963
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
964
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
965
+ return;
966
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
967
+ }
922
968
 
923
969
  // ../kit/src/usage.ts
924
970
  import { appendFileSync, mkdirSync } from "fs";
925
971
  import { homedir as homedir3 } from "os";
926
972
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
927
- import process12 from "process";
973
+ import process13 from "process";
928
974
 
929
975
  // ../kit/src/logs.ts
930
976
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -938,14 +984,14 @@ var usageError;
938
984
  function noteUsageError(message) {
939
985
  usageError = message;
940
986
  }
941
- function stateHome(env = process12.env) {
987
+ function stateHome(env = process13.env) {
942
988
  const dir = env.XDG_STATE_HOME;
943
989
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
944
990
  }
945
- function usagePath(env = process12.env) {
991
+ function usagePath(env = process13.env) {
946
992
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
947
993
  }
948
- function usageRecorded(env = process12.env) {
994
+ function usageRecorded(env = process13.env) {
949
995
  const off = env.KAYNOOO_CLI_NO_USAGE;
950
996
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
951
997
  }
@@ -959,7 +1005,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
959
1005
  usageError = undefined;
960
1006
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
961
1007
  }
962
- function recordUsage(entry, env = process12.env) {
1008
+ function recordUsage(entry, env = process13.env) {
963
1009
  if (!usageRecorded(env))
964
1010
  return;
965
1011
  try {
@@ -1049,8 +1095,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1049
1095
  `);
1050
1096
  }
1051
1097
  function printError(prefix, message, hint, cause) {
1052
- const colors = paint(process13.stderr);
1053
- const styled = takesControlCodes(process13.stderr);
1098
+ const colors = paint(process14.stderr);
1099
+ const styled = takesControlCodes(process14.stderr);
1054
1100
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1055
1101
  const under = (label, text, tint) => text === undefined ? "" : `
1056
1102
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1093,11 +1139,11 @@ async function dispatch(level, typed, { version, redact }) {
1093
1139
  }
1094
1140
  }
1095
1141
  if (name === undefined && level.path.length > 1) {
1096
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stderr));
1142
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1097
1143
  return 2;
1098
1144
  }
1099
1145
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1100
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process13.stdout));
1146
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1101
1147
  return 0;
1102
1148
  }
1103
1149
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1232,10 +1278,13 @@ async function runCli(cli, argv = scriptArgs()) {
1232
1278
  const version = cli.version ?? packageVersion();
1233
1279
  if (argv[0] === COMPLETE)
1234
1280
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1281
+ const started = performance.now();
1235
1282
  const code = await dispatch({ path: [cli.name], header: (colors, about) => `${colors.bold(cli.name)} ${colors.dim(version)} ${about}`, summary: cli.about, ...scopeOf(cli.commands, cli.extraCommands, cli.aliases), defaultCommand: cli.defaultCommand, runBare: cli.runBare === true, examples: cli.examples, replaces: cli.replaces }, argv, { version, redact: cli.redact });
1283
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1284
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1236
1285
  if (cli.usage !== false) {
1237
1286
  try {
1238
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1287
+ recordUsage(usageEntry(cli.name, command, argv, code));
1239
1288
  } catch {}
1240
1289
  }
1241
1290
  return code;
@@ -1263,11 +1312,13 @@ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs(
1263
1312
  return 0;
1264
1313
  }
1265
1314
  let code;
1315
+ const started = performance.now();
1266
1316
  try {
1267
1317
  code = await run(argv);
1268
1318
  } catch (error) {
1269
1319
  code = reportThrown(name, error, redact, wantsJson(argv));
1270
1320
  }
1321
+ notifyEnd(name, code, performance.now() - started);
1271
1322
  if (usage !== false) {
1272
1323
  try {
1273
1324
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1311,7 +1362,7 @@ var SESSION_FILES = new Glob("*.json");
1311
1362
  var ACCOUNT_DIRS = new Glob("*/sessions");
1312
1363
  // src/todo-scan.ts
1313
1364
  import { join as join7 } from "path";
1314
- import process15 from "process";
1365
+ import process16 from "process";
1315
1366
 
1316
1367
  // src/files.ts
1317
1368
  import { existsSync as existsSync4, readdirSync, statSync as statSync2 } from "fs";
@@ -1359,7 +1410,7 @@ var COMMENT = /(?<![:\w/])\/\/|\/\*|<!--|(?:^|\s)(?:#|--)(?=\s)|^\s*\*(?=\s|$)/;
1359
1410
  var MARKUP = /\.(?:md|mdx|markdown|html?|xml)$/i;
1360
1411
  var MARKUP_COMMENT = /<!--/;
1361
1412
  var CLOSERS = /\s*(?:\*\/|-->)\s*$/;
1362
- var MARKER = /^(?:@|\[)?(TODO|FIXME)\b/;
1413
+ var MARKER = /^(?:@|\[)?(TODO|FIXME|HACK|XXX)\b/;
1363
1414
  var QUOTES = ["'", '"', "`"];
1364
1415
  var ESCAPE2 = /\\./g;
1365
1416
  var AFTER_FIRST_LINE = /\n[\s\S]*/;
@@ -1368,6 +1419,40 @@ function isQuoted(line, index) {
1368
1419
  const before = line.slice(0, index).replaceAll(ESCAPE2, "");
1369
1420
  return QUOTES.some((quote) => before.split(quote).length % 2 === 0);
1370
1421
  }
1422
+ var BLAME_HEADER = /^[0-9a-f]{40} \d+ (\d+)/;
1423
+ var DAY_S = 86400;
1424
+ async function commitTimes(path, cwd) {
1425
+ const blamed = await runCommand(["git", "blame", "--porcelain", "--", path], { cwd });
1426
+ const times = new Map;
1427
+ if (blamed.code !== 0)
1428
+ return times;
1429
+ const bySha = new Map;
1430
+ let sha = "";
1431
+ let line = 0;
1432
+ for (const row of stdoutOf(blamed.chunks).split(`
1433
+ `)) {
1434
+ const header = BLAME_HEADER.exec(row);
1435
+ if (header !== null) {
1436
+ sha = row.slice(0, 40);
1437
+ line = Number(header[1]);
1438
+ } else if (row.startsWith("committer-time ")) {
1439
+ bySha.set(sha, Number(row.slice("committer-time ".length)));
1440
+ } else if (row.startsWith("\t")) {
1441
+ times.set(line, bySha.get(sha) ?? 0);
1442
+ }
1443
+ }
1444
+ return times;
1445
+ }
1446
+ async function addAges(marks, cwd, now = Date.now() / 1000) {
1447
+ await Promise.all([...Map.groupBy(marks, (mark) => mark.path)].map(async ([path, ofFile]) => {
1448
+ const times = await commitTimes(path, cwd);
1449
+ for (const mark of ofFile) {
1450
+ const time = times.get(mark.line);
1451
+ if (time !== undefined)
1452
+ mark.age = Math.max(0, Math.floor((now - time) / DAY_S));
1453
+ }
1454
+ }));
1455
+ }
1371
1456
  function marksIn(text, path) {
1372
1457
  const marks = [];
1373
1458
  const comment = MARKUP.test(path) ? MARKUP_COMMENT : COMMENT;
@@ -1423,17 +1508,21 @@ async function lookUp(refs, cwd) {
1423
1508
  }
1424
1509
 
1425
1510
  // src/todo-scan.ts
1426
- var USAGE = `todo-scan [options] [path...]: lists the TODO, FIXME and owner/repo#N comments under the paths (here by default), each as <file>:<line>: <comment>, honouring .gitignore
1511
+ var USAGE = `todo-scan [options] [path...]: lists the TODO, FIXME, HACK, XXX and owner/repo#N comments under the paths (here by default), each as <file>:<line>: <comment>, honouring .gitignore
1512
+
1513
+ --older <duration> keeps only the comments whose line last changed longer ago than that (30d, 12w, 6m: git blame dates each one, a file git cannot blame is left out) and shows each one's age.
1427
1514
 
1428
1515
  --stale keeps only the comments naming a closed issue, each issue's state looked up with ft, or gh for a GitHub repository, and exits 1 when it finds one.
1429
1516
 
1430
1517
  Lists at most 100 comments, the count of the rest after them (--limit <n>, --full for all); --json is never cut unless --limit is given.`;
1431
1518
  var EXITS = [[0, "it listed the comments or found no stale one"], [1, "--stale finds one"], [2, "a usage error or when --stale could not look a repository up (ft and gh both failed)"]];
1432
1519
  var LIST_LIMIT = 100;
1520
+ var DAY_MS2 = 86400000;
1433
1521
  var OPTIONS = {
1434
1522
  stale: { type: "boolean", description: "only the comments naming a closed issue, looked up with ft or gh" },
1523
+ older: { type: "string", description: "only the comments whose line last changed longer ago than this duration, from git blame" },
1435
1524
  ...limitOptions(LIST_LIMIT),
1436
- json: jsonOption("[{path, line, kind, text, refs: [{repo, number, state?}]}]")
1525
+ json: jsonOption("[{path, line, kind, text, refs: [{repo, number, state?}], age?}], age being the days since the line last changed, given with --older or --json when git can date it")
1437
1526
  };
1438
1527
  function printLines(lines, footer) {
1439
1528
  const all = [...lines, ...footer === undefined ? [] : [footer]];
@@ -1443,20 +1532,27 @@ function printLines(lines, footer) {
1443
1532
  }
1444
1533
  async function todoScan(args) {
1445
1534
  const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, 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"]] });
1446
- const cwd = process15.cwd();
1535
+ const cwd = process16.cwd();
1447
1536
  const limit = limitOf(values, LIST_LIMIT);
1448
- const marks = [];
1537
+ const found = [];
1449
1538
  for (const path of await listFiles(positionals, cwd)) {
1450
1539
  const text = await readText(join7(cwd, path));
1451
1540
  if (text !== undefined)
1452
- marks.push(...marksIn(text, path));
1541
+ found.push(...marksIn(text, path));
1453
1542
  }
1543
+ const older = values.older === undefined ? undefined : duration(values.older, "older", 0, "m") / DAY_MS2;
1544
+ let marks = found;
1545
+ if (older !== undefined || values.json === true)
1546
+ await addAges(found, cwd);
1547
+ const ageNote = (mark) => older === undefined || mark.age === undefined ? "" : ` [${mark.age}d]`;
1548
+ if (older !== undefined)
1549
+ marks = found.filter((mark) => mark.age !== undefined && mark.age >= older);
1454
1550
  if (values.stale !== true) {
1455
1551
  const { shown, footer } = capped(marks, limit);
1456
1552
  if (values.json === true)
1457
1553
  printJson(shown);
1458
1554
  else
1459
- printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.text}`), footer);
1555
+ printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.text}${ageNote(mark)}`), footer);
1460
1556
  return 0;
1461
1557
  }
1462
1558
  const { states, failed } = await lookUp(marks.flatMap((mark) => mark.refs), cwd);
@@ -1467,11 +1563,11 @@ async function todoScan(args) {
1467
1563
  if (values.json === true)
1468
1564
  printJson(shown.map((mark) => ({ ...mark, refs: mark.refs.map((ref) => ({ ...ref, state: states.get(refKey(ref)) })) })));
1469
1565
  else
1470
- printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.refs.filter((ref) => states.get(refKey(ref)) === "closed").map(refKey).join(", ")} closed: ${mark.text}`), footer);
1566
+ printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.refs.filter((ref) => states.get(refKey(ref)) === "closed").map(refKey).join(", ")} closed: ${mark.text}${ageNote(mark)}`), footer);
1471
1567
  if (stale.length > 0)
1472
1568
  return 1;
1473
1569
  return failed.size > 0 ? 2 : 0;
1474
1570
  }
1475
1571
 
1476
1572
  // src/todo-scan-cli.ts
1477
- process16.exitCode = await runMain({ name: "todo-scan", run: todoScan });
1573
+ process17.exitCode = await runMain({ name: "todo-scan", run: todoScan });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-code",
3
3
  "type": "module",
4
- "version": "0.14.3",
4
+ "version": "0.15.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",
@@ -46,6 +46,6 @@
46
46
  "@kaynooo/utils": "3.0.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@kaynooo/cli-kit": "0.38.2"
49
+ "@kaynooo/cli-kit": "0.39.0"
50
50
  }
51
51
  }