@kaynooo/cli-code 0.14.2 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // @bun
3
3
 
4
4
  // src/cli.ts
5
- import process17 from "process";
5
+ import process19 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,24 +499,20 @@ 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)) {
489
506
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
490
507
  }
491
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
492
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
508
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
509
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
493
510
  `);
494
511
  }
495
512
  function exitRows(exits, colors = paint(process8.stdout)) {
496
513
  if (exits.length === 0)
497
514
  return [];
498
- const width = Math.max(...exits.map(([code]) => String(code).length));
499
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
500
- }
501
- function replacesRows(replaces, colors = paint(process8.stdout)) {
502
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
515
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
503
516
  }
504
517
  function wantsHelpJson(env = process8.env) {
505
518
  return env.KIT_HELP === "json";
@@ -525,29 +538,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
525
538
  return [];
526
539
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
527
540
  }
541
+ var MAX_INLINE_CHOICES = 24;
528
542
  function optionRows(options, colors = paint(process8.stdout)) {
529
543
  const rows = Object.entries(options).map(([name, option]) => {
530
544
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
531
- 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>";
532
548
  const placeholder = option.optional === undefined ? named : `[${named}]`;
533
549
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
534
- 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 };
535
552
  });
536
553
  const width = Math.max(0, ...rows.map((row) => row.width));
537
554
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
538
555
  }
539
556
 
540
557
  // ../kit/src/text.ts
541
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
542
558
  function distance(a, b) {
543
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
544
- 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()) {
545
564
  const current = [i + 1];
546
- for (const [j, right] of [...b].entries())
547
- 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;
548
572
  previous = current;
549
573
  }
550
- return previous[b.length] ?? 0;
574
+ return previous[right.length] ?? 0;
551
575
  }
552
576
  function closest(name, names) {
553
577
  const started = names.find((known) => known.startsWith(name));
@@ -628,7 +652,7 @@ class Completing {
628
652
  }
629
653
  var completion = { active: false };
630
654
  var OUTPUT_OPTIONS = {
631
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
655
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
632
656
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
633
657
  };
634
658
  function applyOutput(color, plain, env = process9.env) {
@@ -800,9 +824,33 @@ function nearestOption(message, options, allowNegative) {
800
824
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
801
825
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
802
826
  }
827
+ // ../kit/src/argv.ts
828
+ import { readFileSync as readFileSync3, realpathSync } from "fs";
829
+ import { resolve as resolve4 } from "path";
830
+ import process10 from "process";
831
+ function commandLine() {
832
+ try {
833
+ return readFileSync3("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
834
+ } catch {
835
+ return;
836
+ }
837
+ }
838
+ function realPath(word) {
839
+ try {
840
+ return realpathSync(resolve4(word));
841
+ } catch {
842
+ return;
843
+ }
844
+ }
845
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
846
+ const target = script === undefined ? undefined : realPath(script) ?? script;
847
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve4(word) === script || realPath(word) === target));
848
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
849
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
850
+ }
803
851
  // ../kit/src/process.ts
804
852
  import { constants } from "os";
805
- import process10 from "process";
853
+ import process11 from "process";
806
854
  var KILL_GRACE_MS = 2000;
807
855
  function exitCodeOf(code, signal) {
808
856
  if (code !== null)
@@ -822,7 +870,7 @@ async function runCommand(argv, { cwd, env, stdin = "ignore", timeoutMs, signal,
822
870
  return;
823
871
  try {
824
872
  if (grouped)
825
- process10.kill(-proc.pid, killing);
873
+ process11.kill(-proc.pid, killing);
826
874
  else
827
875
  proc.kill(killing);
828
876
  } catch {}
@@ -896,15 +944,93 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
896
944
  var RESET_STYLE = `${ESC}[0m`;
897
945
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
898
946
  // ../kit/src/cli.ts
899
- import { readFileSync as readFileSync3, realpathSync } from "fs";
947
+ import { readFileSync as readFileSync4, realpathSync as realpathSync2 } from "fs";
900
948
  import { dirname as dirname3, join as join5 } from "path";
949
+ import process14 from "process";
950
+
951
+ // ../kit/src/completions.ts
952
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
953
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
954
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
955
+ set -l current (commandline -ct)
956
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
957
+ if test "$line" = __files__
958
+ __fish_complete_path $current
959
+ else
960
+ echo $line
961
+ end
962
+ end
963
+ end`;
964
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
965
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
966
+ local -a lines
967
+ COMPREPLY=()
968
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
969
+ for line in "\${lines[@]}"; do
970
+ if [[ $line == __files__ ]]; then
971
+ COMPREPLY+=($(compgen -f -- "$cur"))
972
+ else
973
+ words+="\${line%%$'\\t'*}"$'\\n'
974
+ fi
975
+ done
976
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
977
+ }`;
978
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
979
+ local line
980
+ local -a described plain
981
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
982
+ if [[ $line == __files__ ]]; then
983
+ _files
984
+ elif [[ $line == *$'\\t'* ]]; then
985
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
986
+ else
987
+ plain+=("$line")
988
+ fi
989
+ done
990
+ (( \${#described} )) && _describe -V value described
991
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
992
+ return 0
993
+ }`;
994
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
995
+ if (shell === "fish")
996
+ return `${header}
997
+ ${FISH_FUNCTION}
998
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
999
+ `).join("")}`;
1000
+ if (shell === "bash")
1001
+ return `${header}
1002
+ ${BASH_FUNCTION}
1003
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
1004
+ `;
1005
+ return `${header}
1006
+ ${ZSH_FUNCTION}
1007
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
1008
+ `;
1009
+ }
1010
+
1011
+ // ../kit/src/notify.ts
901
1012
  import process12 from "process";
1013
+ var NOTIFY_AFTER_MS = 1e4;
1014
+ var CANCELLED = 130;
1015
+ function base64(text) {
1016
+ return Buffer.from(text).toString("base64");
1017
+ }
1018
+ function notification(title, body, env = process12.env) {
1019
+ const id = `kit${process12.pid}`;
1020
+ 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\\`];
1021
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
1022
+ }
1023
+ function notifyEnd(command, code, ms, { stream = process12.stderr, env = process12.env } = {}) {
1024
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
1025
+ return;
1026
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
1027
+ }
902
1028
 
903
1029
  // ../kit/src/usage.ts
904
1030
  import { appendFileSync, mkdirSync } from "fs";
905
1031
  import { homedir as homedir3 } from "os";
906
1032
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
907
- import process11 from "process";
1033
+ import process13 from "process";
908
1034
 
909
1035
  // ../kit/src/logs.ts
910
1036
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -918,14 +1044,14 @@ var usageError;
918
1044
  function noteUsageError(message) {
919
1045
  usageError = message;
920
1046
  }
921
- function stateHome(env = process11.env) {
1047
+ function stateHome(env = process13.env) {
922
1048
  const dir = env.XDG_STATE_HOME;
923
1049
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
924
1050
  }
925
- function usagePath(env = process11.env) {
1051
+ function usagePath(env = process13.env) {
926
1052
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
927
1053
  }
928
- function usageRecorded(env = process11.env) {
1054
+ function usageRecorded(env = process13.env) {
929
1055
  const off = env.KAYNOOO_CLI_NO_USAGE;
930
1056
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
931
1057
  }
@@ -939,7 +1065,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
939
1065
  usageError = undefined;
940
1066
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
941
1067
  }
942
- function recordUsage(entry, env = process11.env) {
1068
+ function recordUsage(entry, env = process13.env) {
943
1069
  if (!usageRecorded(env))
944
1070
  return;
945
1071
  try {
@@ -955,7 +1081,11 @@ var LEVEL_OPTIONS = {
955
1081
  ...OUTPUT_OPTIONS,
956
1082
  help: { type: "boolean", short: "h", description: "show this help" }
957
1083
  };
958
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
1084
+ var TOP_OPTIONS = {
1085
+ ...LEVEL_OPTIONS,
1086
+ version: { type: "boolean", short: "v", description: "print the version" },
1087
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
1088
+ };
959
1089
  async function commandRows(all, colors) {
960
1090
  const commands = shown(all);
961
1091
  const width = Math.max(0, ...Object.keys(commands).map((name) => name.length));
@@ -1016,7 +1146,6 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1016
1146
  header(colors, summary),
1017
1147
  "",
1018
1148
  usageLine(`${prefix} ${defaultCommand === undefined ? colors.cyan("<command>") : `[${colors.cyan("<command>")}]`} [options]`, colors),
1019
- ...replacesRows(replaces, colors),
1020
1149
  "",
1021
1150
  ...await commandRows(commands, colors),
1022
1151
  ...own.length === 0 ? [] : ["", `${colors.bold(`Options of ${defaultCommand}:`)} ${colors.dim("the command run when none is named")}`, ...optionRows(Object.fromEntries(own), colors)],
@@ -1030,8 +1159,8 @@ async function help2({ path, header, summary: lazySummary, commands, defaultComm
1030
1159
  `);
1031
1160
  }
1032
1161
  function printError(prefix, message, hint, cause) {
1033
- const colors = paint(process12.stderr);
1034
- const styled = takesControlCodes(process12.stderr);
1162
+ const colors = paint(process14.stderr);
1163
+ const styled = takesControlCodes(process14.stderr);
1035
1164
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
1036
1165
  const under = (label, text, tint) => text === undefined ? "" : `
1037
1166
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -1074,11 +1203,11 @@ async function dispatch(level, typed, { version, redact }) {
1074
1203
  }
1075
1204
  }
1076
1205
  if (name === undefined && level.path.length > 1) {
1077
- console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stderr));
1206
+ console.error(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stderr));
1078
1207
  return 2;
1079
1208
  }
1080
1209
  if (name === undefined || name === "help" || name === "--help" || name === "-h") {
1081
- console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process12.stdout));
1210
+ console.log(await help2(await expand(level, [...level.path.slice(1), ...argv]), process14.stdout));
1082
1211
  return 0;
1083
1212
  }
1084
1213
  if (level.path.length === 1 && (name === "--version" || name === "-v")) {
@@ -1134,24 +1263,24 @@ function candidateLine(candidate) {
1134
1263
  }
1135
1264
  function positionalBeingTyped(before, { options, positionals }) {
1136
1265
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
1137
- let index = 0;
1266
+ const typed = [];
1138
1267
  let at = 0;
1139
1268
  while (at < before.length) {
1140
1269
  const word = before[at];
1141
1270
  if (word === "--") {
1142
- index += before.length - at - 1;
1271
+ typed.push(...before.slice(at + 1));
1143
1272
  break;
1144
1273
  }
1145
1274
  if (!word.startsWith("-"))
1146
- index++;
1275
+ typed.push(word);
1147
1276
  else if (takesValue(word))
1148
1277
  at++;
1149
1278
  at++;
1150
1279
  }
1151
1280
  const last = positionals.at(-1);
1152
- if (index < positionals.length)
1153
- return positionals[index];
1154
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
1281
+ if (typed.length < positionals.length)
1282
+ return { name: positionals[typed.length], typed };
1283
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
1155
1284
  }
1156
1285
  async function leafCandidates(run, words) {
1157
1286
  const completing = await completingOf(run);
@@ -1159,12 +1288,12 @@ async function leafCandidates(run, words) {
1159
1288
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
1160
1289
  const flag = words.at(-2);
1161
1290
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
1291
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
1162
1292
  if (option?.type === "string") {
1163
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
1293
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
1164
1294
  return values === undefined ? [FILES] : values.map(candidateLine);
1165
1295
  }
1166
- const name = positionalBeingTyped(words.slice(0, -1), completing);
1167
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
1296
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
1168
1297
  return values === undefined ? [FILES] : values.map(candidateLine);
1169
1298
  }
1170
1299
  async function candidates(scope, defaultCommand, words, before = []) {
@@ -1189,15 +1318,32 @@ async function candidates(scope, defaultCommand, words, before = []) {
1189
1318
  }
1190
1319
  return "commands" in command ? candidates(scopeOf(command.commands, command.extraCommands, command.aliases), undefined, rest, [...before, word]) : leafCandidates(command.run, rest);
1191
1320
  }
1321
+ var COMPLETIONS = "--completions";
1322
+ function flagValue([flag = "", ...rest]) {
1323
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
1324
+ }
1325
+ function printCompletionScript(name, args) {
1326
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
1327
+ if (shell === undefined || args.length !== 1) {
1328
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1329
+ return 2;
1330
+ }
1331
+ console.log(completionScript(shell, [name]).trimEnd());
1332
+ return 0;
1333
+ }
1192
1334
  async function printCandidates(found) {
1193
1335
  for (const line of await found)
1194
1336
  console.log(line);
1195
1337
  return 0;
1196
1338
  }
1197
1339
  function packageVersion(entry = Bun.main) {
1198
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1340
+ let resolved = entry;
1341
+ try {
1342
+ resolved = realpathSync2(entry);
1343
+ } catch {}
1344
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
1199
1345
  try {
1200
- const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
1346
+ const { version } = JSON.parse(readFileSync4(join5(dir, "package.json"), "utf8"));
1201
1347
  if (typeof version === "string")
1202
1348
  return version;
1203
1349
  } catch {}
@@ -1205,14 +1351,19 @@ function packageVersion(entry = Bun.main) {
1205
1351
  return "0.0.0";
1206
1352
  }
1207
1353
  }
1208
- async function runCli(cli, argv = process12.argv.slice(2)) {
1354
+ async function runCli(cli, argv = scriptArgs()) {
1209
1355
  const version = cli.version ?? packageVersion();
1210
1356
  if (argv[0] === COMPLETE)
1211
1357
  return printCandidates(candidates(scopeOf(cli.commands, cli.extraCommands, cli.aliases), cli.defaultCommand, argv.slice(1)));
1358
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1359
+ return printCompletionScript(cli.name, flagValue(argv));
1360
+ const started = performance.now();
1212
1361
  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 });
1362
+ const command = commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv);
1363
+ notifyEnd(command === undefined ? cli.name : `${cli.name} ${command}`, code, performance.now() - started);
1213
1364
  if (cli.usage !== false) {
1214
1365
  try {
1215
- recordUsage(usageEntry(cli.name, commandPath(scopeOf(cli.commands, cli.extraCommands, cli.aliases), argv), argv, code));
1366
+ recordUsage(usageEntry(cli.name, command, argv, code));
1216
1367
  } catch {}
1217
1368
  }
1218
1369
  return code;
@@ -1232,19 +1383,23 @@ function commandPath(scope, argv) {
1232
1383
  }
1233
1384
  return path.length === 0 ? undefined : path.join(" ");
1234
1385
  }
1235
- async function runMain({ name, version, run, redact, usage }, argv = process12.argv.slice(2)) {
1386
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
1236
1387
  if (argv[0] === COMPLETE)
1237
1388
  return printCandidates(leafCandidates(run, argv.slice(1)));
1389
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1390
+ return printCompletionScript(name, flagValue(argv));
1238
1391
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
1239
1392
  console.log(version ?? packageVersion());
1240
1393
  return 0;
1241
1394
  }
1242
1395
  let code;
1396
+ const started = performance.now();
1243
1397
  try {
1244
1398
  code = await run(argv);
1245
1399
  } catch (error) {
1246
1400
  code = reportThrown(name, error, redact, wantsJson(argv));
1247
1401
  }
1402
+ notifyEnd(name, code, performance.now() - started);
1248
1403
  if (usage !== false) {
1249
1404
  try {
1250
1405
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1288,7 +1443,7 @@ var SESSION_FILES = new Glob("*.json");
1288
1443
  var ACCOUNT_DIRS = new Glob("*/sessions");
1289
1444
  // src/hotspots.ts
1290
1445
  import { basename, join as join7 } from "path";
1291
- import process14 from "process";
1446
+ import process16 from "process";
1292
1447
 
1293
1448
  // src/churn.ts
1294
1449
  var SOURCE = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|kay|py|go|rs|rb|php|java|kt|swift|cs|c|cc|cpp|h|hpp|scala|dart|lua|sh|zsh|fish)$/;
@@ -1296,9 +1451,8 @@ var TESTS = /(?:^|\/)(?:tests?|__tests__|spec|e2e|__mocks__|fixtures)\/|\.(?:tes
1296
1451
  var GENERATED = /(?:^|\/)(?:dist|build|out|generated|\.nuxt|\.output|\.next)\/|\.min\.[cm]?js$|\.d\.ts$|\.(?:generated|gen)\.[^/]+$|\.pb\.go$|\.snap$/;
1297
1452
  var LEADING_NEWLINE = /^\n/;
1298
1453
  var GENERATED_HEADER = /@generated|generated by|do not edit/i;
1299
- var DECISION = /\b(?:if|elif|elsif|for|foreach|while|until|case|when|catch|except|rescue|match|guard|and|or)\b|&&|\|\||\?\?|\?(?=[^.?:])/g;
1300
- var COMMENT = /\/\*[\s\S]*?\*\/|\/\/[^\n]*|^[ \t]*#[^\n]*/gm;
1301
- var STRING = /'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`/g;
1454
+ var DECISION = /\b(?:if|elif|elsif|for|foreach|while|until|case|when|catch|except|rescue|match|guard|and|or)\b|&&|\|\||\?\?|\s\?(?![,):.?])/g;
1455
+ var COMMENT_OR_STRING = /(\/\*[\s\S]*?\*\/|\/\/[^\n]*|^[ \t]*#[^\n]*)|'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`/gm;
1302
1456
  function isCandidate(path) {
1303
1457
  return SOURCE.test(path) && !TESTS.test(path) && !GENERATED.test(path);
1304
1458
  }
@@ -1306,25 +1460,35 @@ function isGenerated(text) {
1306
1460
  return GENERATED_HEADER.test(text.slice(0, 400));
1307
1461
  }
1308
1462
  function complexityOf(text) {
1309
- return 1 + (text.replace(COMMENT, "").replace(STRING, '""').match(DECISION)?.length ?? 0);
1463
+ return 1 + (text.replace(COMMENT_OR_STRING, (_, comment) => comment === undefined ? '""' : "").match(DECISION)?.length ?? 0);
1310
1464
  }
1311
1465
  async function churnSince(cwd, since, { bulk, halfLifeMs, now = Date.now() }) {
1312
- const log = await runCommand(["git", "log", `--since=${since}`, "--no-renames", "--relative", "--name-only", "--format=%x01%ct", "-z"], { cwd });
1313
- if (log.code !== 0)
1466
+ const [log, top] = await Promise.all([runCommand(["git", "log", `--since=${since}`, "--no-renames", "--numstat", "--format=%x01%ct%x02%ae", "-z"], { cwd }), runCommand(["git", "rev-parse", "--show-prefix"], { cwd })]);
1467
+ if (log.code !== 0 || top.code !== 0)
1314
1468
  return;
1469
+ const prefix = top.text.trim();
1315
1470
  const churn = new Map;
1471
+ const authors = new Map;
1316
1472
  for (const commit of log.text.split("\x01").slice(1)) {
1317
- const [stamp = "", ...names] = commit.split("\x00");
1318
- const paths = names.map((name) => name.replace(LEADING_NEWLINE, "")).filter((name) => name !== "");
1319
- if (paths.length > bulk)
1473
+ const [head = "", ...entries] = commit.split("\x00");
1474
+ const [stamp = "", author = ""] = head.split("\x02");
1475
+ const all = entries.map((entry) => entry.replace(LEADING_NEWLINE, "")).filter((entry) => entry !== "").map((entry) => {
1476
+ const [added = "", deleted = "", ...path] = entry.split("\t");
1477
+ return { path: path.join("\t"), lines: (Number(added) || 0) + (Number(deleted) || 0) };
1478
+ });
1479
+ if (all.length > bulk)
1320
1480
  continue;
1481
+ const paths = all.filter(({ path }) => path.startsWith(prefix)).map(({ path, lines }) => ({ path: path.slice(prefix.length), lines }));
1321
1482
  const age = Math.max(0, now - Number(stamp) * 1000);
1322
1483
  const weight = halfLifeMs === 0 ? 1 : 0.5 ** (age / halfLifeMs);
1323
- for (const path of paths) {
1324
- const seen = churn.get(path) ?? { commits: 0, weight: 0 };
1325
- churn.set(path, { commits: seen.commits + 1, weight: seen.weight + weight });
1484
+ for (const { path, lines } of paths) {
1485
+ const seen = churn.get(path) ?? { commits: 0, weight: 0, lines: 0, linesWeight: 0, authors: 0 };
1486
+ churn.set(path, { commits: seen.commits + 1, weight: seen.weight + weight, lines: seen.lines + lines, linesWeight: seen.linesWeight + lines * weight, authors: 0 });
1487
+ authors.set(path, (authors.get(path) ?? new Set).add(author));
1326
1488
  }
1327
1489
  }
1490
+ for (const [path, seen] of churn)
1491
+ seen.authors = authors.get(path)?.size ?? 0;
1328
1492
  return churn;
1329
1493
  }
1330
1494
 
@@ -1427,27 +1591,27 @@ var DEFAULT_HALF_LIFE = "90d";
1427
1591
  var DEFAULT_COUNT = configuredNumber("hotspots", "limit", 20);
1428
1592
  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
1429
1593
 
1430
- 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.
1594
+ 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. --by-lines scores the lines changed instead of the commits. Each file also shows how many lines changed, its author count ("solo" when one author wrote every change) and its most complex declaration, found by indentation. Test files and generated or built files are left out unless --all.
1431
1595
 
1432
- 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.
1433
-
1434
- 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.`;
1596
+ 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.`;
1597
+ var EXITS = [[0, "it ranked the files"], [1, "no file has commits in the window"], [2, "a usage error or outside a git repository"]];
1435
1598
  var OPTIONS = {
1436
1599
  since: { type: "string", short: "s", description: `only count the commits since this date, as git reads it (${DEFAULT_SINCE})` },
1437
1600
  "half-life": { type: "string", description: `how long until a commit counts half as much (${DEFAULT_HALF_LIFE}), 0 for no decay` },
1438
1601
  bulk: { type: "string", description: `leave out the commits touching more files than this (${DEFAULT_BULK})` },
1439
1602
  ...limitOptions(DEFAULT_COUNT),
1440
1603
  all: { type: "boolean", short: "a", description: "keep test files and generated files" },
1441
- json: jsonOption("[{rank, path, score, churn, recent, complexity, worst, lines}], never cut unless --limit is given")
1604
+ "by-lines": { type: "boolean", description: "score complexity times the lines changed (decayed like the commits) instead of the commits" },
1605
+ json: jsonOption("[{rank, path, score, churn, recent, changed, authors, solo, complexity, worst, lines}], never cut unless --limit is given; changed counts the lines added and deleted, solo being true for a file one author edited")
1442
1606
  };
1443
1607
  var HOT = 0.66;
1444
1608
  var WARM = 0.33;
1445
1609
  async function hotspots(args) {
1446
- 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'] });
1610
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { exits: EXITS, positionals: ["[dir]"], replaces: "guessing which files are worth splitting first", examples: ["hotspots", 'hotspots src --since "3 months ago" --limit 10'] });
1447
1611
  if (positionals.length > 1)
1448
1612
  badUsage("give one folder");
1449
1613
  const count = limitOf(values, DEFAULT_COUNT);
1450
- const cwd = process14.cwd();
1614
+ const cwd = process16.cwd();
1451
1615
  const bulk = Number(values.bulk ?? DEFAULT_BULK);
1452
1616
  if (!Number.isInteger(bulk) || bulk < 1)
1453
1617
  badUsage(`--bulk takes a number of files, not ${values.bulk}`);
@@ -1465,7 +1629,7 @@ async function hotspots(args) {
1465
1629
  continue;
1466
1630
  const complexity = complexityOf(text);
1467
1631
  const worst = worstUnit(text, path);
1468
- 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(`
1632
+ ranked.push({ path, score: Math.round(complexity * (values["by-lines"] === true ? touched.linesWeight : touched.weight)), churn: touched.commits, recent: Math.round(touched.weight * 10) / 10, changed: touched.lines, authors: touched.authors, solo: touched.authors === 1, complexity, worst: worst === undefined ? undefined : { name: worst.name, line: worst.line, complexity: worst.complexity }, lines: text.split(`
1469
1633
  `).length - (text.endsWith(`
1470
1634
  `) ? 1 : 0) });
1471
1635
  }
@@ -1478,8 +1642,8 @@ async function hotspots(args) {
1478
1642
  printJson(shown);
1479
1643
  return 0;
1480
1644
  }
1481
- const colors = paint(process14.stdout);
1482
- const path = role("path", process14.stdout);
1645
+ const colors = paint(process16.stdout);
1646
+ const path = role("path", process16.stdout);
1483
1647
  const top = shown.reduce((highest, row) => Math.max(highest, row.score), 0);
1484
1648
  const heat = (score, text) => {
1485
1649
  if (top > 0 && score >= top * HOT)
@@ -1487,22 +1651,24 @@ async function hotspots(args) {
1487
1651
  return top > 0 && score >= top * WARM ? colors.yellow(text) : text;
1488
1652
  };
1489
1653
  printHeader("hotspots", `${basename(cwd)} \xB7 since ${values.since ?? DEFAULT_SINCE}`);
1490
- console.log(table([["rank", "score", "churn", "recent", "complexity", "lines", "file", "most complex declaration"], ...shown.map((row) => [colors.dim(String(row.rank)), heat(row.score, String(row.score)), ...[row.churn, row.recent, row.complexity, row.lines].map(String), fileLink(path(row.path), row.path, process14.stdout, cwd), row.worst === undefined ? "" : `${row.worst.name} (${row.worst.complexity}, line ${row.worst.line})`])], { header: true, align: ["right", "right", "right", "right", "right", "right", "left", "left"] }));
1654
+ console.log(table([["rank", "score", "churn", "recent", "changed", "authors", "complexity", "lines", "file", "most complex declaration"], ...shown.map((row) => [colors.dim(String(row.rank)), heat(row.score, String(row.score)), ...[row.churn, row.recent, row.changed].map(String), row.solo ? colors.dim("1 solo") : String(row.authors), ...[row.complexity, row.lines].map(String), fileLink(path(row.path), row.path, process16.stdout, cwd), row.worst === undefined ? "" : `${row.worst.name} (${row.worst.complexity}, line ${row.worst.line})`])], { header: true, align: ["right", "right", "right", "right", "right", "right", "right", "right", "left", "left"] }));
1491
1655
  if (footer !== undefined)
1492
1656
  console.log(footer);
1493
1657
  return 0;
1494
1658
  }
1495
1659
 
1496
1660
  // src/peek.ts
1497
- import { realpathSync as realpathSync2 } from "fs";
1498
- import { isAbsolute as isAbsolute2, join as join8, relative as relative2, resolve as resolve4, sep } from "path";
1499
- import process15 from "process";
1661
+ import { realpathSync as realpathSync3 } from "fs";
1662
+ import { isAbsolute as isAbsolute2, join as join8, relative as relative2, resolve as resolve5, sep } from "path";
1663
+ import process17 from "process";
1500
1664
 
1501
1665
  // src/source.ts
1502
1666
  var LOCATION = /^(?:\.\/)?([^\s:()]+)(?::(\d+)(?::\d+)?|\((\d+),\d+\))(?=[:\s)]|$)/;
1503
- var DECLARATION = /^(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:function\*?|class|interface|type|enum|const|let|var|namespace|module|def|func|fn|struct|trait|impl)\s/;
1504
- var MODIFIERS = /^(?:(?:public|private|protected|static|async|override|readonly|abstract|get|set|pub|fn|def|func)\s+)*/;
1505
- var MEMBER = /^(?:(?:public|private|protected|static|async|override|readonly|abstract|get|set|pub|fn|def|func)\s+)*[#\w$]+\s*(?:<[^>]*>\s*)?\(/;
1667
+ var DECLARATION = /^(?:(?:export|default|declare|abstract|async|pub(?:\([^)]*\))?|public|private|protected|internal|final|open|sealed|static|suspend)\s+)*(?:function\*?|class|interface|type|enum|const|let|var|namespace|module|def|func|fun|fn|struct|trait|impl)\s/;
1668
+ var MODIFIER_WORDS = String.raw`(?:public|private|protected|internal|final|open|sealed|static|async|suspend|override|readonly|abstract|get|set|pub(?:\([^)]*\))?|function|fn|def|func|fun)\s+`;
1669
+ var RETURN_TYPE = String.raw`(?:[\w$.]+(?:<[^>]*>)?(?:\[\])*\??\s+(?=[#\w$]+\s*(?:<[^>]*>\s*)?\())?`;
1670
+ var MODIFIERS = new RegExp(String.raw`^(?:(?:${MODIFIER_WORDS})+${RETURN_TYPE})?`);
1671
+ var MEMBER = new RegExp(String.raw`^(?:(?:${MODIFIER_WORDS})+${RETURN_TYPE})?[#\w$]+\s*(?:<[^>]*>\s*)?\(`);
1506
1672
  var RECEIVER = /^(?:\([^)]*\)\s*)?/;
1507
1673
  var STAR = /^\*?\s*/;
1508
1674
  var HOLDS_MEMBERS = /\b(?:class|interface|trait|impl|struct)\s/;
@@ -1632,7 +1798,7 @@ function outline(text, path) {
1632
1798
  if (indent === 0 && DECLARATION.test(text) && !LOCAL_BINDING.test(text)) {
1633
1799
  entries.push({ line: i + 1, depth: 0, text: signature(line) });
1634
1800
  memberIndent = HOLDS_MEMBERS.test(text) ? -1 : undefined;
1635
- } else if (indent === 0 && text !== "" && !text.startsWith("}") && !LEADING.test(text)) {
1801
+ } else if (indent === 0 && text !== "" && !text.startsWith("{") && !text.startsWith("}") && !LEADING.test(text)) {
1636
1802
  memberIndent = undefined;
1637
1803
  } else if (memberIndent !== undefined && indent > 0 && (memberIndent === -1 || indent === memberIndent) && MEMBER.test(text) && !CALL_KEYWORDS.test(text)) {
1638
1804
  memberIndent = indent;
@@ -1681,9 +1847,8 @@ peek --around <regex> [-C 3] [path...] the lines around each match, overlapping
1681
1847
  <output> | peek [-C 3] the lines around each path:line the output opens a line with (errs, rg -n, grep -n, tsc, linters)
1682
1848
  The paths default to the files git keeps here (.gitignore holds).
1683
1849
  --refs lists at most 100 lines and --around prints at most 20 spans, the count of the rest after them (--limit <n>, --full for all).
1684
- --json prints spans as [{path, from, to, lines}], --refs as [{path, line, text}] ({definitions, references} with --defs-first), --outline as [{path, line, depth, text}], the lines never cut and the rows never counted off unless --limit is given.
1685
-
1686
- Exits 0 when it printed something, 1 when nothing is found, a file cannot be read or a span starts past the end, 2 on a usage error or a path outside the repository.`;
1850
+ --json prints spans as [{path, from, to, lines}], --refs as [{path, line, text}] ({definitions, references} with --defs-first), --outline as [{path, line, depth, text}], the lines never cut and the rows never counted off unless --limit is given.`;
1851
+ var EXITS2 = [[0, "it printed something"], [1, "nothing is found, a file cannot be read or a span starts past the end"], [2, "a usage error or a path outside the repository"]];
1687
1852
  var REFS_LIMIT = 100;
1688
1853
  var AROUND_LIMIT = 20;
1689
1854
  var PARENT = `..${sep}`;
@@ -1704,13 +1869,13 @@ function cut(text) {
1704
1869
  return text.length > LONGEST_LINE ? `${text.slice(0, LONGEST_LINE - 1)}\u2026` : text;
1705
1870
  }
1706
1871
  async function readableRoot() {
1707
- const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process15.cwd() });
1708
- return realpathSync2(ran.code === 0 ? ran.text.trim() : process15.cwd());
1872
+ const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process17.cwd() });
1873
+ return realpathSync3(ran.code === 0 ? ran.text.trim() : process17.cwd());
1709
1874
  }
1710
1875
  async function isOutside(path) {
1711
1876
  let real;
1712
1877
  try {
1713
- real = realpathSync2(resolve4(process15.cwd(), path));
1878
+ real = realpathSync3(resolve5(process17.cwd(), path));
1714
1879
  } catch {
1715
1880
  return false;
1716
1881
  }
@@ -1724,7 +1889,7 @@ async function checkInside(path) {
1724
1889
  async function pipedSpans(text, context) {
1725
1890
  const spans = [];
1726
1891
  for (const [path, numbers] of locations(text)) {
1727
- const source = await isOutside(path) ? undefined : await readText(resolve4(process15.cwd(), path));
1892
+ const source = await isOutside(path) ? undefined : await readText(resolve5(process17.cwd(), path));
1728
1893
  if (source !== undefined)
1729
1894
  spans.push(...spansAround(path, source.replace(TRAILING_NEWLINE2, "").split(`
1730
1895
  `).length, numbers, context));
@@ -1733,7 +1898,7 @@ async function pipedSpans(text, context) {
1733
1898
  }
1734
1899
  async function textOf(path) {
1735
1900
  await checkInside(path);
1736
- const text = await readText(resolve4(process15.cwd(), path));
1901
+ const text = await readText(resolve5(process17.cwd(), path));
1737
1902
  if (text === undefined)
1738
1903
  fail(`cannot read ${path} (missing, binary or too large)`, 1);
1739
1904
  return text;
@@ -1791,8 +1956,8 @@ async function spanOf(target) {
1791
1956
  async function* sources(paths) {
1792
1957
  for (const path of paths)
1793
1958
  await checkInside(path);
1794
- for (const path of await listFiles(paths, process15.cwd())) {
1795
- const text = await readText(join8(process15.cwd(), path));
1959
+ for (const path of await listFiles(paths, process17.cwd())) {
1960
+ const text = await readText(join8(process17.cwd(), path));
1796
1961
  if (text !== undefined)
1797
1962
  yield { path, text };
1798
1963
  }
@@ -1816,7 +1981,7 @@ async function definitionsOf(symbols, paths) {
1816
1981
  return [...found.values()].flat();
1817
1982
  }
1818
1983
  async function peek(args) {
1819
- const { values, positionals } = parse(args, USAGE2, OPTIONS2, { positionals: ["[target...]"], replaces: "sed -n N,Mp, grep -n chains and whole-file reads", examples: [["peek src/a.ts:120-140 src/b.ts:1-40", "two spans in one call"], ["peek --def parseArgs src", "a whole declaration"]] });
1984
+ const { values, positionals } = parse(args, USAGE2, OPTIONS2, { exits: EXITS2, positionals: ["[target...]"], replaces: "sed -n N,Mp, grep -n chains and whole-file reads", examples: [["peek src/a.ts:120-140 src/b.ts:1-40", "two spans in one call"], ["peek --def parseArgs src", "a whole declaration"]] });
1820
1985
  const modes = [values.def?.length === 0 ? undefined : values.def, values.refs, values.outline, values.around].filter((mode) => mode !== undefined && mode !== false);
1821
1986
  const json = values.json === true;
1822
1987
  if (values["defs-first"] === true && values.refs === undefined)
@@ -1893,14 +2058,14 @@ async function peek(args) {
1893
2058
 
1894
2059
  // src/todo-scan.ts
1895
2060
  import { join as join9 } from "path";
1896
- import process16 from "process";
2061
+ import process18 from "process";
1897
2062
 
1898
2063
  // src/todo.ts
1899
- var COMMENT2 = /(?<![:\w/])\/\/|\/\*|<!--|(?:^|\s)(?:#|--)(?=\s)|^\s*\*(?=\s|$)/;
2064
+ var COMMENT = /(?<![:\w/])\/\/|\/\*|<!--|(?:^|\s)(?:#|--)(?=\s)|^\s*\*(?=\s|$)/;
1900
2065
  var MARKUP = /\.(?:md|mdx|markdown|html?|xml)$/i;
1901
2066
  var MARKUP_COMMENT = /<!--/;
1902
2067
  var CLOSERS = /\s*(?:\*\/|-->)\s*$/;
1903
- var MARKER = /^(?:@|\[)?(TODO|FIXME)\b/;
2068
+ var MARKER = /^(?:@|\[)?(TODO|FIXME|HACK|XXX)\b/;
1904
2069
  var QUOTES = ["'", '"', "`"];
1905
2070
  var ESCAPE2 = /\\./g;
1906
2071
  var AFTER_FIRST_LINE = /\n[\s\S]*/;
@@ -1909,9 +2074,43 @@ function isQuoted(line, index) {
1909
2074
  const before = line.slice(0, index).replaceAll(ESCAPE2, "");
1910
2075
  return QUOTES.some((quote) => before.split(quote).length % 2 === 0);
1911
2076
  }
2077
+ var BLAME_HEADER = /^[0-9a-f]{40} \d+ (\d+)/;
2078
+ var DAY_S = 86400;
2079
+ async function commitTimes(path, cwd) {
2080
+ const blamed = await runCommand(["git", "blame", "--porcelain", "--", path], { cwd });
2081
+ const times = new Map;
2082
+ if (blamed.code !== 0)
2083
+ return times;
2084
+ const bySha = new Map;
2085
+ let sha = "";
2086
+ let line = 0;
2087
+ for (const row of stdoutOf(blamed.chunks).split(`
2088
+ `)) {
2089
+ const header = BLAME_HEADER.exec(row);
2090
+ if (header !== null) {
2091
+ sha = row.slice(0, 40);
2092
+ line = Number(header[1]);
2093
+ } else if (row.startsWith("committer-time ")) {
2094
+ bySha.set(sha, Number(row.slice("committer-time ".length)));
2095
+ } else if (row.startsWith("\t")) {
2096
+ times.set(line, bySha.get(sha) ?? 0);
2097
+ }
2098
+ }
2099
+ return times;
2100
+ }
2101
+ async function addAges(marks, cwd, now = Date.now() / 1000) {
2102
+ await Promise.all([...Map.groupBy(marks, (mark) => mark.path)].map(async ([path, ofFile]) => {
2103
+ const times = await commitTimes(path, cwd);
2104
+ for (const mark of ofFile) {
2105
+ const time = times.get(mark.line);
2106
+ if (time !== undefined)
2107
+ mark.age = Math.max(0, Math.floor((now - time) / DAY_S));
2108
+ }
2109
+ }));
2110
+ }
1912
2111
  function marksIn(text, path) {
1913
2112
  const marks = [];
1914
- const comment = MARKUP.test(path) ? MARKUP_COMMENT : COMMENT2;
2113
+ const comment = MARKUP.test(path) ? MARKUP_COMMENT : COMMENT;
1915
2114
  for (const [i, line] of text.split(`
1916
2115
  `).entries()) {
1917
2116
  const opener = comment.exec(line);
@@ -1964,18 +2163,21 @@ async function lookUp(refs, cwd) {
1964
2163
  }
1965
2164
 
1966
2165
  // src/todo-scan.ts
1967
- var USAGE3 = `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
2166
+ var USAGE3 = `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
1968
2167
 
1969
- --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.
2168
+ --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.
1970
2169
 
1971
- 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.
2170
+ --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.
1972
2171
 
1973
- Exits 0 when it listed the comments or found no stale one, 1 when --stale finds one, 2 on a usage error or when --stale could not look a repository up (ft and gh both failed), so a clean exit never hides an unchecked issue.`;
2172
+ 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.`;
2173
+ var EXITS3 = [[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)"]];
1974
2174
  var LIST_LIMIT = 100;
2175
+ var DAY_MS3 = 86400000;
1975
2176
  var OPTIONS3 = {
1976
2177
  stale: { type: "boolean", description: "only the comments naming a closed issue, looked up with ft or gh" },
2178
+ older: { type: "string", description: "only the comments whose line last changed longer ago than this duration, from git blame" },
1977
2179
  ...limitOptions(LIST_LIMIT),
1978
- json: jsonOption("[{path, line, kind, text, refs: [{repo, number, state?}]}]")
2180
+ 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")
1979
2181
  };
1980
2182
  function printLines(lines, footer) {
1981
2183
  const all = [...lines, ...footer === undefined ? [] : [footer]];
@@ -1984,21 +2186,28 @@ function printLines(lines, footer) {
1984
2186
  `));
1985
2187
  }
1986
2188
  async function todoScan(args) {
1987
- const { values, positionals } = parse(args, USAGE3, OPTIONS3, { 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"]] });
1988
- const cwd = process16.cwd();
2189
+ const { values, positionals } = parse(args, USAGE3, OPTIONS3, { exits: EXITS3, 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"]] });
2190
+ const cwd = process18.cwd();
1989
2191
  const limit = limitOf(values, LIST_LIMIT);
1990
- const marks = [];
2192
+ const found = [];
1991
2193
  for (const path of await listFiles(positionals, cwd)) {
1992
2194
  const text = await readText(join9(cwd, path));
1993
2195
  if (text !== undefined)
1994
- marks.push(...marksIn(text, path));
1995
- }
2196
+ found.push(...marksIn(text, path));
2197
+ }
2198
+ const older = values.older === undefined ? undefined : duration(values.older, "older", 0, "m") / DAY_MS3;
2199
+ let marks = found;
2200
+ if (older !== undefined || values.json === true)
2201
+ await addAges(found, cwd);
2202
+ const ageNote = (mark) => older === undefined || mark.age === undefined ? "" : ` [${mark.age}d]`;
2203
+ if (older !== undefined)
2204
+ marks = found.filter((mark) => mark.age !== undefined && mark.age >= older);
1996
2205
  if (values.stale !== true) {
1997
2206
  const { shown, footer } = capped(marks, limit);
1998
2207
  if (values.json === true)
1999
2208
  printJson(shown);
2000
2209
  else
2001
- printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.text}`), footer);
2210
+ printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.text}${ageNote(mark)}`), footer);
2002
2211
  return 0;
2003
2212
  }
2004
2213
  const { states, failed } = await lookUp(marks.flatMap((mark) => mark.refs), cwd);
@@ -2009,14 +2218,14 @@ async function todoScan(args) {
2009
2218
  if (values.json === true)
2010
2219
  printJson(shown.map((mark) => ({ ...mark, refs: mark.refs.map((ref) => ({ ...ref, state: states.get(refKey(ref)) })) })));
2011
2220
  else
2012
- printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.refs.filter((ref) => states.get(refKey(ref)) === "closed").map(refKey).join(", ")} closed: ${mark.text}`), footer);
2221
+ 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);
2013
2222
  if (stale.length > 0)
2014
2223
  return 1;
2015
2224
  return failed.size > 0 ? 2 : 0;
2016
2225
  }
2017
2226
 
2018
2227
  // src/cli.ts
2019
- process17.exitCode = await runCli({
2228
+ process19.exitCode = await runCli({
2020
2229
  name: "src",
2021
2230
  about: "reads and ranks the source of a folder: line spans, TODO comments and the files worth splitting",
2022
2231
  replaces: "sed -n N,Mp, grep -n chains and grep -rn TODO",