dir-analysis-tool 3.5.7 → 3.6.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.
@@ -4,7 +4,7 @@ import { close, existsSync, open, read } from "node:fs";
4
4
  import { lstat, open as open$1, readFile, readdir, stat } from "node:fs/promises";
5
5
  import { availableParallelism } from "node:os";
6
6
  import { Worker } from "node:worker_threads";
7
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
8
  // src/errors.ts
9
9
  /**
10
10
  * An expected, user-facing failure (bad input, missing directory, invalid
@@ -1028,6 +1028,77 @@ function joinRelative(root, relative) {
1028
1028
  return root.endsWith(sep) ? root + native : root + sep + native;
1029
1029
  }
1030
1030
  const IS_WINDOWS = process.platform === "win32";
1031
+ const STAT_FIELDS = [
1032
+ "size",
1033
+ "blocks",
1034
+ "mtimeMs",
1035
+ "ctimeMs",
1036
+ "dev",
1037
+ "ino",
1038
+ "nlink"
1039
+ ];
1040
+ /**
1041
+ * Files that several paths may lead to, by `dev:ino`, each under the path
1042
+ * chosen so far. A tree full of hard links can hold one of these per file
1043
+ * until the walk ends, so the stats sit in one flat array instead of an
1044
+ * object each.
1045
+ */
1046
+ var LinkedFiles = class {
1047
+ #slots = /* @__PURE__ */ new Map();
1048
+ #dirs = [];
1049
+ #names = [];
1050
+ #viaSymlink = [];
1051
+ #stats = new Float64Array(STAT_FIELDS.length * 64);
1052
+ slot(key) {
1053
+ return this.#slots.get(key);
1054
+ }
1055
+ add(key, dir, name, stats, viaSymlink) {
1056
+ const slot = this.#dirs.length;
1057
+ this.#slots.set(key, slot);
1058
+ if ((slot + 1) * STAT_FIELDS.length > this.#stats.length) {
1059
+ const grown = new Float64Array(this.#stats.length * 2);
1060
+ grown.set(this.#stats);
1061
+ this.#stats = grown;
1062
+ }
1063
+ this.#dirs.push(dir);
1064
+ this.#names.push(name);
1065
+ this.#viaSymlink.push(viaSymlink);
1066
+ this.set(slot, dir, name, stats, viaSymlink);
1067
+ }
1068
+ set(slot, dir, name, stats, viaSymlink) {
1069
+ this.#dirs[slot] = dir;
1070
+ this.#names[slot] = name;
1071
+ this.#viaSymlink[slot] = viaSymlink;
1072
+ const at = slot * STAT_FIELDS.length;
1073
+ for (let i = 0; i < STAT_FIELDS.length; i++) this.#stats[at + i] = stats[STAT_FIELDS[i]];
1074
+ }
1075
+ dir(slot) {
1076
+ return this.#dirs[slot];
1077
+ }
1078
+ name(slot) {
1079
+ return this.#names[slot];
1080
+ }
1081
+ viaSymlink(slot) {
1082
+ return this.#viaSymlink[slot];
1083
+ }
1084
+ stats(slot) {
1085
+ const at = slot * STAT_FIELDS.length;
1086
+ const v = this.#stats;
1087
+ return {
1088
+ size: v[at],
1089
+ blocks: v[at + 1],
1090
+ mtimeMs: v[at + 2],
1091
+ ctimeMs: v[at + 3],
1092
+ dev: v[at + 4],
1093
+ ino: v[at + 5],
1094
+ nlink: v[at + 6]
1095
+ };
1096
+ }
1097
+ /** Each key with its slot, in the order the keys were added. */
1098
+ entries() {
1099
+ return this.#slots.entries();
1100
+ }
1101
+ };
1031
1102
  /**
1032
1103
  * Concurrent directory walker.
1033
1104
  *
@@ -1055,10 +1126,18 @@ var Scanner = class {
1055
1126
  #visitor;
1056
1127
  #limiter;
1057
1128
  #filtersActive;
1058
- /** `dev:ino` of files with several links (or of every file when following symlinks). */
1129
+ /** `dev:ino` of files counted as they were found: every one-link file when following symlinks. */
1059
1130
  #seenInodes = /* @__PURE__ */ new Set();
1060
1131
  /** `dev:ino` of entered directories, tracked only when following symlinks. */
1061
1132
  #seenDirs = /* @__PURE__ */ new Set();
1133
+ /**
1134
+ * Files that more than one path may lead to (several hard links, or a
1135
+ * followed symlink), by `dev:ino`: the path chosen so far. They are counted
1136
+ * after the walk, so the choice never depends on which path came first.
1137
+ */
1138
+ #linkedFiles = new LinkedFiles();
1139
+ /** Directories reached through a followed symlink, entered after the walk. */
1140
+ #linkedDirs = [];
1062
1141
  constructor(options, visitor) {
1063
1142
  this.#options = options;
1064
1143
  this.#visitor = visitor;
@@ -1066,17 +1145,24 @@ var Scanner = class {
1066
1145
  this.#filtersActive = options.minSize > 0 || options.maxSize < Infinity || options.modifiedAfter > -Infinity || options.modifiedBefore < Infinity;
1067
1146
  }
1068
1147
  async run() {
1069
- const { root, signal, excluder } = this.#options;
1148
+ const { root, signal, excluder, start } = this.#options;
1070
1149
  if (signal?.aborted) throw new AbortError();
1071
- const rootStats = await stat(root);
1072
- if (this.#options.followSymlinks) this.#seenDirs.add(await inodeKey(rootStats, root));
1073
- const chain = await excluder.loadAncestorChain(root);
1074
- const index = this.#addDir("", -1, 0);
1150
+ let chain;
1151
+ if (start) chain = start.chain;
1152
+ else {
1153
+ const rootStats = await stat(root);
1154
+ if (this.#options.followSymlinks) this.#seenDirs.add(await inodeKey(rootStats, root));
1155
+ chain = await excluder.loadAncestorChain(root);
1156
+ }
1157
+ const index = this.#addDir(start ? basename(start.rel) : "", -1, start?.depth ?? 0, chain);
1158
+ const relRoot = start?.rel ?? "";
1075
1159
  const onAbort = () => this.#limiter.abort(new AbortError());
1076
1160
  signal?.addEventListener("abort", onAbort, { once: true });
1077
1161
  try {
1078
- this.#limiter.run(() => this.#scanDir(index, root, chain, ""));
1162
+ this.#limiter.run(() => this.#scanDir(index, root, chain, this.#options.excluder.needsPaths ? relRoot : ""));
1079
1163
  await this.#limiter.idle();
1164
+ await this.#enterLinkedDirs();
1165
+ this.#countLinkedFiles();
1080
1166
  } finally {
1081
1167
  signal?.removeEventListener("abort", onAbort);
1082
1168
  }
@@ -1088,16 +1174,47 @@ var Scanner = class {
1088
1174
  compareRelative(dirA, nameA, dirB, nameB) {
1089
1175
  return compareRelativePaths(this.dirs, dirA, nameA, dirB, nameB);
1090
1176
  }
1177
+ /**
1178
+ * With followSymlinks, a directory can be reached through its real path and
1179
+ * through any number of symlinks. Real paths are walked first; then, round
1180
+ * by round, each directory reached only through symlinks is entered through
1181
+ * the link whose path sorts first. Every directory a round enters is
1182
+ * claimed before any of them is read, so the outcome is the same whatever
1183
+ * order the reads finish in.
1184
+ */
1185
+ async #enterLinkedDirs() {
1186
+ while (this.#linkedDirs.length > 0) {
1187
+ const round = this.#linkedDirs.sort((a, b) => this.compareRelative(a.parent, a.name, b.parent, b.name));
1188
+ this.#linkedDirs = [];
1189
+ for (const link of round) {
1190
+ if (this.#seenDirs.has(link.key)) continue;
1191
+ this.#seenDirs.add(link.key);
1192
+ this.#enterDir(link.parent, link.name, link.fullPath, link.chain, link.relPath);
1193
+ }
1194
+ await this.#limiter.idle();
1195
+ }
1196
+ }
1197
+ /**
1198
+ * Counts each file that several paths lead to once, under one path: a real
1199
+ * path over a followed symlink, then the path that sorts first. This is the
1200
+ * rule `dat watch` uses for hard links, so both report the same paths.
1201
+ */
1202
+ #countLinkedFiles() {
1203
+ const files = this.#linkedFiles;
1204
+ const chosen = [];
1205
+ for (const [key, slot] of files.entries()) if (!this.#seenInodes.has(key)) chosen.push(slot);
1206
+ chosen.sort((a, b) => this.compareRelative(files.dir(a), files.name(a), files.dir(b), files.name(b)));
1207
+ for (const slot of chosen) this.#countFile(files.dir(slot), files.name(slot), files.stats(slot));
1208
+ this.#linkedFiles = new LinkedFiles();
1209
+ }
1091
1210
  /** Root-relative path of a directory (or of `name` inside it), with `/` separators. */
1092
1211
  relativePath(dirIndex, name) {
1093
- const parts = name === void 0 ? [] : [name];
1094
- for (let i = dirIndex; i > 0; i = this.dirs[i].parent) parts.push(this.dirs[i].name);
1095
- return parts.toReversed().join("/");
1212
+ return relativePathOf(this.dirs, dirIndex, name);
1096
1213
  }
1097
1214
  absolutePath(dirIndex, name) {
1098
1215
  return joinRelative(this.#options.root, this.relativePath(dirIndex, name));
1099
1216
  }
1100
- #addDir(name, parent, depth) {
1217
+ #addDir(name, parent, depth, chain) {
1101
1218
  const node = {
1102
1219
  name,
1103
1220
  parent,
@@ -1113,7 +1230,7 @@ var Scanner = class {
1113
1230
  };
1114
1231
  const index = this.dirs.push(node) - 1;
1115
1232
  this.counters.directories++;
1116
- this.#visitor.directory?.(index, node);
1233
+ this.#visitor.directory?.(index, node, chain);
1117
1234
  return index;
1118
1235
  }
1119
1236
  /**
@@ -1128,7 +1245,7 @@ var Scanner = class {
1128
1245
  entries = await readdir(absPath, { withFileTypes: true });
1129
1246
  } catch (error) {
1130
1247
  this.dirs[index].entries = -1;
1131
- this.recordError(this.relativePath(index), error);
1248
+ this.recordError(this.relativePath(index), error, index);
1132
1249
  return;
1133
1250
  }
1134
1251
  const node = this.dirs[index];
@@ -1181,7 +1298,11 @@ var Scanner = class {
1181
1298
  });
1182
1299
  return;
1183
1300
  }
1184
- const child = this.#addDir(name, parent, depth);
1301
+ if (this.#options.start?.shallow) {
1302
+ this.#visitor.subfolder?.(parent, name, chain);
1303
+ return;
1304
+ }
1305
+ const child = this.#addDir(name, parent, depth, chain);
1185
1306
  this.#limiter.run(() => this.#scanDir(child, fullPath, chain, relPath));
1186
1307
  }
1187
1308
  async #statFile(dirIndex, name, fullPath) {
@@ -1189,7 +1310,7 @@ var Scanner = class {
1189
1310
  try {
1190
1311
  stats = await lstat(fullPath);
1191
1312
  } catch (error) {
1192
- this.recordError(this.relativePath(dirIndex, name), error);
1313
+ this.recordError(this.relativePath(dirIndex, name), error, dirIndex);
1193
1314
  return;
1194
1315
  }
1195
1316
  const pending = this.#acceptFile(dirIndex, name, fullPath, stats);
@@ -1228,7 +1349,7 @@ var Scanner = class {
1228
1349
  });
1229
1350
  return;
1230
1351
  }
1231
- this.recordError(this.relativePath(dirIndex, name), error);
1352
+ this.recordError(this.relativePath(dirIndex, name), error, dirIndex);
1232
1353
  return;
1233
1354
  }
1234
1355
  if (isSymlink) this.counters.symlinks++;
@@ -1248,11 +1369,22 @@ var Scanner = class {
1248
1369
  }
1249
1370
  }
1250
1371
  const key = await inodeKey(stats, fullPath);
1372
+ if (isSymlink) {
1373
+ this.#linkedDirs.push({
1374
+ parent: dirIndex,
1375
+ name,
1376
+ fullPath,
1377
+ chain,
1378
+ relPath,
1379
+ key
1380
+ });
1381
+ return;
1382
+ }
1251
1383
  if (this.#seenDirs.has(key)) return;
1252
1384
  this.#seenDirs.add(key);
1253
1385
  this.#enterDir(dirIndex, name, fullPath, chain, relPath);
1254
1386
  } else if (stats.isFile()) {
1255
- const pending = this.#acceptFile(dirIndex, name, fullPath, stats);
1387
+ const pending = this.#acceptFile(dirIndex, name, fullPath, stats, isSymlink);
1256
1388
  if (pending) await pending;
1257
1389
  }
1258
1390
  }
@@ -1260,40 +1392,50 @@ var Scanner = class {
1260
1392
  * Counts a file once per underlying data. Synchronous unless the file's
1261
1393
  * identity needs an exact (bigint) stat; see `inodeKey`.
1262
1394
  */
1263
- #acceptFile(dirIndex, name, fullPath, stats) {
1395
+ #acceptFile(dirIndex, name, fullPath, stats, viaSymlink = false) {
1396
+ const onLinked = this.#options.onLinkedFile;
1397
+ if (onLinked && !this.#options.countHardlinks && stats.nlink > 1) {
1398
+ const key = inodeKey(stats, fullPath);
1399
+ if (typeof key !== "string") return key.then((exact) => onLinked(dirIndex, name, stats, exact));
1400
+ onLinked(dirIndex, name, stats, key);
1401
+ return;
1402
+ }
1264
1403
  if (!this.#options.countHardlinks && (stats.nlink > 1 || this.#options.followSymlinks)) {
1265
1404
  const key = inodeKey(stats, fullPath);
1266
- if (typeof key !== "string") return key.then((exact) => this.#acceptKeyedFile(dirIndex, name, stats, exact));
1267
- this.#acceptKeyedFile(dirIndex, name, stats, key);
1405
+ if (typeof key !== "string") return key.then((exact) => this.#acceptKeyedFile(dirIndex, name, stats, exact, viaSymlink));
1406
+ this.#acceptKeyedFile(dirIndex, name, stats, key, viaSymlink);
1268
1407
  return;
1269
1408
  }
1270
1409
  this.#countFile(dirIndex, name, stats);
1271
1410
  }
1272
- #acceptKeyedFile(dirIndex, name, stats, key) {
1273
- if (this.#seenInodes.has(key)) {
1274
- if (stats.nlink > 1) this.counters.hardlinks++;
1411
+ #acceptKeyedFile(dirIndex, name, stats, key, viaSymlink) {
1412
+ if (stats.nlink === 1 && !viaSymlink) {
1413
+ this.#seenInodes.add(key);
1414
+ this.#countFile(dirIndex, name, stats);
1275
1415
  return;
1276
1416
  }
1277
- this.#seenInodes.add(key);
1278
- this.#countFile(dirIndex, name, stats);
1417
+ const files = this.#linkedFiles;
1418
+ const slot = files.slot(key);
1419
+ if (slot === void 0) {
1420
+ files.add(key, dirIndex, name, stats, viaSymlink);
1421
+ return;
1422
+ }
1423
+ if (stats.nlink > 1) this.counters.hardlinks++;
1424
+ if (viaSymlink === files.viaSymlink(slot) ? this.compareRelative(dirIndex, name, files.dir(slot), files.name(slot)) < 0 : !viaSymlink) files.set(slot, dirIndex, name, stats, viaSymlink);
1279
1425
  }
1280
1426
  #countFile(dirIndex, name, stats) {
1281
1427
  const size = stats.size;
1282
- if (this.#filtersActive) {
1283
- const o = this.#options;
1284
- const mtime = stats.mtimeMs;
1285
- if (size < o.minSize || size > o.maxSize || mtime < o.modifiedAfter || mtime > o.modifiedBefore) {
1286
- this.counters.filtered++;
1287
- o.onSkip?.({
1288
- kind: "filtered",
1289
- dir: dirIndex,
1290
- name,
1291
- stats
1292
- });
1293
- return;
1294
- }
1428
+ if (this.#filtersActive && !passesFilters(this.#options, stats)) {
1429
+ this.counters.filtered++;
1430
+ this.#options.onSkip?.({
1431
+ kind: "filtered",
1432
+ dir: dirIndex,
1433
+ name,
1434
+ stats
1435
+ });
1436
+ return;
1295
1437
  }
1296
- const diskBytes = IS_WINDOWS || !(stats.blocks >= 0) ? size : stats.blocks * 512;
1438
+ const diskBytes = diskBytesOf(stats);
1297
1439
  const node = this.dirs[dirIndex];
1298
1440
  node.ownFiles++;
1299
1441
  node.ownBytes += size;
@@ -1304,15 +1446,11 @@ var Scanner = class {
1304
1446
  this.#visitor.file(dirIndex, name, stats, diskBytes);
1305
1447
  }
1306
1448
  /** Counts an error and keeps its details, up to {@link MAX_ERROR_DETAILS}. */
1307
- recordError(path, error) {
1449
+ recordError(path, error, dir = -1) {
1308
1450
  this.counters.errors++;
1309
- if (this.errors.length >= 100) return;
1310
- const code = errorCode(error);
1311
- this.errors.push({
1312
- path: path || ".",
1313
- code: code ?? "UNKNOWN",
1314
- message: (code && ERROR_DESCRIPTIONS[code]) ?? errorMessage(error)
1315
- });
1451
+ const detail = scanError(path, error);
1452
+ if (dir >= 0) this.#options.onError?.(dir, detail);
1453
+ if (this.errors.length < 100) this.errors.push(detail);
1316
1454
  }
1317
1455
  };
1318
1456
  /**
@@ -1334,6 +1472,31 @@ function rollUp(dirs) {
1334
1472
  }
1335
1473
  }
1336
1474
  }
1475
+ /** Root-relative path of a directory (or of `name` inside it) in `dirs`, with `/` separators. */
1476
+ function relativePathOf(dirs, dirIndex, name) {
1477
+ const parts = name === void 0 ? [] : [name];
1478
+ for (let i = dirIndex; i > 0; i = dirs[i].parent) parts.push(dirs[i].name);
1479
+ return parts.toReversed().join("/");
1480
+ }
1481
+ /** Whether a file passes the size and date filters. */
1482
+ function passesFilters(options, stats) {
1483
+ const size = stats.size;
1484
+ const mtime = stats.mtimeMs;
1485
+ return !(size < options.minSize || size > options.maxSize || mtime < options.modifiedAfter || mtime > options.modifiedBefore);
1486
+ }
1487
+ /** Space a file takes on disk, which `du` reports; its length where blocks aren't known. */
1488
+ function diskBytesOf(stats) {
1489
+ return IS_WINDOWS || !(stats.blocks >= 0) ? stats.size : stats.blocks * 512;
1490
+ }
1491
+ /** An error's details as reports show them. */
1492
+ function scanError(path, error) {
1493
+ const code = errorCode(error);
1494
+ return {
1495
+ path: path || ".",
1496
+ code: code ?? "UNKNOWN",
1497
+ message: (code && ERROR_DESCRIPTIONS[code]) ?? errorMessage(error)
1498
+ };
1499
+ }
1337
1500
  /** Code unit of the `/` that joins path segments. */
1338
1501
  const SLASH = 47;
1339
1502
  /**
@@ -1485,6 +1648,7 @@ async function hashStage(groups, stage, options, hashing) {
1485
1648
  /** Records one file's digest, or its error, the same way for both paths. */
1486
1649
  const record = (candidate, state, digest) => {
1487
1650
  if (typeof digest === "string") {
1651
+ options.cache?.set(candidate, stage, digest);
1488
1652
  const members = state.byHash.get(digest);
1489
1653
  if (members) members.push(candidate);
1490
1654
  else state.byHash.set(digest, [candidate]);
@@ -1497,17 +1661,24 @@ async function hashStage(groups, stage, options, hashing) {
1497
1661
  total
1498
1662
  });
1499
1663
  };
1500
- function* files() {
1501
- for (const group of groups) {
1502
- const state = {
1503
- bytes: group[0].bytes,
1504
- pending: group.length,
1505
- byHash: /* @__PURE__ */ new Map()
1506
- };
1507
- for (const candidate of group) yield [candidate, state];
1664
+ const cache = options.cache;
1665
+ const states = groups.map((group) => [group, {
1666
+ bytes: group[0].bytes,
1667
+ pending: group.length,
1668
+ byHash: /* @__PURE__ */ new Map()
1669
+ }]);
1670
+ let toHash = total;
1671
+ if (cache) for (const [group, state] of states) for (const candidate of group) {
1672
+ const digest = cache.get(candidate, stage);
1673
+ if (digest !== void 0) {
1674
+ record(candidate, state, digest);
1675
+ toHash--;
1508
1676
  }
1509
1677
  }
1510
- if (hashing.workers > 0 && total >= hashing.threshold) {
1678
+ function* files() {
1679
+ for (const [group, state] of states) for (const candidate of group) if (cache?.get(candidate, stage) === void 0) yield [candidate, state];
1680
+ }
1681
+ if (hashing.workers > 0 && toHash >= hashing.threshold) {
1511
1682
  hashing.pool ??= new HashPool(hashing.workers);
1512
1683
  await hashWithWorkers(files(), stage, options, hashing.pool, record);
1513
1684
  return results;
@@ -2525,6 +2696,13 @@ const DEFAULT_LARGE_FILE_THRESHOLD = 104857600;
2525
2696
  const DEFAULT_STALE_AGE = "1y";
2526
2697
  /** A directory is folded into its largest child when that child holds this share of its size. */
2527
2698
  const PASS_THROUGH_SHARE$1 = .95;
2699
+ /** Digests kept on the candidates themselves, for {@link Collector.findDuplicates}. */
2700
+ const CANDIDATE_DIGESTS = {
2701
+ get: (candidate, stage) => candidate.digests?.[stage],
2702
+ set: (candidate, stage, digest) => {
2703
+ (candidate.digests ??= {})[stage] = digest;
2704
+ }
2705
+ };
2528
2706
  /**
2529
2707
  * Analyzes a directory tree in a single pass.
2530
2708
  *
@@ -2566,7 +2744,7 @@ async function analyze(path, options = {}) {
2566
2744
  progress.stop();
2567
2745
  const interval = options.progressInterval ?? 100;
2568
2746
  let last = 0;
2569
- duplicates = await collector.findDuplicates(scanOptions.concurrency, scanOptions.signal, (p) => {
2747
+ duplicates = await collector.findDuplicates(scanner, scanOptions.concurrency, scanOptions.signal, (p) => {
2570
2748
  if (!report) return;
2571
2749
  const now = performance.now();
2572
2750
  if (p.done !== p.total && p.done !== 0 && now - last < interval) return;
@@ -2643,40 +2821,123 @@ function resolveFeatures(options, now) {
2643
2821
  budgets
2644
2822
  };
2645
2823
  }
2646
- /** Collects every statistic during the scan. One instance per analysis. */
2824
+ /**
2825
+ * Collects every statistic during the scan. One instance per analysis, or in
2826
+ * watch one per folder, merged into a fresh one with {@link absorb} for each report.
2827
+ */
2647
2828
  var Collector = class {
2648
2829
  #features;
2830
+ #stamps;
2649
2831
  #scanner = null;
2650
- #types = emptyTypeStats();
2651
- #extensions = /* @__PURE__ */ new Map();
2832
+ /** File types with at least one file; `build` lists every type in the usual order. */
2833
+ #types = null;
2834
+ #extensions = null;
2652
2835
  #largestFileBytes = 0;
2653
- #topFiles;
2654
- #large = {
2655
- refs: [],
2656
- bytes: 0
2657
- };
2658
- #empty = [];
2659
- #stale = {
2660
- refs: [],
2661
- bytes: 0
2662
- };
2836
+ #topFiles = null;
2837
+ #large = null;
2838
+ #empty = null;
2839
+ #stale = null;
2663
2840
  /** Size -> candidates; a single candidate is stored unwrapped to save memory. */
2664
- #bySize = /* @__PURE__ */ new Map();
2841
+ #bySize = null;
2665
2842
  /** Tree data: subdirectories and largest files of each directory shallower than the tree depth. */
2666
- #treeChildren = /* @__PURE__ */ new Map();
2667
- #treeFiles = /* @__PURE__ */ new Map();
2668
- constructor(features) {
2843
+ #treeChildren = null;
2844
+ #treeFiles = null;
2845
+ /** @param stamps Keep each duplicate candidate's timestamps (see {@link DigestCache}). */
2846
+ constructor(features, stamps = false) {
2669
2847
  this.#features = features;
2670
- this.#topFiles = new TopK(features.top, (a, b) => this.#compareRefs(a, b));
2848
+ this.#stamps = stamps;
2849
+ }
2850
+ #addType(category, files, bytes) {
2851
+ const types = this.#types ??= {};
2852
+ const stat = types[category];
2853
+ if (stat) {
2854
+ stat.files += files;
2855
+ stat.bytes += bytes;
2856
+ } else types[category] = {
2857
+ files,
2858
+ bytes
2859
+ };
2860
+ }
2861
+ #addExtension(extension, files, bytes) {
2862
+ const extensions = this.#extensions ??= /* @__PURE__ */ new Map();
2863
+ const stat = extensions.get(extension);
2864
+ if (stat) {
2865
+ stat.files += files;
2866
+ stat.bytes += bytes;
2867
+ } else extensions.set(extension, {
2868
+ files,
2869
+ bytes
2870
+ });
2871
+ }
2872
+ #pushTop(ref) {
2873
+ (this.#topFiles ??= new TopK(this.#features.top, (a, b) => this.#compareRefs(a, b))).push(ref.bytes, ref);
2874
+ }
2875
+ #acceptsTop(bytes) {
2876
+ if (this.#features.top === 0) return false;
2877
+ return this.#topFiles?.accepts(bytes) ?? true;
2671
2878
  }
2672
2879
  attach(scanner) {
2673
2880
  this.#scanner = scanner;
2674
2881
  }
2882
+ /**
2883
+ * Adds everything `other` collected for a single folder, which it knew as
2884
+ * directory 0, as directory `dir` of this collector's tree. Lists and top-N
2885
+ * heaps merge to what one collector would have kept seeing every file.
2886
+ */
2887
+ absorb(other, dir) {
2888
+ const move = (ref) => ({
2889
+ ...ref,
2890
+ dir
2891
+ });
2892
+ for (const category of CATEGORIES) {
2893
+ const stat = other.#types?.[category];
2894
+ if (stat) this.#addType(category, stat.files, stat.bytes);
2895
+ }
2896
+ for (const [extension, stat] of other.#extensions ?? []) this.#addExtension(extension, stat.files, stat.bytes);
2897
+ if (other.#largestFileBytes > this.#largestFileBytes) this.#largestFileBytes = other.#largestFileBytes;
2898
+ for (const ref of other.#topFiles?.sorted() ?? []) if (this.#acceptsTop(ref.bytes)) this.#pushTop(move(ref));
2899
+ if (other.#large) {
2900
+ const large = this.#large ??= {
2901
+ refs: [],
2902
+ bytes: 0
2903
+ };
2904
+ for (const ref of other.#large.refs) large.refs.push(move(ref));
2905
+ large.bytes += other.#large.bytes;
2906
+ }
2907
+ if (other.#empty) {
2908
+ const empty = this.#empty ??= [];
2909
+ for (const ref of other.#empty) empty.push(move(ref));
2910
+ }
2911
+ if (other.#stale) {
2912
+ const stale = this.#stale ??= {
2913
+ refs: [],
2914
+ bytes: 0
2915
+ };
2916
+ for (const ref of other.#stale.refs) stale.refs.push(move(ref));
2917
+ stale.bytes += other.#stale.bytes;
2918
+ }
2919
+ const files = other.#treeFiles?.get(0);
2920
+ if (files) {
2921
+ const heap = new TopK(this.#features.tree.limit, (a, b) => comparePaths(a.name, b.name));
2922
+ for (const ref of files.sorted()) heap.push(ref.bytes, move(ref));
2923
+ (this.#treeFiles ??= /* @__PURE__ */ new Map()).set(dir, heap);
2924
+ }
2925
+ for (const candidate of other.candidates()) {
2926
+ candidate.dir = dir;
2927
+ this.#addCandidate(candidate);
2928
+ }
2929
+ }
2930
+ /** Every duplicate candidate collected so far. */
2931
+ *candidates() {
2932
+ for (const value of this.#bySize?.values() ?? []) if (Array.isArray(value)) yield* value;
2933
+ else yield value;
2934
+ }
2675
2935
  directory(index, node) {
2676
2936
  const tree = this.#features.tree;
2677
2937
  if (tree && node.parent >= 0 && node.depth <= tree.depth) {
2678
- let siblings = this.#treeChildren.get(node.parent);
2679
- if (!siblings) this.#treeChildren.set(node.parent, siblings = []);
2938
+ const children = this.#treeChildren ??= /* @__PURE__ */ new Map();
2939
+ let siblings = children.get(node.parent);
2940
+ if (!siblings) children.set(node.parent, siblings = []);
2680
2941
  siblings.push(index);
2681
2942
  }
2682
2943
  }
@@ -2685,17 +2946,8 @@ var Collector = class {
2685
2946
  const mtimeMs = stats.mtimeMs;
2686
2947
  const features = this.#features;
2687
2948
  const extension = extensionOf(name);
2688
- const type = this.#types[classify(name, extension)];
2689
- type.files++;
2690
- type.bytes += bytes;
2691
- const ext = this.#extensions.get(extension);
2692
- if (ext) {
2693
- ext.files++;
2694
- ext.bytes += bytes;
2695
- } else this.#extensions.set(extension, {
2696
- files: 1,
2697
- bytes
2698
- });
2949
+ this.#addType(classify(name, extension), 1, bytes);
2950
+ this.#addExtension(extension, 1, bytes);
2699
2951
  if (bytes > this.#largestFileBytes) this.#largestFileBytes = bytes;
2700
2952
  let ref;
2701
2953
  const makeRef = () => ref ??= {
@@ -2704,22 +2956,31 @@ var Collector = class {
2704
2956
  bytes,
2705
2957
  mtimeMs
2706
2958
  };
2707
- if (this.#topFiles.accepts(bytes)) this.#topFiles.push(bytes, makeRef());
2959
+ if (this.#acceptsTop(bytes)) this.#pushTop(makeRef());
2708
2960
  if (features.largeThreshold !== null && bytes >= features.largeThreshold) {
2709
- this.#large.refs.push(makeRef());
2710
- this.#large.bytes += bytes;
2961
+ const large = this.#large ??= {
2962
+ refs: [],
2963
+ bytes: 0
2964
+ };
2965
+ large.refs.push(makeRef());
2966
+ large.bytes += bytes;
2711
2967
  }
2712
- if (features.empty && bytes === 0) this.#empty.push(makeRef());
2968
+ if (features.empty && bytes === 0) (this.#empty ??= []).push(makeRef());
2713
2969
  if (features.staleBefore !== null && mtimeMs < features.staleBefore) {
2714
- this.#stale.refs.push(makeRef());
2715
- this.#stale.bytes += bytes;
2970
+ const stale = this.#stale ??= {
2971
+ refs: [],
2972
+ bytes: 0
2973
+ };
2974
+ stale.refs.push(makeRef());
2975
+ stale.bytes += bytes;
2716
2976
  }
2717
2977
  if (features.tree) {
2718
2978
  if (this.#scanner.dirs[dir].depth < features.tree.depth) {
2719
- let heap = this.#treeFiles.get(dir);
2979
+ const heaps = this.#treeFiles ??= /* @__PURE__ */ new Map();
2980
+ let heap = heaps.get(dir);
2720
2981
  if (!heap) {
2721
2982
  heap = new TopK(features.tree.limit, (a, b) => comparePaths(a.name, b.name));
2722
- this.#treeFiles.set(dir, heap);
2983
+ heaps.set(dir, heap);
2723
2984
  }
2724
2985
  if (heap.accepts(bytes)) heap.push(bytes, makeRef());
2725
2986
  }
@@ -2733,17 +2994,24 @@ var Collector = class {
2733
2994
  ino: stats.ino,
2734
2995
  nlink: stats.nlink
2735
2996
  };
2736
- const existing = this.#bySize.get(bytes);
2737
- if (existing === void 0) this.#bySize.set(bytes, candidate);
2738
- else if (Array.isArray(existing)) existing.push(candidate);
2739
- else this.#bySize.set(bytes, [existing, candidate]);
2997
+ if (this.#stamps) {
2998
+ candidate.mtimeMs = mtimeMs;
2999
+ candidate.ctimeMs = stats.ctimeMs;
3000
+ }
3001
+ this.#addCandidate(candidate);
2740
3002
  }
2741
3003
  }
2742
- async findDuplicates(concurrency, signal, onProgress) {
2743
- const scanner = this.#scanner;
3004
+ #addCandidate(candidate) {
3005
+ const bySize = this.#bySize ??= /* @__PURE__ */ new Map();
3006
+ const existing = bySize.get(candidate.bytes);
3007
+ if (existing === void 0) bySize.set(candidate.bytes, candidate);
3008
+ else if (Array.isArray(existing)) existing.push(candidate);
3009
+ else bySize.set(candidate.bytes, [existing, candidate]);
3010
+ }
3011
+ async findDuplicates(scanner, concurrency, signal, onProgress, cache) {
2744
3012
  const groups = [];
2745
- for (const value of this.#bySize.values()) if (Array.isArray(value)) groups.push(value);
2746
- this.#bySize.clear();
3013
+ for (const value of this.#bySize?.values() ?? []) if (Array.isArray(value)) groups.push(value);
3014
+ this.#bySize = null;
2747
3015
  const dirPaths = /* @__PURE__ */ new Map();
2748
3016
  const items = (await findDuplicates(groups, {
2749
3017
  pathOf: (c) => {
@@ -2754,7 +3022,8 @@ var Collector = class {
2754
3022
  concurrency,
2755
3023
  signal,
2756
3024
  onProgress,
2757
- onError: (c, error) => scanner.recordError(scanner.relativePath(c.dir, c.name), error)
3025
+ onError: (c, error) => scanner.recordError(scanner.relativePath(c.dir, c.name), error),
3026
+ cache
2758
3027
  })).map((group) => {
2759
3028
  const files = group.members.map((m) => scanner.relativePath(m.dir, m.name)).sort(comparePaths);
2760
3029
  return {
@@ -2809,27 +3078,34 @@ var Collector = class {
2809
3078
  filtered: c.filtered,
2810
3079
  errors: c.errors
2811
3080
  },
2812
- types: this.#types,
2813
- extensions: [...this.#extensions].map(([extension, stat]) => ({
3081
+ types: this.#typeStats(),
3082
+ extensions: [...this.#extensions ?? []].map(([extension, stat]) => ({
2814
3083
  extension,
2815
3084
  ...stat
2816
3085
  })).sort((a, b) => b.bytes - a.bytes || b.files - a.files || comparePaths(a.extension, b.extension)),
2817
3086
  largestDirectories: this.#largestDirectories(scanner),
2818
- largestFiles: this.#topFiles.sorted().map(toEntry),
3087
+ largestFiles: (this.#topFiles?.sorted() ?? []).map(toEntry),
2819
3088
  errors: [...scanner.errors].sort((a, b) => comparePaths(a.path, b.path))
2820
3089
  };
2821
- if (features.largeThreshold !== null) result.largeFiles = {
2822
- threshold: features.largeThreshold,
2823
- count: this.#large.refs.length,
2824
- bytes: this.#large.bytes,
2825
- items: this.#large.refs.map(toEntry).sort(bySizeThenPath)
2826
- };
3090
+ if (features.largeThreshold !== null) {
3091
+ const large = this.#large ?? {
3092
+ refs: [],
3093
+ bytes: 0
3094
+ };
3095
+ result.largeFiles = {
3096
+ threshold: features.largeThreshold,
3097
+ count: large.refs.length,
3098
+ bytes: large.bytes,
3099
+ items: large.refs.map(toEntry).sort(bySizeThenPath)
3100
+ };
3101
+ }
2827
3102
  if (context.duplicates) result.duplicates = context.duplicates;
2828
3103
  if (features.empty) {
3104
+ const empty = this.#empty ?? [];
2829
3105
  result.emptyFiles = {
2830
- count: this.#empty.length,
3106
+ count: empty.length,
2831
3107
  bytes: 0,
2832
- items: this.#empty.map(toEntry).sort((a, b) => comparePaths(a.path, b.path))
3108
+ items: empty.map(toEntry).sort((a, b) => comparePaths(a.path, b.path))
2833
3109
  };
2834
3110
  const emptyDirs = [];
2835
3111
  for (let i = 1; i < scanner.dirs.length; i++) if (scanner.dirs[i].entries === 0) emptyDirs.push(scanner.relativePath(i));
@@ -2838,15 +3114,30 @@ var Collector = class {
2838
3114
  items: emptyDirs.sort(comparePaths)
2839
3115
  };
2840
3116
  }
2841
- if (features.staleBefore !== null) result.staleFiles = {
2842
- modifiedBefore: new Date(features.staleBefore).toISOString(),
2843
- count: this.#stale.refs.length,
2844
- bytes: this.#stale.bytes,
2845
- items: this.#stale.refs.map(toEntry).sort(bySizeThenPath)
2846
- };
3117
+ if (features.staleBefore !== null) {
3118
+ const stale = this.#stale ?? {
3119
+ refs: [],
3120
+ bytes: 0
3121
+ };
3122
+ result.staleFiles = {
3123
+ modifiedBefore: new Date(features.staleBefore).toISOString(),
3124
+ count: stale.refs.length,
3125
+ bytes: stale.bytes,
3126
+ items: stale.refs.map(toEntry).sort(bySizeThenPath)
3127
+ };
3128
+ }
2847
3129
  if (features.tree) result.tree = this.#buildTree(scanner, 0, features.tree.limit, toEntry);
2848
3130
  return result;
2849
3131
  }
3132
+ /** Every file type, in the usual order, including those without files. */
3133
+ #typeStats() {
3134
+ const types = emptyTypeStats();
3135
+ for (const category of CATEGORIES) {
3136
+ const stat = this.#types?.[category];
3137
+ if (stat) types[category] = { ...stat };
3138
+ }
3139
+ return types;
3140
+ }
2850
3141
  #largestDirectories(scanner) {
2851
3142
  const top = new TopK(this.#features.top, (a, b) => scanner.compareRelative(a, void 0, b, void 0));
2852
3143
  const dirs = scanner.dirs;
@@ -2871,8 +3162,8 @@ var Collector = class {
2871
3162
  bytes: node.bytes,
2872
3163
  files: node.files
2873
3164
  };
2874
- const subdirs = this.#treeChildren.get(index);
2875
- const files = this.#treeFiles.get(index);
3165
+ const subdirs = this.#treeChildren?.get(index);
3166
+ const files = this.#treeFiles?.get(index);
2876
3167
  if (!subdirs && !files) return result;
2877
3168
  const candidates = [];
2878
3169
  for (const child of subdirs ?? []) candidates.push({
@@ -2949,8 +3240,7 @@ function createProgressReporter(report, interval, snapshot) {
2949
3240
  * already bounded by `top` or by the tree's own per-folder limit.
2950
3241
  */
2951
3242
  function compactAnalysis(result, options) {
2952
- const { limit } = options;
2953
- if (!Number.isSafeInteger(limit) || limit < 0) throw new RangeError(`compact limit must be a whole number of at least 0 (got ${limit}).`);
3243
+ const limit = checkLimit(options.limit);
2954
3244
  const previous = result.compact?.omitted ?? {};
2955
3245
  const cuts = [];
2956
3246
  const note = (list, total, shown) => {
@@ -3023,6 +3313,52 @@ function compactAnalysis(result, options) {
3023
3313
  };
3024
3314
  return out;
3025
3315
  }
3316
+ /**
3317
+ * Bounds the file lists of a comparison to `limit` items, as
3318
+ * {@link compactAnalysis} does for an analysis. Counts, sizes and deltas stay
3319
+ * the full totals; what was cut is listed in `compact.omitted`. Returns a new
3320
+ * result and leaves the input untouched.
3321
+ *
3322
+ * Cut: the `items` of `added`, `removed`, and `changed`. Not cut: the sides'
3323
+ * summaries and types, `delta`, and `directories`, which `top` already bounds.
3324
+ */
3325
+ function compactComparison(result, options) {
3326
+ const limit = checkLimit(options.limit);
3327
+ const omitted = {};
3328
+ const cut = (list, items, count) => {
3329
+ const total = Math.max(count, items.length);
3330
+ const shown = items.slice(0, limit);
3331
+ if (total > shown.length) omitted[list] = total - shown.length;
3332
+ return shown;
3333
+ };
3334
+ const info = {
3335
+ limit,
3336
+ truncated: false,
3337
+ omitted
3338
+ };
3339
+ const out = {
3340
+ ...result,
3341
+ added: {
3342
+ ...result.added,
3343
+ items: cut("added.items", result.added.items, result.added.count)
3344
+ },
3345
+ removed: {
3346
+ ...result.removed,
3347
+ items: cut("removed.items", result.removed.items, result.removed.count)
3348
+ },
3349
+ changed: {
3350
+ ...result.changed,
3351
+ items: cut("changed.items", result.changed.items, result.changed.count)
3352
+ },
3353
+ compact: info
3354
+ };
3355
+ info.truncated = Object.keys(omitted).length > 0;
3356
+ return out;
3357
+ }
3358
+ function checkLimit(limit) {
3359
+ if (!Number.isSafeInteger(limit) || limit < 0) throw new RangeError(`compact limit must be a whole number of at least 0 (got ${limit}).`);
3360
+ return limit;
3361
+ }
3026
3362
  // src/core/compare.ts
3027
3363
  const PASS_THROUGH_SHARE = .95;
3028
3364
  /** Records every file by its root-relative path, for diffing. */
@@ -3466,14 +3802,14 @@ function nestedRepositoryNote(path) {
3466
3802
  function hardlinkNote(path) {
3467
3803
  return {
3468
3804
  code: "hardlink-order-dependent",
3469
- message: "A file with several hard links is counted once; which of its paths is counted depends on scan order.",
3805
+ message: "A file with several hard links is counted once, under the link whose path sorts first; the others count in summary.hardlinks.",
3470
3806
  ...path === void 0 ? {} : { path }
3471
3807
  };
3472
3808
  }
3473
3809
  function symlinkOrderNote(path) {
3474
3810
  return {
3475
3811
  code: "symlink-order-dependent",
3476
- message: "With --follow-symlinks, a directory reached by several paths is entered once; which path depends on scan order.",
3812
+ message: "With --follow-symlinks, a directory reached by several paths is entered once: through its real path when the scan has one, otherwise through the link whose path sorts first.",
3477
3813
  ...path === void 0 ? {} : { path }
3478
3814
  };
3479
3815
  }
@@ -5348,4 +5684,4 @@ function renderSkipsExplanation(result, options = {}) {
5348
5684
  }
5349
5685
  return `${lines.join("\n")}\n`;
5350
5686
  }
5351
- export { errorCode as $, DEFAULT_LARGE_FILE_THRESHOLD as A, extensionOf as B, MAX_EXPLAIN_LIMIT as C, outsideRootError as D, isOutside as E, listDirectories as F, formatBytes as G, evaluateBudgets as H, DEFAULT_EXCLUDES as I, VERSION as J, parseSize as K, Excluder as L, analyze as M, DEFAULT_CONCURRENCY as N, compare as O, assertDirectory as P, DatError as Q, joinRelative as R, EXPLAIN_VERSION as S, explainSkips as T, formatBudgetActual as U, BUDGET_METRICS as V, parseBudget as W, parsePointInTime as X, parseDuration as Y, AbortError as Z, findConfigFile as _, renderComparisonCsv as a, validateConfig as b, renderAnalysis as c, escapeControlInLines as d, errorMessage as et, formatCount as f, CONFIG_FILE_NAMES as g, supportsColor as h, renderAnalysisCsv as i, DEFAULT_STALE_AGE as j, compactAnalysis as k, renderComparison as l, createStyle as m, renderSkipsExplanation as n, renderAnalysisMarkdown as o, stringifyJson as p, CATEGORIES as q, renderAnalysisHtml as r, renderComparisonMarkdown as s, renderPathExplanation as t, escapeControl as u, loadConfig as v, explainPath as w, DEFAULT_EXPLAIN_LIMIT as x, buildJsonSchema as y, classify as z };
5687
+ export { classify as $, compactComparison as A, listDirectories as B, MAX_EXPLAIN_LIMIT as C, outsideRootError as D, isOutside as E, analyze as F, compareRelativePaths as G, DEFAULT_EXCLUDES as H, createProgressReporter as I, relativePathOf as J, diskBytesOf as K, resolveFeatures as L, Collector as M, DEFAULT_LARGE_FILE_THRESHOLD as N, compare as O, DEFAULT_STALE_AGE as P, joinRelative as Q, DEFAULT_CONCURRENCY as R, EXPLAIN_VERSION as S, explainSkips as T, Excluder as U, resolveScan as V, Scanner as W, scanError as X, rollUp as Y, comparePaths as Z, findConfigFile as _, renderComparisonCsv as a, formatBytes as at, validateConfig as b, renderAnalysis as c, VERSION as ct, escapeControlInLines as d, AbortError as dt, extensionOf as et, formatCount as f, DatError as ft, CONFIG_FILE_NAMES as g, supportsColor as h, renderAnalysisCsv as i, parseBudget as it, CANDIDATE_DIGESTS as j, compactAnalysis as k, renderComparison as l, parseDuration as lt, createStyle as m, errorMessage as mt, renderSkipsExplanation as n, evaluateBudgets as nt, renderAnalysisMarkdown as o, parseSize as ot, stringifyJson as p, errorCode as pt, passesFilters as q, renderAnalysisHtml as r, formatBudgetActual as rt, renderComparisonMarkdown as s, CATEGORIES as st, renderPathExplanation as t, BUDGET_METRICS as tt, escapeControl as u, parsePointInTime as ut, loadConfig as v, explainPath as w, DEFAULT_EXPLAIN_LIMIT as x, buildJsonSchema as y, assertDirectory as z };