dir-analysis-tool 3.5.3 → 3.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -253,7 +253,7 @@ build/keep/k.txt: excluded
253
253
  Note Git's global excludes file (core.excludesFile, usually ~/.config/git/ignore) is not read; Git may ignore more than dat does.
254
254
  ```
255
255
 
256
- Without a path, it runs one scan and groups everything left out by the rule that skipped it: default excludes, each exclude pattern, each `.gitignore` line, size and date filters, `--max-depth`, and symbolic links that were not followed. Counts are complete and equal `summary.excluded` and `summary.filtered` from `analyze`; each group lists its first 20 entries in path order.
256
+ Without a path, it runs one scan and groups everything left out by the rule that skipped it: default excludes, each exclude pattern, each `.gitignore` line, size and date filters, `--max-depth`, and symbolic links that were not followed. With `-L`, links that can't be followed are grouped by why: `ENOENT` (the target is missing) or `ELOOP` (the link loops); they count in `summary.symlinks`, not in `errors`, and the group's `code` field says which. Counts are complete and equal `summary.excluded` and `summary.filtered` from `analyze`; each group lists its first 20 entries in path order.
257
257
 
258
258
  ```text
259
259
  $ dat explain -g
@@ -280,7 +280,7 @@ Sizes inside skipped directories are unknown. Measure one with: dat <dir> --all
280
280
 
281
281
  All scan options are accepted, as are `--si`, `--color`, `--no-color`, `--no-progress`, and `-q`. The path is relative to the current directory and must be inside the root.
282
282
 
283
- - **Decisions:** `included`, `excluded` (a default, a pattern, `.gitignore`, or `.git/info/exclude`), `filtered` (size or date), `skipped` (beyond `--max-depth`, a symbolic link that is not followed, a socket or device, or an unreadable folder), and `not-found`. The exit code is `0` for all of them, so read `decision`; `1` means an error, such as a path outside the root.
283
+ - **Decisions:** `included`, `excluded` (a default, a pattern, `.gitignore`, or `.git/info/exclude`), `filtered` (size or date), `skipped` (beyond `--max-depth`, a symbolic link that is not followed or, with `-L`, leads nowhere, a socket or device, or an unreadable folder), and `not-found`. The exit code is `0` for all of them, so read `decision`; `1` means an error, such as a path outside the root.
284
284
  - **What it cannot know** is said, not guessed. dat never enters an excluded directory, so the size and count below one stay unknown (`descendants` is always `null`). Notes flag a negation that cannot work (`!build/keep/` under an ignored `build/`, `-e '!node_modules'`, or `-e '!x.log'` against a `.gitignore` rule), a scan root that Git ignores, nested repositories, matches that depend on the platform's case-insensitivity, and counts that depend on scan order (hard links, followed symlinks).
285
285
  - **Not read:** Git's global excludes file (`core.excludesFile`, usually `~/.config/git/ignore`). Every `-g` explanation inside a repository says so. A `.git` file, which links a worktree or submodule to its repository, is counted as an ordinary file, because default excludes only skip directories.
286
286
  - `--max-depth` skips are reported only here (`totals.depthSkipped`); `analyze` does not count them.
@@ -534,7 +534,7 @@ Then ask in your own words, for example "why is this repo so big?" or "fail CI i
534
534
  2. Files over 256 KiB are compared by a SHA-256 sample of their first and last 64 KiB.
535
535
  3. Remaining candidates are hashed in full: small files in a single read, large files streamed through reusable buffers. Each size group is finished as soon as its last file is hashed, so intermediate hash maps are retained only for groups in flight; candidates and results still use memory proportional to their count.
536
536
  - **Disk usage.** Sizes are apparent sizes (file lengths). `On disk` is the space allocated in blocks, which is what `du` reports.
537
- - **Determinism.** Results are sorted by size and then by path, so the same tree always produces the same output, whatever order the filesystem returned it in.
537
+ - **Determinism.** Results are sorted by size and then by path, so the same tree always produces the same output, whatever order the filesystem returned it in. Equal sizes are ordered by comparing paths where they first differ, without building them, so deep trees full of same-size files rank them as fast as shallow ones.
538
538
 
539
539
  **Benchmarks** (Apple M4, warm cache, best of three; measurements from the optimization work, not performance guarantees). On the Linux kernel source tree, 96,127 files and 1.53 GiB:
540
540
 
@@ -545,7 +545,7 @@ Then ask in your own words, for example "why is this repo so big?" or "fail CI i
545
545
  | Scan and find duplicates | 2.64 s | **1.20 s** | |
546
546
  | Peak heap while finding duplicates | 118 MB | **45 MB** | |
547
547
 
548
- On a synthetic tree of 1,000,000 files, v3.1 scans in 8.9 s where `du -s` takes 13 s. Compared with v2.0.7 on a 140,237-file tree, v3 scans about 3× faster and finds duplicates about 4× faster, with identical results. Run `pnpm bench` (or `pnpm bench <directory>`) to measure on your machine.
548
+ On a synthetic tree of 1,000,000 files, v3.1 scans in 8.9 s where `du -s` takes 13 s. On a 500-level chain of folders holding 2,000 files of one size, 3.5.5 scans in 44 ms where 3.5.4 took 90 ms (Linux in Docker on the same M4, median of nine), the same as with the largest-files list turned off. Compared with v2.0.7 on a 140,237-file tree, v3 scans about 3× faster and finds duplicates about 4× faster, with identical results. Run `pnpm bench` (or `pnpm bench <directory>`) to measure on your machine.
549
549
 
550
550
  The benchmark script reports scan and duplicate timings plus process peak RSS (not JavaScript heap). Results vary with storage, cache state, tree shape, and Node.js version. `du` measures allocated disk space and does not produce the same reports.
551
551
 
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $ as errorCode, C as MAX_EXPLAIN_LIMIT, D as outsideRootError, E as isOutside, F as listDirectories, G as formatBytes, J as VERSION, K as parseSize, L as Excluder, M as analyze, O as compare, P as assertDirectory, Q as DatError, R as joinRelative, T as explainSkips, U as formatBudgetActual, W as parseBudget, X as parsePointInTime, Z as AbortError, a as renderComparisonCsv, c as renderAnalysis, d as escapeControlInLines, et as errorMessage, f as formatCount, h as supportsColor, i as renderAnalysisCsv, k as compactAnalysis, l as renderComparison, m as createStyle, n as renderSkipsExplanation, o as renderAnalysisMarkdown, p as stringifyJson, r as renderAnalysisHtml, s as renderComparisonMarkdown, t as renderPathExplanation, u as escapeControl, v as loadConfig, w as explainPath } from "./shared-BJ-V9aTZ.js";
2
+ import { $ as errorCode, C as MAX_EXPLAIN_LIMIT, D as outsideRootError, E as isOutside, F as listDirectories, G as formatBytes, J as VERSION, K as parseSize, L as Excluder, M as analyze, O as compare, P as assertDirectory, Q as DatError, R as joinRelative, T as explainSkips, U as formatBudgetActual, W as parseBudget, X as parsePointInTime, Z as AbortError, a as renderComparisonCsv, c as renderAnalysis, d as escapeControlInLines, et as errorMessage, f as formatCount, h as supportsColor, i as renderAnalysisCsv, k as compactAnalysis, l as renderComparison, m as createStyle, n as renderSkipsExplanation, o as renderAnalysisMarkdown, p as stringifyJson, r as renderAnalysisHtml, s as renderComparisonMarkdown, t as renderPathExplanation, u as escapeControl, v as loadConfig, w as explainPath } from "./shared-15TspuKg.js";
3
3
  import { constants, existsSync, watch } from "node:fs";
4
4
  import { access, mkdir, realpath, stat, writeFile } from "node:fs/promises";
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
package/dist/index.d.ts CHANGED
@@ -475,6 +475,8 @@ interface ExplainGroup {
475
475
  rule: string | null;
476
476
  index: number | null;
477
477
  limit: number | string | null;
478
+ /** `symlink` with followSymlinks: `ENOENT` (target missing) or `ELOOP` (a loop); else `null`. */
479
+ code: string | null;
478
480
  count: number;
479
481
  /** The first entries in path order, at most `limit` of them. */
480
482
  entries: string[];
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { Z as AbortError, V as BUDGET_METRICS, q as CATEGORIES, g as CONFIG_FILE_NAMES, N as DEFAULT_CONCURRENCY, I as DEFAULT_EXCLUDES, x as DEFAULT_EXPLAIN_LIMIT, A as DEFAULT_LARGE_FILE_THRESHOLD, j as DEFAULT_STALE_AGE, Q as DatError, S as EXPLAIN_VERSION, C as MAX_EXPLAIN_LIMIT, J as VERSION, M as analyze, y as buildJsonSchema, z as classify, k as compactAnalysis, O as compare, m as createStyle, H as evaluateBudgets, w as explainPath, T as explainSkips, B as extensionOf, _ as findConfigFile, G as formatBytes, F as listDirectories, v as loadConfig, W as parseBudget, Y as parseDuration, X as parsePointInTime, K as parseSize, c as renderAnalysis, i as renderAnalysisCsv, r as renderAnalysisHtml, o as renderAnalysisMarkdown, l as renderComparison, a as renderComparisonCsv, s as renderComparisonMarkdown, t as renderPathExplanation, n as renderSkipsExplanation, b as validateConfig } from "./shared-BJ-V9aTZ.js";
1
+ export { Z as AbortError, V as BUDGET_METRICS, q as CATEGORIES, g as CONFIG_FILE_NAMES, N as DEFAULT_CONCURRENCY, I as DEFAULT_EXCLUDES, x as DEFAULT_EXPLAIN_LIMIT, A as DEFAULT_LARGE_FILE_THRESHOLD, j as DEFAULT_STALE_AGE, Q as DatError, S as EXPLAIN_VERSION, C as MAX_EXPLAIN_LIMIT, J as VERSION, M as analyze, y as buildJsonSchema, z as classify, k as compactAnalysis, O as compare, m as createStyle, H as evaluateBudgets, w as explainPath, T as explainSkips, B as extensionOf, _ as findConfigFile, G as formatBytes, F as listDirectories, v as loadConfig, W as parseBudget, Y as parseDuration, X as parsePointInTime, K as parseSize, c as renderAnalysis, i as renderAnalysisCsv, r as renderAnalysisHtml, o as renderAnalysisMarkdown, l as renderComparison, a as renderComparisonCsv, s as renderComparisonMarkdown, t as renderPathExplanation, n as renderSkipsExplanation, b as validateConfig } from "./shared-15TspuKg.js";
@@ -867,12 +867,19 @@ var Scanner = class {
867
867
  const onAbort = () => this.#limiter.abort(new AbortError());
868
868
  signal?.addEventListener("abort", onAbort, { once: true });
869
869
  try {
870
- this.#limiter.run(() => this.#scanDir(index, root, chain));
870
+ this.#limiter.run(() => this.#scanDir(index, root, chain, ""));
871
871
  await this.#limiter.idle();
872
872
  } finally {
873
873
  signal?.removeEventListener("abort", onAbort);
874
874
  }
875
875
  }
876
+ /**
877
+ * Orders two entries as {@link comparePaths} orders their relative paths,
878
+ * without building them. See {@link compareRelativePaths}.
879
+ */
880
+ compareRelative(dirA, nameA, dirB, nameB) {
881
+ return compareRelativePaths(this.dirs, dirA, nameA, dirB, nameB);
882
+ }
876
883
  /** Root-relative path of a directory (or of `name` inside it), with `/` separators. */
877
884
  relativePath(dirIndex, name) {
878
885
  const parts = name === void 0 ? [] : [name];
@@ -901,7 +908,12 @@ var Scanner = class {
901
908
  this.#visitor.directory?.(index, node);
902
909
  return index;
903
910
  }
904
- async #scanDir(index, absPath, inherited) {
911
+ /**
912
+ * @param relDir Root-relative path of the directory when the excluder
913
+ * matches paths (passed down from the parent, so it is never rebuilt
914
+ * from the root), and `''` otherwise.
915
+ */
916
+ async #scanDir(index, absPath, inherited, relDir) {
905
917
  const { excluder } = this.#options;
906
918
  let entries;
907
919
  try {
@@ -914,7 +926,6 @@ var Scanner = class {
914
926
  const node = this.dirs[index];
915
927
  node.entries = entries.length;
916
928
  if (entries.length === 0) return;
917
- const relDir = excluder.needsPaths ? this.relativePath(index) : "";
918
929
  let chain = inherited;
919
930
  if (excluder.gitignore && entries.some((e) => e.name === ".gitignore" && !e.isDirectory())) {
920
931
  const scope = await excluder.loadScope(joinNative(absPath, ".gitignore"), relDir);
@@ -922,6 +933,7 @@ var Scanner = class {
922
933
  }
923
934
  const base = absPath.endsWith(sep) ? absPath : absPath + sep;
924
935
  const checkExclusion = excluder.active;
936
+ const needsPaths = excluder.needsPaths;
925
937
  for (const entry of entries) {
926
938
  const name = entry.name;
927
939
  const isDirectory = entry.isDirectory();
@@ -929,9 +941,9 @@ var Scanner = class {
929
941
  const isSymlink = !isDirectory && !isFile && entry.isSymbolicLink();
930
942
  const isUnknown = !isDirectory && !isFile && !isSymlink && isUnknownType(entry);
931
943
  if (!isDirectory && !isFile && !isSymlink && !isUnknown) continue;
944
+ const rel = needsPaths ? relDir ? `${relDir}/${name}` : name : "";
932
945
  if (checkExclusion) {
933
- const rel = relDir ? `${relDir}/${name}` : name;
934
- if (excluder.isExcluded(rel, name, isDirectory, chain)) {
946
+ if (excluder.isExcluded(rel || name, name, isDirectory, chain)) {
935
947
  this.counters.excluded++;
936
948
  this.#options.onSkip?.({
937
949
  kind: "excluded",
@@ -945,12 +957,12 @@ var Scanner = class {
945
957
  }
946
958
  const fullPath = base + name;
947
959
  if (this.#options.directoriesOnly && !isDirectory) continue;
948
- if (isDirectory && !this.#options.followSymlinks) this.#enterDir(index, name, fullPath, chain);
960
+ if (isDirectory && !this.#options.followSymlinks) this.#enterDir(index, name, fullPath, chain, rel);
949
961
  else if (isFile) this.#limiter.run(() => this.#statFile(index, name, fullPath));
950
- else this.#limiter.run(() => this.#resolveEntry(index, name, fullPath, chain, isSymlink, isDirectory));
962
+ else this.#limiter.run(() => this.#resolveEntry(index, name, fullPath, chain, rel, isSymlink, isDirectory));
951
963
  }
952
964
  }
953
- #enterDir(parent, name, fullPath, chain) {
965
+ #enterDir(parent, name, fullPath, chain, relPath) {
954
966
  const depth = this.dirs[parent].depth + 1;
955
967
  if (depth > this.#options.maxDepth) {
956
968
  this.#options.onSkip?.({
@@ -962,7 +974,7 @@ var Scanner = class {
962
974
  return;
963
975
  }
964
976
  const child = this.#addDir(name, parent, depth);
965
- this.#limiter.run(() => this.#scanDir(child, fullPath, chain));
977
+ this.#limiter.run(() => this.#scanDir(child, fullPath, chain, relPath));
966
978
  }
967
979
  async #statFile(dirIndex, name, fullPath) {
968
980
  let stats;
@@ -979,7 +991,7 @@ var Scanner = class {
979
991
  * Handles symlinks, entries whose type the filesystem did not report, and
980
992
  * (when following symlinks) directories, which then need their identity.
981
993
  */
982
- async #resolveEntry(dirIndex, name, fullPath, chain, isSymlink, checkedAsDirectory) {
994
+ async #resolveEntry(dirIndex, name, fullPath, chain, relPath, isSymlink, checkedAsDirectory) {
983
995
  let stats;
984
996
  try {
985
997
  stats = await lstat(fullPath);
@@ -1000,6 +1012,12 @@ var Scanner = class {
1000
1012
  const code = errorCode(error);
1001
1013
  if (isSymlink && (code === "ENOENT" || code === "ELOOP")) {
1002
1014
  this.counters.symlinks++;
1015
+ this.#options.onSkip?.({
1016
+ kind: "broken-symlink",
1017
+ dir: dirIndex,
1018
+ name,
1019
+ code
1020
+ });
1003
1021
  return;
1004
1022
  }
1005
1023
  this.recordError(this.relativePath(dirIndex, name), error);
@@ -1009,8 +1027,7 @@ var Scanner = class {
1009
1027
  if (stats.isDirectory()) {
1010
1028
  const { excluder } = this.#options;
1011
1029
  if (excluder.active && !checkedAsDirectory) {
1012
- const rel = this.relativePath(dirIndex, name);
1013
- if (excluder.isExcluded(rel, name, true, chain)) {
1030
+ if (excluder.isExcluded(relPath || name, name, true, chain)) {
1014
1031
  this.counters.excluded++;
1015
1032
  this.#options.onSkip?.({
1016
1033
  kind: "excluded",
@@ -1025,7 +1042,7 @@ var Scanner = class {
1025
1042
  const key = await inodeKey(stats, fullPath);
1026
1043
  if (this.#seenDirs.has(key)) return;
1027
1044
  this.#seenDirs.add(key);
1028
- this.#enterDir(dirIndex, name, fullPath, chain);
1045
+ this.#enterDir(dirIndex, name, fullPath, chain, relPath);
1029
1046
  } else if (stats.isFile()) {
1030
1047
  const pending = this.#acceptFile(dirIndex, name, fullPath, stats);
1031
1048
  if (pending) await pending;
@@ -1109,6 +1126,59 @@ function rollUp(dirs) {
1109
1126
  }
1110
1127
  }
1111
1128
  }
1129
+ /** Code unit of the `/` that joins path segments. */
1130
+ const SLASH = 47;
1131
+ /**
1132
+ * Compares the root-relative paths of two entries, each a directory index
1133
+ * plus an optional name inside it. The result has the same sign as
1134
+ * `comparePaths(relativePath(dirA, nameA), relativePath(dirB, nameB))`.
1135
+ *
1136
+ * Building both paths costs O(depth) time and garbage on every call, which
1137
+ * made top-N tie-breaks on deep trees slow (#31). This walks parent indices
1138
+ * to the closest common directory instead, and compares only the first
1139
+ * segment where the paths part. That is not a segment-by-segment comparison:
1140
+ * when one segment is a prefix of the other, the shorter path continues with
1141
+ * `/` (or ends), and `/` sorts after characters such as `-` and `.`, exactly
1142
+ * as it does in the joined string.
1143
+ */
1144
+ function compareRelativePaths(dirs, dirA, nameA, dirB, nameB) {
1145
+ if (dirA === dirB) {
1146
+ if (nameA === void 0 || nameB === void 0) return nameA === nameB ? 0 : nameA === void 0 ? -1 : 1;
1147
+ return nameA < nameB ? -1 : nameA > nameB ? 1 : 0;
1148
+ }
1149
+ let a = dirA;
1150
+ let b = dirB;
1151
+ let belowA = -1;
1152
+ let belowB = -1;
1153
+ while (dirs[a].depth > dirs[b].depth) {
1154
+ belowA = a;
1155
+ a = dirs[a].parent;
1156
+ }
1157
+ while (dirs[b].depth > dirs[a].depth) {
1158
+ belowB = b;
1159
+ b = dirs[b].parent;
1160
+ }
1161
+ while (a !== b) {
1162
+ belowA = a;
1163
+ a = dirs[a].parent;
1164
+ belowB = b;
1165
+ b = dirs[b].parent;
1166
+ }
1167
+ const segmentA = belowA === -1 ? nameA : dirs[belowA].name;
1168
+ const segmentB = belowB === -1 ? nameB : dirs[belowB].name;
1169
+ if (segmentA === void 0) return segmentB === void 0 ? 0 : -1;
1170
+ if (segmentB === void 0) return 1;
1171
+ const length = Math.min(segmentA.length, segmentB.length);
1172
+ for (let i = 0; i < length; i++) {
1173
+ const diff = segmentA.charCodeAt(i) - segmentB.charCodeAt(i);
1174
+ if (diff !== 0) return diff;
1175
+ }
1176
+ return nextCode(segmentA, length, belowA !== -1 && (belowA !== dirA || nameA !== void 0)) - nextCode(segmentB, length, belowB !== -1 && (belowB !== dirB || nameB !== void 0));
1177
+ }
1178
+ function nextCode(segment, at, continues) {
1179
+ if (at < segment.length) return segment.charCodeAt(at);
1180
+ return continues ? SLASH : -1;
1181
+ }
1112
1182
  /**
1113
1183
  * `dev:ino` identity of a file or directory. `Stats.ino` is a Number, which is
1114
1184
  * exact only up to 2^53; Windows NTFS file IDs keep a sequence number in their
@@ -2357,7 +2427,7 @@ var Collector = class {
2357
2427
  if (this.#scanner.dirs[dir].depth < features.tree.depth) {
2358
2428
  let heap = this.#treeFiles.get(dir);
2359
2429
  if (!heap) {
2360
- heap = new TopK(features.tree.limit, (a, b) => a.name.localeCompare(b.name));
2430
+ heap = new TopK(features.tree.limit, (a, b) => comparePaths(a.name, b.name));
2361
2431
  this.#treeFiles.set(dir, heap);
2362
2432
  }
2363
2433
  if (heap.accepts(bytes)) heap.push(bytes, makeRef());
@@ -2452,7 +2522,7 @@ var Collector = class {
2452
2522
  extensions: [...this.#extensions].map(([extension, stat]) => ({
2453
2523
  extension,
2454
2524
  ...stat
2455
- })).sort((a, b) => b.bytes - a.bytes || b.files - a.files || a.extension.localeCompare(b.extension)),
2525
+ })).sort((a, b) => b.bytes - a.bytes || b.files - a.files || comparePaths(a.extension, b.extension)),
2456
2526
  largestDirectories: this.#largestDirectories(scanner),
2457
2527
  largestFiles: this.#topFiles.sorted().map(toEntry),
2458
2528
  errors: [...scanner.errors].sort((a, b) => comparePaths(a.path, b.path))
@@ -2487,7 +2557,7 @@ var Collector = class {
2487
2557
  return result;
2488
2558
  }
2489
2559
  #largestDirectories(scanner) {
2490
- const top = new TopK(this.#features.top, (a, b) => comparePaths(scanner.relativePath(a), scanner.relativePath(b)));
2560
+ const top = new TopK(this.#features.top, (a, b) => scanner.compareRelative(a, void 0, b, void 0));
2491
2561
  const dirs = scanner.dirs;
2492
2562
  for (let i = 1; i < dirs.length; i++) {
2493
2563
  const node = dirs[i];
@@ -2533,7 +2603,7 @@ var Collector = class {
2533
2603
  };
2534
2604
  }
2535
2605
  });
2536
- candidates.sort((a, b) => b.bytes - a.bytes || a.key.localeCompare(b.key));
2606
+ candidates.sort((a, b) => b.bytes - a.bytes || comparePaths(a.key, b.key));
2537
2607
  const shown = candidates.slice(0, limit);
2538
2608
  result.children = shown.map((c) => c.build());
2539
2609
  const omittedEntries = (subdirs?.length ?? 0) + node.ownFiles - shown.length;
@@ -2552,9 +2622,9 @@ var Collector = class {
2552
2622
  }
2553
2623
  return result;
2554
2624
  }
2625
+ /** Ties in the largest-files heap: path order, without building the paths (#31). */
2555
2626
  #compareRefs(a, b) {
2556
- const scanner = this.#scanner;
2557
- return comparePaths(scanner.relativePath(a.dir, a.name), scanner.relativePath(b.dir, b.name));
2627
+ return this.#scanner.compareRelative(a.dir, a.name, b.dir, b.name);
2558
2628
  }
2559
2629
  };
2560
2630
  function createProgressReporter(report, interval, snapshot) {
@@ -3416,7 +3486,8 @@ async function explainSkips(root, options = {}) {
3416
3486
  line: null,
3417
3487
  rule: null,
3418
3488
  index: null,
3419
- limit: null
3489
+ limit: null,
3490
+ code: null
3420
3491
  });
3421
3492
  let scanner = null;
3422
3493
  const onSkip = (event) => {
@@ -3474,6 +3545,12 @@ async function explainSkips(root, options = {}) {
3474
3545
  case "symlink":
3475
3546
  groupFor("symlink", () => base("symlink")).add(rel);
3476
3547
  return;
3548
+ case "broken-symlink":
3549
+ groupFor(`symlink\0${event.code}`, () => ({
3550
+ ...base("symlink"),
3551
+ code: event.code
3552
+ })).add(rel);
3553
+ return;
3477
3554
  }
3478
3555
  };
3479
3556
  scanner = new Scanner({
@@ -3500,7 +3577,7 @@ async function explainSkips(root, options = {}) {
3500
3577
  count: sample.count,
3501
3578
  entries: sample.items,
3502
3579
  truncated: sample.count > sample.items.length
3503
- })).toSorted((a, b) => b.count - a.count || SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source) || comparePaths(a.file ?? "", b.file ?? "") || (a.line ?? 0) - (b.line ?? 0) || (a.index ?? 0) - (b.index ?? 0) || comparePaths(a.rule ?? "", b.rule ?? ""));
3580
+ })).toSorted((a, b) => b.count - a.count || SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source) || comparePaths(a.file ?? "", b.file ?? "") || (a.line ?? 0) - (b.line ?? 0) || (a.index ?? 0) - (b.index ?? 0) || comparePaths(a.rule ?? "", b.rule ?? "") || comparePaths(a.code ?? "", b.code ?? ""));
3504
3581
  return {
3505
3582
  explainVersion: 1,
3506
3583
  root: absRoot,
@@ -4864,7 +4941,7 @@ function ruleLabel(group, units) {
4864
4941
  case "size": return `${flagOf(group.rule)} ${sizeOf(group.limit, units)}`;
4865
4942
  case "date": return `${flagOf(group.rule)} ${String(group.limit)}`;
4866
4943
  case "max-depth": return `--max-depth ${String(group.limit)}`;
4867
- case "symlink": return "symbolic links (not followed)";
4944
+ case "symlink": return group.code === null ? "symbolic links (not followed)" : group.code === "ELOOP" ? `symbolic links in a loop (${group.code})` : `symbolic links to nothing (${escapeControl(group.code)})`;
4868
4945
  case "special-file": return "special files";
4869
4946
  case "error": return "unreadable";
4870
4947
  case "unknown": return "no single rule identified";
@@ -4896,7 +4973,7 @@ function reasonLines(reason, units, s) {
4896
4973
  rows.push(["Rule", `--max-depth ${String(reason.limit)}; ${at} is at depth ${String(reason.actual)}`]);
4897
4974
  break;
4898
4975
  case "symlink":
4899
- rows.push(["Rule", reason.code ? `symbolic link to nothing (${reason.code}); counted, not followed` : "symbolic link; counted, not followed (use -L to follow)"]);
4976
+ rows.push(["Rule", reason.code === "ELOOP" ? `symbolic link in a loop (${reason.code}); counted, not followed` : reason.code ? `symbolic link to nothing (${escapeControl(reason.code)}); counted, not followed` : "symbolic link; counted, not followed (use -L to follow)"]);
4900
4977
  break;
4901
4978
  case "special-file":
4902
4979
  rows.push(["Rule", "special file (socket, FIFO, or device); never counted"]);
@@ -4946,8 +5023,11 @@ function renderSkipsExplanation(result, options = {}) {
4946
5023
  if (totals.excluded > 0) parts.push(`${plural(totals.excluded, "entry", "entries")} excluded`);
4947
5024
  if (totals.filtered > 0) parts.push(`${plural(totals.filtered, "file")} filtered`);
4948
5025
  if (totals.depthSkipped > 0) parts.push(`${plural(totals.depthSkipped, "directory", "directories")} beyond --max-depth`);
4949
- const unfollowed = result.groups.find((g) => g.source === "symlink")?.count ?? 0;
5026
+ const links = result.groups.filter((g) => g.source === "symlink");
5027
+ const unfollowed = links.find((g) => g.code === null)?.count ?? 0;
5028
+ const broken = links.reduce((sum, g) => sum + (g.code === null ? 0 : g.count), 0);
4950
5029
  if (unfollowed > 0) parts.push(`${plural(unfollowed, "symbolic link")} not followed`);
5030
+ if (broken > 0) parts.push(plural(broken, "broken symbolic link"));
4951
5031
  if (totals.errors > 0) parts.push(`${plural(totals.errors, "entry", "entries")} unreadable`);
4952
5032
  const lines = [];
4953
5033
  lines.push(parts.length > 0 ? s.bold(`Skipped: ${parts.join(", ")}`) : s.bold("Nothing was skipped: every entry is counted."));
@@ -4970,7 +5050,8 @@ function renderSkipsExplanation(result, options = {}) {
4970
5050
  for (const error of result.errors) lines.push(` ${fitPath(error.path, width - 20)} ${s.dim(error.code)}`);
4971
5051
  }
4972
5052
  const notes = result.notes.map(noteText);
4973
- if (result.groups.some((g) => g.source !== "size" && g.source !== "date")) notes.push("Sizes inside skipped directories are unknown. Measure one with: dat <dir> --all");
5053
+ const skipsDirectories = (g) => g.source !== "size" && g.source !== "date" && !(g.source === "symlink" && g.code !== null);
5054
+ if (result.groups.some(skipsDirectories)) notes.push("Sizes inside skipped directories are unknown. Measure one with: dat <dir> --all");
4974
5055
  if (notes.length > 0) {
4975
5056
  lines.push("");
4976
5057
  for (const note of notes) lines.push(s.dim(note));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dir-analysis-tool",
3
- "version": "3.5.3",
3
+ "version": "3.5.5",
4
4
  "description": "Fast, zero-dependency directory analysis for your terminal and CI: largest folders and files, type and extension breakdowns, staged duplicate detection, size budgets, directory diffs, and self-contained HTML, Markdown, JSON, and CSV reports.",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1012,6 +1012,10 @@
1012
1012
  "limit": {
1013
1013
  "type": ["number", "string", "null"]
1014
1014
  },
1015
+ "code": {
1016
+ "type": ["string", "null"],
1017
+ "description": "For a symlink group with --follow-symlinks: ENOENT (the target is missing) or ELOOP (the link loops). Null otherwise. Added in 3.5.4."
1018
+ },
1015
1019
  "count": {
1016
1020
  "type": "integer",
1017
1021
  "minimum": 0