dir-analysis-tool 3.5.8 → 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.
package/README.md CHANGED
@@ -233,6 +233,7 @@ A size tree (`dat src -t --tree-depth 2`):
233
233
  | `--content` | Also compare same-sized files by content, byte by byte, stopping at the first difference. By default, files are compared by size. |
234
234
  | `-n, --top <n>` | Items per list. Default `10`; `0` lists no files and keeps the counts. JSON and CSV list every added, removed and changed file; the changed-folders list follows `--top` in every format. |
235
235
  | `-f, --format <format>` | `pretty`, `json`, `markdown`, or `csv`. |
236
+ | `--compact` | One-line JSON with the added, removed and changed lists cut to `--top` items (3.6 or later). See [Compact JSON](#compact-json). |
236
237
 
237
238
  All scan options and shared output options above are accepted too; `--html`, `--csv`, and HTML format are analyze-only. Use `--format csv` to export a comparison.
238
239
 
@@ -281,7 +282,7 @@ Sizes inside skipped directories are unknown. Measure one with: dat <dir> --all
281
282
  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
283
 
283
284
  - **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
- - **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
+ - **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 data reached by several paths (hard links, followed symlinks), which is counted once under a fixed path: the real path first, then the path that sorts first. The codes `hardlink-order-dependent` and `symlink-order-dependent` keep their names from before 3.6, when that choice depended on scan order.
285
286
  - **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
287
  - `--max-depth` skips are reported only here (`totals.depthSkipped`); `analyze` does not count them.
287
288
 
@@ -430,7 +431,13 @@ Large trees can produce very long lists, mostly duplicate groups: 650 KB of JSON
430
431
  - **Lists that are cut:** `extensions`, the `items` of `largeFiles`, `duplicates`, `emptyFiles`, `emptyDirectories`, and `staleFiles`, the `files` of each listed duplicate group, and `errors` (counted against `summary.errors`). `largestFiles` and `largestDirectories` follow `--top` as always, and the tree keeps its own `omitted`.
431
432
  - **Follow up** with a focused scan when you need more: `dat . -d --compact -n 50` for more items, `dat . -d -n 0 --json | jq .duplicates` for one full section, `dat ./assets -d --compact` for a smaller scope, and `dat explain` for what was skipped.
432
433
 
433
- `--compact` implies `--json` and cannot be combined with another `--format`. Without it, JSON output is unchanged.
434
+ **Comparisons** (3.6 or later). `dat compare <left> <right> --compact` does the same for a comparison: the `items` of `added`, `removed`, and `changed` are cut to the limit, while both sides' `summary` and `types`, `delta`, `unchanged`, and every `count`, `bytes`, and `delta` stay complete. `directories` already follows `--top`. Comparing an empty folder with a `node_modules` folder of 17,412 files gives 3.2 MB of JSON, or 4.5 KB with `--compact`:
435
+
436
+ ```jsonc
437
+ "compact": { "limit": 10, "truncated": true, "omitted": { "added.items": 17402 } }
438
+ ```
439
+
440
+ `--compact` implies `--json` and cannot be combined with another `--format`. Without it, JSON output is unchanged. It is a flag rather than a config key, so a config file never turns a person's report into JSON.
434
441
 
435
442
  Optional sections appear only when their report is on: `largeFiles`, `duplicates`, `emptyFiles`, `emptyDirectories`, `staleFiles`, `tree`, and `budgets`.
436
443
 
@@ -505,6 +512,7 @@ await writeFile('report.md', renderAnalysisMarkdown(result));
505
512
  | `analyze(path, options?)` | Analyze a tree. Options mirror the CLI flags: `exclude`, `gitignore`, `maxDepth`, `minSize`, `modifiedAfter`, `top`, `largeFiles`, `duplicates`, `empty`, `stale`, `tree`, `budgets`, `concurrency`, `signal`, `onProgress`, and more. |
506
513
  | `compare(left, right, options?)` | Diff two trees. |
507
514
  | `compactAnalysis(result, { limit })` | The `--compact` form of a result: lists cut to `limit`, totals kept, cuts listed in `compact`. Returns a new object. |
515
+ | `compactComparison(result, { limit })` | The same for a comparison (`compare --compact`): `added`, `removed`, and `changed` items cut to `limit`, totals kept. Returns a new object. |
508
516
  | `listDirectories(path, options?)` | The folders a scan would enter. |
509
517
  | `explainPath(root, path, options?)`, `explainSkips(root, options?)` | Why a scan counts or skips one path, and everything a scan skips grouped by rule (`limit` caps listed entries). Render with `renderPathExplanation` and `renderSkipsExplanation`. |
510
518
  | `renderAnalysis`, `renderAnalysisMarkdown`, `renderAnalysisCsv`, `renderAnalysisHtml` | Render a result in any format. `renderComparison*` does the same for comparisons. |
@@ -529,7 +537,7 @@ Then ask in your own words, for example "why is this repo so big?" or "fail CI i
529
537
 
530
538
  - **Scanning.** Directories are read with `readdir({ withFileTypes })`, so they never need a `stat`, and each regular file is `lstat`ed once. All filesystem calls go through one concurrency limiter (32 operations in flight by default), so no tree, however wide, can exhaust file handles. Work is scheduled depth-first to keep the queue small.
531
539
  - **Patterns.** Exclude patterns and `.gitignore` files are compiled by a built-in matcher: consecutive rules become a few regular expressions, and plain names and `*.ext` rules are resolved with hash lookups, reducing pattern-matching overhead without caching results per path. Rules with several wildcards use a matcher whose time grows linearly with the path length, so an unusual `.gitignore` cannot stall a scan.
532
- - **Memory.** Totals, type and extension statistics, folder sizes, and the top-N lists are computed while scanning; the lists use bounded heaps. Reports you opt into keep only what they match. Duplicate detection keeps one small record per file that shares its size with another.
540
+ - **Memory.** Totals, type and extension statistics, folder sizes, and the top-N lists are computed while scanning; the lists use bounded heaps. Reports you opt into keep only what they match. Duplicate detection keeps one small record per file that shares its size with another. A file with several hard links (and, with `-L`, one reached through a symlink) is held as a small record until the walk ends, so it can be counted under a fixed path.
533
541
  - **Largest folders.** Folders are ranked by the total size below them. A folder whose size comes almost entirely (95% or more) from one subfolder is folded into that subfolder, so the list points to where the data actually lives instead of repeating every parent.
534
542
  - **Duplicates,** in stages so most files are never read in full:
535
543
  1. Only sizes shared by at least two files are considered. Empty files are excluded, and hard links to the same data are not copies.
@@ -538,7 +546,7 @@ Then ask in your own words, for example "why is this repo so big?" or "fail CI i
538
546
  - **Comparing contents.** `dat compare --content` reads each pair of same-size files side by side, in 256 KiB chunks through a fixed set of reusable buffers, and stops at the first byte that differs. No hash is computed, and the comparison itself uses a fixed amount of memory however large the files are.
539
547
  - **Watching.** `dat watch` keeps a collector per folder and builds each report by merging them with the same code a full scan uses, so the two can't drift apart. A change re-reads the folders it touched and scans any new subfolder; hard links are counted once, under the link whose path sorts first.
540
548
  - **Disk usage.** Sizes are apparent sizes (file lengths). `On disk` is the space allocated in blocks, which is what `du` reports.
541
- - **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.
549
+ - **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. Data that several paths lead to is counted once under a fixed path: a hard-linked file under the link whose path sorts first, and with `-L` a folder or file through its real path when there is one, otherwise through the symlink whose path sorts first (3.6 or later; before, the first path the scan reached). 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.
542
550
 
543
551
  **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:
544
552
 
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { A as CANDIDATE_DIGESTS, B as resolveScan, C as MAX_EXPLAIN_LIMIT, D as outsideRootError, E as isOutside, F as createProgressReporter, G as diskBytesOf, H as Excluder, I as resolveFeatures, J as rollUp, K as passesFilters, O as compare, P as analyze, R as assertDirectory, T as explainSkips, U as Scanner, W as compareRelativePaths, X as comparePaths, Y as scanError, Z as joinRelative, a as renderComparisonCsv, at as parseSize, c as renderAnalysis, d as escapeControlInLines, dt as DatError, f as formatCount, ft as errorCode, h as supportsColor, i as renderAnalysisCsv, it as formatBytes, j as Collector, k as compactAnalysis, l as renderComparison, lt as parsePointInTime, m as createStyle, n as renderSkipsExplanation, nt as formatBudgetActual, o as renderAnalysisMarkdown, p as stringifyJson, pt as errorMessage, q as relativePathOf, r as renderAnalysisHtml, rt as parseBudget, s as renderComparisonMarkdown, st as VERSION, t as renderPathExplanation, tt as evaluateBudgets, u as escapeControl, ut as AbortError, v as loadConfig, w as explainPath, z as listDirectories } from "./shared-BCvVJ4Tm.js";
2
+ import { A as compactComparison, B as listDirectories, C as MAX_EXPLAIN_LIMIT, D as outsideRootError, E as isOutside, F as analyze, G as compareRelativePaths, I as createProgressReporter, J as relativePathOf, K as diskBytesOf, L as resolveFeatures, M as Collector, O as compare, Q as joinRelative, T as explainSkips, U as Excluder, V as resolveScan, W as Scanner, X as scanError, Y as rollUp, Z as comparePaths, a as renderComparisonCsv, at as formatBytes, c as renderAnalysis, ct as VERSION, d as escapeControlInLines, dt as AbortError, f as formatCount, ft as DatError, h as supportsColor, i as renderAnalysisCsv, it as parseBudget, j as CANDIDATE_DIGESTS, k as compactAnalysis, l as renderComparison, m as createStyle, mt as errorMessage, n as renderSkipsExplanation, nt as evaluateBudgets, o as renderAnalysisMarkdown, ot as parseSize, p as stringifyJson, pt as errorCode, q as passesFilters, r as renderAnalysisHtml, rt as formatBudgetActual, s as renderComparisonMarkdown, t as renderPathExplanation, u as escapeControl, ut as parsePointInTime, v as loadConfig, w as explainPath, z as assertDirectory } from "./shared-CR5IVm-D.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";
@@ -746,7 +746,7 @@ function addReportOptions(command) {
746
746
  function addOutputOptions(command, formats = FORMATS) {
747
747
  return command.addOption(option("-f, --format <format>", "output format", OUTPUT_GROUP).choices(formats)).addOption(option("-j, --json", "same as --format json", OUTPUT_GROUP)).addOption(option("-o, --output <file>", "write the report to a file instead of stdout", OUTPUT_GROUP)).addOption(option("--si", "use decimal units (kB, MB) instead of binary (KiB, MiB)", OUTPUT_GROUP)).addOption(option("--color", "force colors", OUTPUT_GROUP)).addOption(option("--no-color", "disable colors (also honors NO_COLOR)", OUTPUT_GROUP)).addOption(option("--no-progress", "hide the progress line", OUTPUT_GROUP)).addOption(option("-q, --quiet", "print only the report and errors", OUTPUT_GROUP));
748
748
  }
749
- /** Bounded JSON for scripts and agents. Analyze only. */
749
+ /** Bounded JSON for scripts and agents (analyze and compare). */
750
750
  function addCompactOption(command) {
751
751
  return command.addOption(option("--compact", "print one-line JSON with every list cut to --top items (implies --json)", OUTPUT_GROUP));
752
752
  }
@@ -1000,17 +1000,19 @@ Examples:
1000
1000
  $ dat compare ./a ./b --content also detect same-size content changes
1001
1001
  $ dat compare old new -f markdown a table for a pull request comment
1002
1002
  $ dat compare old new --json | jq .delta
1003
+ $ dat compare old new --compact bounded one-line JSON for scripts and agents
1003
1004
  `;
1004
1005
  function registerCompare(program, ctx) {
1005
1006
  const command = program.command("compare").description("compare two directories: added, removed, and changed files, and size changes").argument("<left>", "the baseline directory").argument("<right>", "the directory to compare against the baseline");
1006
1007
  addScanOptions(command);
1007
- command.addOption(new Option("--content", "compare same-size files by content, byte by byte").helpGroup("Report options:")).addOption(new Option("-n, --top <n>", "items per list (default: 10; 0 lists none); JSON and CSV list every file").argParser(integer(0)).helpGroup("Report options:"));
1008
+ command.addOption(new Option("--content", "compare same-size files by content, byte by byte").helpGroup("Report options:")).addOption(new Option("-n, --top <n>", "items per list (default: 10; 0 lists none); JSON and CSV list every file, --compact cuts them to this many (10 with 0)").argParser(integer(0)).helpGroup("Report options:"));
1008
1009
  addOutputOptions(command, [
1009
1010
  "pretty",
1010
1011
  "json",
1011
1012
  "markdown",
1012
1013
  "csv"
1013
1014
  ]);
1015
+ addCompactOption(command);
1014
1016
  command.addHelpText("after", EXAMPLES$2);
1015
1017
  command.action(async (left, right, _options, cmd) => {
1016
1018
  const cli = explicitOptions(cmd);
@@ -1031,7 +1033,7 @@ function registerCompare(program, ctx) {
1031
1033
  } finally {
1032
1034
  progress.clear();
1033
1035
  }
1034
- const text = renderComparisonAs(display.format, result, {
1036
+ const text = display.compact ? stringifyJson(compactComparison(result, { limit: listLimit(top) })) : renderComparisonAs(display.format, result, {
1035
1037
  style: ctx.outputStyle(display.color, display.output !== void 0),
1036
1038
  units: display.units,
1037
1039
  width: terminalWidth(ctx.io),
package/dist/index.d.ts CHANGED
@@ -179,7 +179,13 @@ export interface AnalysisResult {
179
179
  }
180
180
  /** Lists that compact output can cut, named by their JSON path. */
181
181
  export type CompactList = "extensions" | "errors" | "largeFiles.items" | "duplicates.items" | "duplicates.items[].files" | "emptyFiles.items" | "emptyDirectories.items" | "staleFiles.items";
182
- export interface CompactInfo {
182
+ /** Lists that compact comparison output can cut, named by their JSON path. */
183
+ export type ComparisonCompactList = "added.items" | "removed.items" | "changed.items";
184
+ /**
185
+ * What compact output cut. `List` names the lists that can be cut:
186
+ * {@link CompactList} for an analysis, {@link ComparisonCompactList} for a comparison.
187
+ */
188
+ export interface CompactInfo<List extends string = CompactList> {
183
189
  /** Maximum number of items kept in each list. */
184
190
  limit: number;
185
191
  /** Whether any list was cut. */
@@ -188,7 +194,7 @@ export interface CompactInfo {
188
194
  * Items not listed, per cut list, in document order. A list that is absent
189
195
  * here was not cut. `duplicates.items[].files` is the sum over listed groups.
190
196
  */
191
- omitted: Partial<Record<CompactList, number>>;
197
+ omitted: Partial<Record<List, number>>;
192
198
  }
193
199
  export interface ChangedFile {
194
200
  path: string;
@@ -222,7 +228,7 @@ export interface ComparisonResult {
222
228
  files: number;
223
229
  directories: number;
224
230
  };
225
- /** Every added file, whatever `top` is; the CLI cuts only pretty and Markdown output. */
231
+ /** Every added file, whatever `top` is; the CLI cuts pretty, Markdown and compact output. */
226
232
  added: ItemList<FileEntry>;
227
233
  /** Every removed file, whatever `top` is. */
228
234
  removed: ItemList<FileEntry>;
@@ -235,6 +241,8 @@ export interface ComparisonResult {
235
241
  unchanged: number;
236
242
  /** At most `top` directories with the largest size change, largest absolute change first. */
237
243
  directories: DirectoryDelta[];
244
+ /** Present only in compact output (`compare --compact`, `compactComparison`): what was cut. */
245
+ compact?: CompactInfo<ComparisonCompactList>;
238
246
  }
239
247
  /** A feature a metric depends on; requesting the metric turns the feature on. */
240
248
  type BudgetFeature = "largeFiles" | "duplicates" | "empty" | "stale";
@@ -371,6 +379,16 @@ interface CompactOptions {
371
379
  * already bounded by `top` or by the tree's own per-folder limit.
372
380
  */
373
381
  export declare function compactAnalysis(result: AnalysisResult, options: CompactOptions): AnalysisResult;
382
+ /**
383
+ * Bounds the file lists of a comparison to `limit` items, as
384
+ * {@link compactAnalysis} does for an analysis. Counts, sizes and deltas stay
385
+ * the full totals; what was cut is listed in `compact.omitted`. Returns a new
386
+ * result and leaves the input untouched.
387
+ *
388
+ * Cut: the `items` of `added`, `removed`, and `changed`. Not cut: the sides'
389
+ * summaries and types, `delta`, and `directories`, which `top` already bounds.
390
+ */
391
+ export declare function compactComparison(result: ComparisonResult, options: CompactOptions): ComparisonResult;
374
392
  interface CompareOptions extends ScanSettings {
375
393
  /**
376
394
  * Also compare the contents of same-sized files, byte by byte. Default: `false`, size only.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { ut as AbortError, et as BUDGET_METRICS, ot as CATEGORIES, g as CONFIG_FILE_NAMES, L as DEFAULT_CONCURRENCY, V as DEFAULT_EXCLUDES, x as DEFAULT_EXPLAIN_LIMIT, M as DEFAULT_LARGE_FILE_THRESHOLD, N as DEFAULT_STALE_AGE, dt as DatError, S as EXPLAIN_VERSION, C as MAX_EXPLAIN_LIMIT, st as VERSION, P as analyze, y as buildJsonSchema, Q as classify, k as compactAnalysis, O as compare, m as createStyle, tt as evaluateBudgets, w as explainPath, T as explainSkips, $ as extensionOf, _ as findConfigFile, it as formatBytes, z as listDirectories, v as loadConfig, rt as parseBudget, ct as parseDuration, lt as parsePointInTime, at 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-BCvVJ4Tm.js";
1
+ export { dt as AbortError, tt as BUDGET_METRICS, st as CATEGORIES, g as CONFIG_FILE_NAMES, R as DEFAULT_CONCURRENCY, H as DEFAULT_EXCLUDES, x as DEFAULT_EXPLAIN_LIMIT, N as DEFAULT_LARGE_FILE_THRESHOLD, P as DEFAULT_STALE_AGE, ft as DatError, S as EXPLAIN_VERSION, C as MAX_EXPLAIN_LIMIT, ct as VERSION, F as analyze, y as buildJsonSchema, $ as classify, k as compactAnalysis, A as compactComparison, O as compare, m as createStyle, nt as evaluateBudgets, w as explainPath, T as explainSkips, et as extensionOf, _ as findConfigFile, at as formatBytes, B as listDirectories, v as loadConfig, it as parseBudget, lt as parseDuration, ut as parsePointInTime, ot 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-CR5IVm-D.js";
@@ -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;
@@ -1082,6 +1161,8 @@ var Scanner = class {
1082
1161
  try {
1083
1162
  this.#limiter.run(() => this.#scanDir(index, root, chain, this.#options.excluder.needsPaths ? relRoot : ""));
1084
1163
  await this.#limiter.idle();
1164
+ await this.#enterLinkedDirs();
1165
+ this.#countLinkedFiles();
1085
1166
  } finally {
1086
1167
  signal?.removeEventListener("abort", onAbort);
1087
1168
  }
@@ -1093,6 +1174,39 @@ var Scanner = class {
1093
1174
  compareRelative(dirA, nameA, dirB, nameB) {
1094
1175
  return compareRelativePaths(this.dirs, dirA, nameA, dirB, nameB);
1095
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
+ }
1096
1210
  /** Root-relative path of a directory (or of `name` inside it), with `/` separators. */
1097
1211
  relativePath(dirIndex, name) {
1098
1212
  return relativePathOf(this.dirs, dirIndex, name);
@@ -1255,11 +1369,22 @@ var Scanner = class {
1255
1369
  }
1256
1370
  }
1257
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
+ }
1258
1383
  if (this.#seenDirs.has(key)) return;
1259
1384
  this.#seenDirs.add(key);
1260
1385
  this.#enterDir(dirIndex, name, fullPath, chain, relPath);
1261
1386
  } else if (stats.isFile()) {
1262
- const pending = this.#acceptFile(dirIndex, name, fullPath, stats);
1387
+ const pending = this.#acceptFile(dirIndex, name, fullPath, stats, isSymlink);
1263
1388
  if (pending) await pending;
1264
1389
  }
1265
1390
  }
@@ -1267,7 +1392,7 @@ var Scanner = class {
1267
1392
  * Counts a file once per underlying data. Synchronous unless the file's
1268
1393
  * identity needs an exact (bigint) stat; see `inodeKey`.
1269
1394
  */
1270
- #acceptFile(dirIndex, name, fullPath, stats) {
1395
+ #acceptFile(dirIndex, name, fullPath, stats, viaSymlink = false) {
1271
1396
  const onLinked = this.#options.onLinkedFile;
1272
1397
  if (onLinked && !this.#options.countHardlinks && stats.nlink > 1) {
1273
1398
  const key = inodeKey(stats, fullPath);
@@ -1277,19 +1402,26 @@ var Scanner = class {
1277
1402
  }
1278
1403
  if (!this.#options.countHardlinks && (stats.nlink > 1 || this.#options.followSymlinks)) {
1279
1404
  const key = inodeKey(stats, fullPath);
1280
- if (typeof key !== "string") return key.then((exact) => this.#acceptKeyedFile(dirIndex, name, stats, exact));
1281
- 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);
1282
1407
  return;
1283
1408
  }
1284
1409
  this.#countFile(dirIndex, name, stats);
1285
1410
  }
1286
- #acceptKeyedFile(dirIndex, name, stats, key) {
1287
- if (this.#seenInodes.has(key)) {
1288
- 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);
1289
1415
  return;
1290
1416
  }
1291
- this.#seenInodes.add(key);
1292
- 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);
1293
1425
  }
1294
1426
  #countFile(dirIndex, name, stats) {
1295
1427
  const size = stats.size;
@@ -3108,8 +3240,7 @@ function createProgressReporter(report, interval, snapshot) {
3108
3240
  * already bounded by `top` or by the tree's own per-folder limit.
3109
3241
  */
3110
3242
  function compactAnalysis(result, options) {
3111
- const { limit } = options;
3112
- 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);
3113
3244
  const previous = result.compact?.omitted ?? {};
3114
3245
  const cuts = [];
3115
3246
  const note = (list, total, shown) => {
@@ -3182,6 +3313,52 @@ function compactAnalysis(result, options) {
3182
3313
  };
3183
3314
  return out;
3184
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
+ }
3185
3362
  // src/core/compare.ts
3186
3363
  const PASS_THROUGH_SHARE = .95;
3187
3364
  /** Records every file by its root-relative path, for diffing. */
@@ -3625,14 +3802,14 @@ function nestedRepositoryNote(path) {
3625
3802
  function hardlinkNote(path) {
3626
3803
  return {
3627
3804
  code: "hardlink-order-dependent",
3628
- 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.",
3629
3806
  ...path === void 0 ? {} : { path }
3630
3807
  };
3631
3808
  }
3632
3809
  function symlinkOrderNote(path) {
3633
3810
  return {
3634
3811
  code: "symlink-order-dependent",
3635
- 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.",
3636
3813
  ...path === void 0 ? {} : { path }
3637
3814
  };
3638
3815
  }
@@ -5507,4 +5684,4 @@ function renderSkipsExplanation(result, options = {}) {
5507
5684
  }
5508
5685
  return `${lines.join("\n")}\n`;
5509
5686
  }
5510
- export { extensionOf as $, CANDIDATE_DIGESTS as A, resolveScan as B, MAX_EXPLAIN_LIMIT as C, outsideRootError as D, isOutside as E, createProgressReporter as F, diskBytesOf as G, Excluder as H, resolveFeatures as I, rollUp as J, passesFilters as K, DEFAULT_CONCURRENCY as L, DEFAULT_LARGE_FILE_THRESHOLD as M, DEFAULT_STALE_AGE as N, compare as O, analyze as P, classify as Q, assertDirectory as R, EXPLAIN_VERSION as S, explainSkips as T, Scanner as U, DEFAULT_EXCLUDES as V, compareRelativePaths as W, comparePaths as X, scanError as Y, joinRelative as Z, findConfigFile as _, renderComparisonCsv as a, parseSize as at, validateConfig as b, renderAnalysis as c, parseDuration as ct, escapeControlInLines as d, DatError as dt, BUDGET_METRICS as et, formatCount as f, errorCode as ft, CONFIG_FILE_NAMES as g, supportsColor as h, renderAnalysisCsv as i, formatBytes as it, Collector as j, compactAnalysis as k, renderComparison as l, parsePointInTime as lt, createStyle as m, renderSkipsExplanation as n, formatBudgetActual as nt, renderAnalysisMarkdown as o, CATEGORIES as ot, stringifyJson as p, errorMessage as pt, relativePathOf as q, renderAnalysisHtml as r, parseBudget as rt, renderComparisonMarkdown as s, VERSION as st, renderPathExplanation as t, evaluateBudgets as tt, escapeControl as u, AbortError as ut, loadConfig as v, explainPath as w, DEFAULT_EXPLAIN_LIMIT as x, buildJsonSchema as y, listDirectories 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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dir-analysis-tool",
3
- "version": "3.5.8",
3
+ "version": "3.6.0",
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": {
@@ -91,18 +91,18 @@
91
91
  "@semantic-release/npm": "^13.2.0",
92
92
  "@semantic-release/release-notes-generator": "^14.1.1",
93
93
  "@types/node": "^22.20.5",
94
- "@vitest/coverage-v8": "^5.0.5",
94
+ "@vitest/coverage-v8": "^5.1.1",
95
95
  "ajv": "^8.20.0",
96
96
  "conventional-changelog-conventionalcommits": "^9.3.1",
97
97
  "husky": "^9.1.7",
98
- "oxlint": "^1.88.0",
99
- "oxlint-tsgolint": "^7.0.2004",
98
+ "oxlint": "^1.94.0",
99
+ "oxlint-tsgolint": "^7.0.2008",
100
100
  "prettier": "^3.9.10",
101
101
  "publint": "^0.3.25",
102
102
  "semantic-release": "^26.0.1",
103
103
  "tsdown": "^0.23.1",
104
104
  "typescript": "^7.0.2",
105
- "vitest": "^5.0.5"
105
+ "vitest": "^5.1.1"
106
106
  },
107
107
  "engines": {
108
108
  "node": ">=22.12.0"
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://json-schema.org/draft/2020-12/schema",
3
3
  "$id": "https://unpkg.com/dir-analysis-tool@3/report.schema.json",
4
4
  "title": "dir-analysis-tool JSON reports",
5
- "description": "Output of dat --json (schemaVersion 3), dat compare --json (schemaVersion 3) and dat explain --json (explainVersion 1). The library returns the same shapes. Within 3.x, fields are only added, never removed, renamed or retyped.",
5
+ "description": "Output of dat --json and dat --compact (schemaVersion 3), dat compare --json and --compact (schemaVersion 3) and dat explain --json (explainVersion 1). The library returns the same shapes. Within 3.x, fields are only added, never removed, renamed or retyped.",
6
6
  "anyOf": [
7
7
  {
8
8
  "$ref": "#/$defs/analysis"
@@ -677,6 +677,41 @@
677
677
  }
678
678
  }
679
679
  },
680
+ "comparisonCompact": {
681
+ "type": "object",
682
+ "description": "Present only in compact comparison output (compare --compact): what was cut.",
683
+ "required": ["limit", "truncated", "omitted"],
684
+ "properties": {
685
+ "limit": {
686
+ "type": "integer",
687
+ "minimum": 0,
688
+ "description": "Maximum number of items kept in each list."
689
+ },
690
+ "truncated": {
691
+ "type": "boolean",
692
+ "description": "Whether any list was cut."
693
+ },
694
+ "omitted": {
695
+ "type": "object",
696
+ "description": "Items not listed, per cut list. A list that is absent here was not cut.",
697
+ "required": [],
698
+ "properties": {
699
+ "added.items": {
700
+ "type": "integer",
701
+ "minimum": 0
702
+ },
703
+ "removed.items": {
704
+ "type": "integer",
705
+ "minimum": 0
706
+ },
707
+ "changed.items": {
708
+ "type": "integer",
709
+ "minimum": 0
710
+ }
711
+ }
712
+ }
713
+ }
714
+ },
680
715
  "comparison": {
681
716
  "type": "object",
682
717
  "description": "dat compare --json.",
@@ -739,15 +774,15 @@
739
774
  }
740
775
  },
741
776
  "added": {
742
- "description": "Every added file, whatever --top is.",
777
+ "description": "Every added file, whatever --top is; compact output cuts the items to the limit.",
743
778
  "$ref": "#/$defs/fileList"
744
779
  },
745
780
  "removed": {
746
- "description": "Every removed file, whatever --top is.",
781
+ "description": "Every removed file, whatever --top is; compact output cuts the items to the limit.",
747
782
  "$ref": "#/$defs/fileList"
748
783
  },
749
784
  "changed": {
750
- "description": "Every changed file, whatever --top is.",
785
+ "description": "Every changed file, whatever --top is; compact output cuts the items to the limit.",
751
786
  "type": "object",
752
787
  "required": ["count", "delta", "items"],
753
788
  "properties": {
@@ -811,6 +846,9 @@
811
846
  }
812
847
  },
813
848
  "description": "Directories with the largest size change, largest absolute change first."
849
+ },
850
+ "compact": {
851
+ "$ref": "#/$defs/comparisonCompact"
814
852
  }
815
853
  }
816
854
  },