@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.
- package/dist/cli.js +174 -66
- package/dist/hotspots-cli.js +103 -42
- package/dist/peek-cli.js +87 -34
- package/dist/todo-scan-cli.js +127 -31
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// @bun
|
|
3
3
|
|
|
4
4
|
// src/cli.ts
|
|
5
|
-
import
|
|
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,7 +499,7 @@ function printJson(value) {
|
|
|
482
499
|
|
|
483
500
|
// ../kit/src/help.ts
|
|
484
501
|
import process8 from "process";
|
|
485
|
-
var OPTIONAL =
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
540
|
-
|
|
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,
|
|
543
|
-
|
|
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[
|
|
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
|
|
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
|
|
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 =
|
|
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 =
|
|
991
|
+
function usagePath(env = process13.env) {
|
|
946
992
|
return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
|
|
947
993
|
}
|
|
948
|
-
function usageRecorded(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 =
|
|
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(
|
|
1053
|
-
const styled = takesControlCodes(
|
|
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]),
|
|
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]),
|
|
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,
|
|
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/hotspots.ts
|
|
1313
1364
|
import { basename, join as join7 } from "path";
|
|
1314
|
-
import
|
|
1365
|
+
import process16 from "process";
|
|
1315
1366
|
|
|
1316
1367
|
// src/churn.ts
|
|
1317
1368
|
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)$/;
|
|
@@ -1319,9 +1370,8 @@ var TESTS = /(?:^|\/)(?:tests?|__tests__|spec|e2e|__mocks__|fixtures)\/|\.(?:tes
|
|
|
1319
1370
|
var GENERATED = /(?:^|\/)(?:dist|build|out|generated|\.nuxt|\.output|\.next)\/|\.min\.[cm]?js$|\.d\.ts$|\.(?:generated|gen)\.[^/]+$|\.pb\.go$|\.snap$/;
|
|
1320
1371
|
var LEADING_NEWLINE = /^\n/;
|
|
1321
1372
|
var GENERATED_HEADER = /@generated|generated by|do not edit/i;
|
|
1322
|
-
var DECISION = /\b(?:if|elif|elsif|for|foreach|while|until|case|when|catch|except|rescue|match|guard|and|or)\b
|
|
1323
|
-
var
|
|
1324
|
-
var STRING = /'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`/g;
|
|
1373
|
+
var DECISION = /\b(?:if|elif|elsif|for|foreach|while|until|case|when|catch|except|rescue|match|guard|and|or)\b|&&|\|\||\?\?|\s\?(?![,):.?])/g;
|
|
1374
|
+
var COMMENT_OR_STRING = /(\/\*[\s\S]*?\*\/|\/\/[^\n]*|^[ \t]*#[^\n]*)|'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`/gm;
|
|
1325
1375
|
function isCandidate(path) {
|
|
1326
1376
|
return SOURCE.test(path) && !TESTS.test(path) && !GENERATED.test(path);
|
|
1327
1377
|
}
|
|
@@ -1329,25 +1379,35 @@ function isGenerated(text) {
|
|
|
1329
1379
|
return GENERATED_HEADER.test(text.slice(0, 400));
|
|
1330
1380
|
}
|
|
1331
1381
|
function complexityOf(text) {
|
|
1332
|
-
return 1 + (text.replace(
|
|
1382
|
+
return 1 + (text.replace(COMMENT_OR_STRING, (_, comment) => comment === undefined ? '""' : "").match(DECISION)?.length ?? 0);
|
|
1333
1383
|
}
|
|
1334
1384
|
async function churnSince(cwd, since, { bulk, halfLifeMs, now = Date.now() }) {
|
|
1335
|
-
const log = await runCommand(["git", "log", `--since=${since}`, "--no-renames", "--
|
|
1336
|
-
if (log.code !== 0)
|
|
1385
|
+
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 })]);
|
|
1386
|
+
if (log.code !== 0 || top.code !== 0)
|
|
1337
1387
|
return;
|
|
1388
|
+
const prefix = top.text.trim();
|
|
1338
1389
|
const churn = new Map;
|
|
1390
|
+
const authors = new Map;
|
|
1339
1391
|
for (const commit of log.text.split("\x01").slice(1)) {
|
|
1340
|
-
const [
|
|
1341
|
-
const
|
|
1342
|
-
|
|
1392
|
+
const [head = "", ...entries] = commit.split("\x00");
|
|
1393
|
+
const [stamp = "", author = ""] = head.split("\x02");
|
|
1394
|
+
const all = entries.map((entry) => entry.replace(LEADING_NEWLINE, "")).filter((entry) => entry !== "").map((entry) => {
|
|
1395
|
+
const [added = "", deleted = "", ...path] = entry.split("\t");
|
|
1396
|
+
return { path: path.join("\t"), lines: (Number(added) || 0) + (Number(deleted) || 0) };
|
|
1397
|
+
});
|
|
1398
|
+
if (all.length > bulk)
|
|
1343
1399
|
continue;
|
|
1400
|
+
const paths = all.filter(({ path }) => path.startsWith(prefix)).map(({ path, lines }) => ({ path: path.slice(prefix.length), lines }));
|
|
1344
1401
|
const age = Math.max(0, now - Number(stamp) * 1000);
|
|
1345
1402
|
const weight = halfLifeMs === 0 ? 1 : 0.5 ** (age / halfLifeMs);
|
|
1346
|
-
for (const path of paths) {
|
|
1347
|
-
const seen = churn.get(path) ?? { commits: 0, weight: 0 };
|
|
1348
|
-
churn.set(path, { commits: seen.commits + 1, weight: seen.weight + weight });
|
|
1403
|
+
for (const { path, lines } of paths) {
|
|
1404
|
+
const seen = churn.get(path) ?? { commits: 0, weight: 0, lines: 0, linesWeight: 0, authors: 0 };
|
|
1405
|
+
churn.set(path, { commits: seen.commits + 1, weight: seen.weight + weight, lines: seen.lines + lines, linesWeight: seen.linesWeight + lines * weight, authors: 0 });
|
|
1406
|
+
authors.set(path, (authors.get(path) ?? new Set).add(author));
|
|
1349
1407
|
}
|
|
1350
1408
|
}
|
|
1409
|
+
for (const [path, seen] of churn)
|
|
1410
|
+
seen.authors = authors.get(path)?.size ?? 0;
|
|
1351
1411
|
return churn;
|
|
1352
1412
|
}
|
|
1353
1413
|
|
|
@@ -1450,7 +1510,7 @@ var DEFAULT_HALF_LIFE = "90d";
|
|
|
1450
1510
|
var DEFAULT_COUNT = configuredNumber("hotspots", "limit", 20);
|
|
1451
1511
|
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
|
|
1452
1512
|
|
|
1453
|
-
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.
|
|
1513
|
+
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.
|
|
1454
1514
|
|
|
1455
1515
|
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.`;
|
|
1456
1516
|
var EXITS = [[0, "it ranked the files"], [1, "no file has commits in the window"], [2, "a usage error or outside a git repository"]];
|
|
@@ -1460,7 +1520,8 @@ var OPTIONS = {
|
|
|
1460
1520
|
bulk: { type: "string", description: `leave out the commits touching more files than this (${DEFAULT_BULK})` },
|
|
1461
1521
|
...limitOptions(DEFAULT_COUNT),
|
|
1462
1522
|
all: { type: "boolean", short: "a", description: "keep test files and generated files" },
|
|
1463
|
-
|
|
1523
|
+
"by-lines": { type: "boolean", description: "score complexity times the lines changed (decayed like the commits) instead of the commits" },
|
|
1524
|
+
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")
|
|
1464
1525
|
};
|
|
1465
1526
|
var HOT = 0.66;
|
|
1466
1527
|
var WARM = 0.33;
|
|
@@ -1469,7 +1530,7 @@ async function hotspots(args) {
|
|
|
1469
1530
|
if (positionals.length > 1)
|
|
1470
1531
|
badUsage("give one folder");
|
|
1471
1532
|
const count = limitOf(values, DEFAULT_COUNT);
|
|
1472
|
-
const cwd =
|
|
1533
|
+
const cwd = process16.cwd();
|
|
1473
1534
|
const bulk = Number(values.bulk ?? DEFAULT_BULK);
|
|
1474
1535
|
if (!Number.isInteger(bulk) || bulk < 1)
|
|
1475
1536
|
badUsage(`--bulk takes a number of files, not ${values.bulk}`);
|
|
@@ -1487,7 +1548,7 @@ async function hotspots(args) {
|
|
|
1487
1548
|
continue;
|
|
1488
1549
|
const complexity = complexityOf(text);
|
|
1489
1550
|
const worst = worstUnit(text, path);
|
|
1490
|
-
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(`
|
|
1551
|
+
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(`
|
|
1491
1552
|
`).length - (text.endsWith(`
|
|
1492
1553
|
`) ? 1 : 0) });
|
|
1493
1554
|
}
|
|
@@ -1500,8 +1561,8 @@ async function hotspots(args) {
|
|
|
1500
1561
|
printJson(shown);
|
|
1501
1562
|
return 0;
|
|
1502
1563
|
}
|
|
1503
|
-
const colors = paint(
|
|
1504
|
-
const path = role("path",
|
|
1564
|
+
const colors = paint(process16.stdout);
|
|
1565
|
+
const path = role("path", process16.stdout);
|
|
1505
1566
|
const top = shown.reduce((highest, row) => Math.max(highest, row.score), 0);
|
|
1506
1567
|
const heat = (score, text) => {
|
|
1507
1568
|
if (top > 0 && score >= top * HOT)
|
|
@@ -1509,7 +1570,7 @@ async function hotspots(args) {
|
|
|
1509
1570
|
return top > 0 && score >= top * WARM ? colors.yellow(text) : text;
|
|
1510
1571
|
};
|
|
1511
1572
|
printHeader("hotspots", `${basename(cwd)} \xB7 since ${values.since ?? DEFAULT_SINCE}`);
|
|
1512
|
-
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,
|
|
1573
|
+
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"] }));
|
|
1513
1574
|
if (footer !== undefined)
|
|
1514
1575
|
console.log(footer);
|
|
1515
1576
|
return 0;
|
|
@@ -1518,13 +1579,15 @@ async function hotspots(args) {
|
|
|
1518
1579
|
// src/peek.ts
|
|
1519
1580
|
import { realpathSync as realpathSync3 } from "fs";
|
|
1520
1581
|
import { isAbsolute as isAbsolute2, join as join8, relative as relative2, resolve as resolve5, sep } from "path";
|
|
1521
|
-
import
|
|
1582
|
+
import process17 from "process";
|
|
1522
1583
|
|
|
1523
1584
|
// src/source.ts
|
|
1524
1585
|
var LOCATION = /^(?:\.\/)?([^\s:()]+)(?::(\d+)(?::\d+)?|\((\d+),\d+\))(?=[:\s)]|$)/;
|
|
1525
|
-
var DECLARATION = /^(?:
|
|
1526
|
-
var
|
|
1527
|
-
var
|
|
1586
|
+
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/;
|
|
1587
|
+
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+`;
|
|
1588
|
+
var RETURN_TYPE = String.raw`(?:[\w$.]+(?:<[^>]*>)?(?:\[\])*\??\s+(?=[#\w$]+\s*(?:<[^>]*>\s*)?\())?`;
|
|
1589
|
+
var MODIFIERS = new RegExp(String.raw`^(?:(?:${MODIFIER_WORDS})+${RETURN_TYPE})?`);
|
|
1590
|
+
var MEMBER = new RegExp(String.raw`^(?:(?:${MODIFIER_WORDS})+${RETURN_TYPE})?[#\w$]+\s*(?:<[^>]*>\s*)?\(`);
|
|
1528
1591
|
var RECEIVER = /^(?:\([^)]*\)\s*)?/;
|
|
1529
1592
|
var STAR = /^\*?\s*/;
|
|
1530
1593
|
var HOLDS_MEMBERS = /\b(?:class|interface|trait|impl|struct)\s/;
|
|
@@ -1654,7 +1717,7 @@ function outline(text, path) {
|
|
|
1654
1717
|
if (indent === 0 && DECLARATION.test(text) && !LOCAL_BINDING.test(text)) {
|
|
1655
1718
|
entries.push({ line: i + 1, depth: 0, text: signature(line) });
|
|
1656
1719
|
memberIndent = HOLDS_MEMBERS.test(text) ? -1 : undefined;
|
|
1657
|
-
} else if (indent === 0 && text !== "" && !text.startsWith("}") && !LEADING.test(text)) {
|
|
1720
|
+
} else if (indent === 0 && text !== "" && !text.startsWith("{") && !text.startsWith("}") && !LEADING.test(text)) {
|
|
1658
1721
|
memberIndent = undefined;
|
|
1659
1722
|
} else if (memberIndent !== undefined && indent > 0 && (memberIndent === -1 || indent === memberIndent) && MEMBER.test(text) && !CALL_KEYWORDS.test(text)) {
|
|
1660
1723
|
memberIndent = indent;
|
|
@@ -1725,13 +1788,13 @@ function cut(text) {
|
|
|
1725
1788
|
return text.length > LONGEST_LINE ? `${text.slice(0, LONGEST_LINE - 1)}\u2026` : text;
|
|
1726
1789
|
}
|
|
1727
1790
|
async function readableRoot() {
|
|
1728
|
-
const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd:
|
|
1729
|
-
return realpathSync3(ran.code === 0 ? ran.text.trim() :
|
|
1791
|
+
const ran = await runCommand(["git", "rev-parse", "--show-toplevel"], { cwd: process17.cwd() });
|
|
1792
|
+
return realpathSync3(ran.code === 0 ? ran.text.trim() : process17.cwd());
|
|
1730
1793
|
}
|
|
1731
1794
|
async function isOutside(path) {
|
|
1732
1795
|
let real;
|
|
1733
1796
|
try {
|
|
1734
|
-
real = realpathSync3(resolve5(
|
|
1797
|
+
real = realpathSync3(resolve5(process17.cwd(), path));
|
|
1735
1798
|
} catch {
|
|
1736
1799
|
return false;
|
|
1737
1800
|
}
|
|
@@ -1745,7 +1808,7 @@ async function checkInside(path) {
|
|
|
1745
1808
|
async function pipedSpans(text, context) {
|
|
1746
1809
|
const spans = [];
|
|
1747
1810
|
for (const [path, numbers] of locations(text)) {
|
|
1748
|
-
const source = await isOutside(path) ? undefined : await readText(resolve5(
|
|
1811
|
+
const source = await isOutside(path) ? undefined : await readText(resolve5(process17.cwd(), path));
|
|
1749
1812
|
if (source !== undefined)
|
|
1750
1813
|
spans.push(...spansAround(path, source.replace(TRAILING_NEWLINE2, "").split(`
|
|
1751
1814
|
`).length, numbers, context));
|
|
@@ -1754,7 +1817,7 @@ async function pipedSpans(text, context) {
|
|
|
1754
1817
|
}
|
|
1755
1818
|
async function textOf(path) {
|
|
1756
1819
|
await checkInside(path);
|
|
1757
|
-
const text = await readText(resolve5(
|
|
1820
|
+
const text = await readText(resolve5(process17.cwd(), path));
|
|
1758
1821
|
if (text === undefined)
|
|
1759
1822
|
fail(`cannot read ${path} (missing, binary or too large)`, 1);
|
|
1760
1823
|
return text;
|
|
@@ -1812,8 +1875,8 @@ async function spanOf(target) {
|
|
|
1812
1875
|
async function* sources(paths) {
|
|
1813
1876
|
for (const path of paths)
|
|
1814
1877
|
await checkInside(path);
|
|
1815
|
-
for (const path of await listFiles(paths,
|
|
1816
|
-
const text = await readText(join8(
|
|
1878
|
+
for (const path of await listFiles(paths, process17.cwd())) {
|
|
1879
|
+
const text = await readText(join8(process17.cwd(), path));
|
|
1817
1880
|
if (text !== undefined)
|
|
1818
1881
|
yield { path, text };
|
|
1819
1882
|
}
|
|
@@ -1914,14 +1977,14 @@ async function peek(args) {
|
|
|
1914
1977
|
|
|
1915
1978
|
// src/todo-scan.ts
|
|
1916
1979
|
import { join as join9 } from "path";
|
|
1917
|
-
import
|
|
1980
|
+
import process18 from "process";
|
|
1918
1981
|
|
|
1919
1982
|
// src/todo.ts
|
|
1920
|
-
var
|
|
1983
|
+
var COMMENT = /(?<![:\w/])\/\/|\/\*|<!--|(?:^|\s)(?:#|--)(?=\s)|^\s*\*(?=\s|$)/;
|
|
1921
1984
|
var MARKUP = /\.(?:md|mdx|markdown|html?|xml)$/i;
|
|
1922
1985
|
var MARKUP_COMMENT = /<!--/;
|
|
1923
1986
|
var CLOSERS = /\s*(?:\*\/|-->)\s*$/;
|
|
1924
|
-
var MARKER = /^(?:@|\[)?(TODO|FIXME)\b/;
|
|
1987
|
+
var MARKER = /^(?:@|\[)?(TODO|FIXME|HACK|XXX)\b/;
|
|
1925
1988
|
var QUOTES = ["'", '"', "`"];
|
|
1926
1989
|
var ESCAPE2 = /\\./g;
|
|
1927
1990
|
var AFTER_FIRST_LINE = /\n[\s\S]*/;
|
|
@@ -1930,9 +1993,43 @@ function isQuoted(line, index) {
|
|
|
1930
1993
|
const before = line.slice(0, index).replaceAll(ESCAPE2, "");
|
|
1931
1994
|
return QUOTES.some((quote) => before.split(quote).length % 2 === 0);
|
|
1932
1995
|
}
|
|
1996
|
+
var BLAME_HEADER = /^[0-9a-f]{40} \d+ (\d+)/;
|
|
1997
|
+
var DAY_S = 86400;
|
|
1998
|
+
async function commitTimes(path, cwd) {
|
|
1999
|
+
const blamed = await runCommand(["git", "blame", "--porcelain", "--", path], { cwd });
|
|
2000
|
+
const times = new Map;
|
|
2001
|
+
if (blamed.code !== 0)
|
|
2002
|
+
return times;
|
|
2003
|
+
const bySha = new Map;
|
|
2004
|
+
let sha = "";
|
|
2005
|
+
let line = 0;
|
|
2006
|
+
for (const row of stdoutOf(blamed.chunks).split(`
|
|
2007
|
+
`)) {
|
|
2008
|
+
const header = BLAME_HEADER.exec(row);
|
|
2009
|
+
if (header !== null) {
|
|
2010
|
+
sha = row.slice(0, 40);
|
|
2011
|
+
line = Number(header[1]);
|
|
2012
|
+
} else if (row.startsWith("committer-time ")) {
|
|
2013
|
+
bySha.set(sha, Number(row.slice("committer-time ".length)));
|
|
2014
|
+
} else if (row.startsWith("\t")) {
|
|
2015
|
+
times.set(line, bySha.get(sha) ?? 0);
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
return times;
|
|
2019
|
+
}
|
|
2020
|
+
async function addAges(marks, cwd, now = Date.now() / 1000) {
|
|
2021
|
+
await Promise.all([...Map.groupBy(marks, (mark) => mark.path)].map(async ([path, ofFile]) => {
|
|
2022
|
+
const times = await commitTimes(path, cwd);
|
|
2023
|
+
for (const mark of ofFile) {
|
|
2024
|
+
const time = times.get(mark.line);
|
|
2025
|
+
if (time !== undefined)
|
|
2026
|
+
mark.age = Math.max(0, Math.floor((now - time) / DAY_S));
|
|
2027
|
+
}
|
|
2028
|
+
}));
|
|
2029
|
+
}
|
|
1933
2030
|
function marksIn(text, path) {
|
|
1934
2031
|
const marks = [];
|
|
1935
|
-
const comment = MARKUP.test(path) ? MARKUP_COMMENT :
|
|
2032
|
+
const comment = MARKUP.test(path) ? MARKUP_COMMENT : COMMENT;
|
|
1936
2033
|
for (const [i, line] of text.split(`
|
|
1937
2034
|
`).entries()) {
|
|
1938
2035
|
const opener = comment.exec(line);
|
|
@@ -1985,17 +2082,21 @@ async function lookUp(refs, cwd) {
|
|
|
1985
2082
|
}
|
|
1986
2083
|
|
|
1987
2084
|
// src/todo-scan.ts
|
|
1988
|
-
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
|
|
2085
|
+
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
|
|
2086
|
+
|
|
2087
|
+
--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.
|
|
1989
2088
|
|
|
1990
2089
|
--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.
|
|
1991
2090
|
|
|
1992
2091
|
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.`;
|
|
1993
2092
|
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)"]];
|
|
1994
2093
|
var LIST_LIMIT = 100;
|
|
2094
|
+
var DAY_MS3 = 86400000;
|
|
1995
2095
|
var OPTIONS3 = {
|
|
1996
2096
|
stale: { type: "boolean", description: "only the comments naming a closed issue, looked up with ft or gh" },
|
|
2097
|
+
older: { type: "string", description: "only the comments whose line last changed longer ago than this duration, from git blame" },
|
|
1997
2098
|
...limitOptions(LIST_LIMIT),
|
|
1998
|
-
json: jsonOption("[{path, line, kind, text, refs: [{repo, number, state?}]}]")
|
|
2099
|
+
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")
|
|
1999
2100
|
};
|
|
2000
2101
|
function printLines(lines, footer) {
|
|
2001
2102
|
const all = [...lines, ...footer === undefined ? [] : [footer]];
|
|
@@ -2005,20 +2106,27 @@ function printLines(lines, footer) {
|
|
|
2005
2106
|
}
|
|
2006
2107
|
async function todoScan(args) {
|
|
2007
2108
|
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"]] });
|
|
2008
|
-
const cwd =
|
|
2109
|
+
const cwd = process18.cwd();
|
|
2009
2110
|
const limit = limitOf(values, LIST_LIMIT);
|
|
2010
|
-
const
|
|
2111
|
+
const found = [];
|
|
2011
2112
|
for (const path of await listFiles(positionals, cwd)) {
|
|
2012
2113
|
const text = await readText(join9(cwd, path));
|
|
2013
2114
|
if (text !== undefined)
|
|
2014
|
-
|
|
2015
|
-
}
|
|
2115
|
+
found.push(...marksIn(text, path));
|
|
2116
|
+
}
|
|
2117
|
+
const older = values.older === undefined ? undefined : duration(values.older, "older", 0, "m") / DAY_MS3;
|
|
2118
|
+
let marks = found;
|
|
2119
|
+
if (older !== undefined || values.json === true)
|
|
2120
|
+
await addAges(found, cwd);
|
|
2121
|
+
const ageNote = (mark) => older === undefined || mark.age === undefined ? "" : ` [${mark.age}d]`;
|
|
2122
|
+
if (older !== undefined)
|
|
2123
|
+
marks = found.filter((mark) => mark.age !== undefined && mark.age >= older);
|
|
2016
2124
|
if (values.stale !== true) {
|
|
2017
2125
|
const { shown, footer } = capped(marks, limit);
|
|
2018
2126
|
if (values.json === true)
|
|
2019
2127
|
printJson(shown);
|
|
2020
2128
|
else
|
|
2021
|
-
printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.text}`), footer);
|
|
2129
|
+
printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.text}${ageNote(mark)}`), footer);
|
|
2022
2130
|
return 0;
|
|
2023
2131
|
}
|
|
2024
2132
|
const { states, failed } = await lookUp(marks.flatMap((mark) => mark.refs), cwd);
|
|
@@ -2029,14 +2137,14 @@ async function todoScan(args) {
|
|
|
2029
2137
|
if (values.json === true)
|
|
2030
2138
|
printJson(shown.map((mark) => ({ ...mark, refs: mark.refs.map((ref) => ({ ...ref, state: states.get(refKey(ref)) })) })));
|
|
2031
2139
|
else
|
|
2032
|
-
printLines(shown.map((mark) => `${mark.path}:${mark.line}: ${mark.refs.filter((ref) => states.get(refKey(ref)) === "closed").map(refKey).join(", ")} closed: ${mark.text}`), footer);
|
|
2140
|
+
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);
|
|
2033
2141
|
if (stale.length > 0)
|
|
2034
2142
|
return 1;
|
|
2035
2143
|
return failed.size > 0 ? 2 : 0;
|
|
2036
2144
|
}
|
|
2037
2145
|
|
|
2038
2146
|
// src/cli.ts
|
|
2039
|
-
|
|
2147
|
+
process19.exitCode = await runCli({
|
|
2040
2148
|
name: "src",
|
|
2041
2149
|
about: "reads and ranks the source of a folder: line spans, TODO comments and the files worth splitting",
|
|
2042
2150
|
replaces: "sed -n N,Mp, grep -n chains and grep -rn TODO",
|