dir-analysis-tool 3.5.4 → 3.5.6

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
@@ -230,7 +230,7 @@ A size tree (`dat src -t --tree-depth 2`):
230
230
 
231
231
  | Option | Description |
232
232
  | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
233
- | `--content` | Also compare same-sized files by content (SHA-256). By default, files are compared by size. |
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
236
 
@@ -532,9 +532,10 @@ Then ask in your own words, for example "why is this repo so big?" or "fail CI i
532
532
  - **Duplicates,** in stages so most files are never read in full:
533
533
  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.
534
534
  2. Files over 256 KiB are compared by a SHA-256 sample of their first and last 64 KiB.
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.
535
+ 3. Remaining candidates are hashed in full: small files in a single read, large files streamed through reusable buffers. A stage with 4,096 files or more is hashed by up to four worker threads (no more than the CPU cores less one), each with one reusable buffer, so SHA-256 runs in parallel; the results are the same as on the main thread. 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
+ - **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.
536
537
  - **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.
538
+ - **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
539
 
539
540
  **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
541
 
@@ -545,7 +546,7 @@ Then ask in your own words, for example "why is this repo so big?" or "fail CI i
545
546
  | Scan and find duplicates | 2.64 s | **1.20 s** | |
546
547
  | Peak heap while finding duplicates | 118 MB | **45 MB** | |
547
548
 
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.
549
+ 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. In a 93,000-file, 1.7 GiB project folder where 92% of the files share their size with another, 3.5.6 finds duplicates in 0.91 s where 3.5.5 took 2.2 s (Linux in Docker), and in 1.22 s where it took 1.50 s on macOS, where file-system calls are the limit; `dat compare --content` of that folder against a copy takes 3.5 s where it took 6.0 s (Linux). 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
550
 
550
551
  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
552
 
@@ -593,7 +594,7 @@ v3 is a rewrite with a new output format. Most commands keep working unchanged.
593
594
 
594
595
  **Why does the total differ from `du`?** `du` reports blocks allocated on disk, while the headline size is the sum of file lengths. The `On disk` line matches `du`. Also check what was skipped: `.git` and `node_modules` are excluded by default (`--all` includes them), and hard-linked data is counted once, as `du` does. `dat explain` lists everything a scan skipped and why.
595
596
 
596
- **Is it safe to run on a huge directory?** Yes. The default scan keeps bounded top-N file lists, but folder metadata, hard-link tracking, and symlink tracking still require memory. Duplicate detection, directory comparisons, and optional file lists use additional memory, filesystem concurrency is bounded, and unreadable paths are reported rather than fatal. Press Ctrl+C at any time.
597
+ **Is it safe to run on a huge directory?** Yes. The default scan keeps bounded top-N file lists, but folder metadata, hard-link tracking, and symlink tracking still require memory. Duplicate detection, directory comparisons, and optional file lists use additional memory (duplicate detection on thousands of files also starts up to four worker threads, a fixed few megabytes each), filesystem concurrency is bounded, and unreadable paths are reported rather than fatal. Press Ctrl+C at any time.
597
598
 
598
599
  **Does it modify anything?** `dat` reads the scanned files. It writes report files when requested, and `dat init` writes a configuration file.
599
600
 
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-c7R0EX5i.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-bXznpAvJ.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";
@@ -774,7 +774,7 @@ function applyLegacyLargeFiles(cli, warn) {
774
774
  warn(`--large-files ${value} is read as ${value} MiB, as in v2. Add a unit to be explicit, for example --large-files ${value}MB.`);
775
775
  }
776
776
  /** Typed readers for loosely typed commander values. */
777
- const read = {
777
+ const read$1 = {
778
778
  string: (value) => typeof value === "string" ? value : void 0,
779
779
  number: (value) => typeof value === "number" ? value : void 0,
780
780
  boolean: (value) => typeof value === "boolean" ? value : void 0,
@@ -786,38 +786,38 @@ const read = {
786
786
  function resolveScanSettings(cli, config) {
787
787
  let defaultExcludes = config.defaultExcludes;
788
788
  if (cli["all"] === true) defaultExcludes = false;
789
- else defaultExcludes = read.boolean(cli["defaultExcludes"]) ?? defaultExcludes;
789
+ else defaultExcludes = read$1.boolean(cli["defaultExcludes"]) ?? defaultExcludes;
790
790
  let maxDepth = config.maxDepth;
791
791
  if (cli["recursive"] === false) maxDepth = 0;
792
- maxDepth = read.number(cli["maxDepth"]) ?? maxDepth;
792
+ maxDepth = read$1.number(cli["maxDepth"]) ?? maxDepth;
793
793
  return {
794
- exclude: [...config.exclude ?? [], ...read.strings(cli["exclude"])],
794
+ exclude: [...config.exclude ?? [], ...read$1.strings(cli["exclude"])],
795
795
  defaultExcludes,
796
- gitignore: read.boolean(cli["gitignore"]) ?? config.gitignore,
796
+ gitignore: read$1.boolean(cli["gitignore"]) ?? config.gitignore,
797
797
  maxDepth,
798
- followSymlinks: read.boolean(cli["followSymlinks"]) ?? config.followSymlinks,
799
- countHardlinks: read.boolean(cli["countHardlinks"]) ?? config.countHardlinks,
800
- minSize: read.string(cli["minSize"]) ?? config.minSize,
801
- maxSize: read.string(cli["maxSize"]) ?? config.maxSize,
802
- modifiedAfter: read.string(cli["newerThan"]) ?? read.string(cli["dateFrom"]) ?? config.newerThan,
803
- modifiedBefore: read.string(cli["olderThan"]) ?? read.string(cli["dateTo"]) ?? config.olderThan
798
+ followSymlinks: read$1.boolean(cli["followSymlinks"]) ?? config.followSymlinks,
799
+ countHardlinks: read$1.boolean(cli["countHardlinks"]) ?? config.countHardlinks,
800
+ minSize: read$1.string(cli["minSize"]) ?? config.minSize,
801
+ maxSize: read$1.string(cli["maxSize"]) ?? config.maxSize,
802
+ modifiedAfter: read$1.string(cli["newerThan"]) ?? read$1.string(cli["dateFrom"]) ?? config.newerThan,
803
+ modifiedBefore: read$1.string(cli["olderThan"]) ?? read$1.string(cli["dateTo"]) ?? config.olderThan
804
804
  };
805
805
  }
806
806
  /** Merges config values with explicit CLI flags into full analysis options. */
807
807
  function resolveAnalyzeOptions(cli, config) {
808
- const emptyFlag = read.boolean(cli["empty"]) ?? (cli["emptyFiles"] === true ? true : void 0);
809
- const treeDepth = read.number(cli["treeDepth"]) ?? config.treeDepth;
810
- const tree = read.boolean(cli["tree"]) ?? config.tree ?? (cli["treeDepth"] === void 0 ? void 0 : true);
808
+ const emptyFlag = read$1.boolean(cli["empty"]) ?? (cli["emptyFiles"] === true ? true : void 0);
809
+ const treeDepth = read$1.number(cli["treeDepth"]) ?? config.treeDepth;
810
+ const tree = read$1.boolean(cli["tree"]) ?? config.tree ?? (cli["treeDepth"] === void 0 ? void 0 : true);
811
811
  return {
812
812
  ...resolveScanSettings(cli, config),
813
- top: read.number(cli["top"]) ?? read.number(cli["topN"]) ?? config.top,
814
- largeFiles: read.flag(cli["largeFiles"]) ?? config.largeFiles,
815
- duplicates: read.boolean(cli["duplicates"]) ?? config.duplicates,
816
- minDuplicateSize: read.string(cli["minDuplicateSize"]) ?? config.minDuplicateSize,
813
+ top: read$1.number(cli["top"]) ?? read$1.number(cli["topN"]) ?? config.top,
814
+ largeFiles: read$1.flag(cli["largeFiles"]) ?? config.largeFiles,
815
+ duplicates: read$1.boolean(cli["duplicates"]) ?? config.duplicates,
816
+ minDuplicateSize: read$1.string(cli["minDuplicateSize"]) ?? config.minDuplicateSize,
817
817
  empty: emptyFlag ?? config.empty,
818
- stale: read.flag(cli["stale"]) ?? config.stale,
818
+ stale: read$1.flag(cli["stale"]) ?? config.stale,
819
819
  tree: tree === true ? { depth: treeDepth } : false,
820
- budgets: [...config.budgets ?? [], ...read.strings(cli["budget"])]
820
+ budgets: [...config.budgets ?? [], ...read$1.strings(cli["budget"])]
821
821
  };
822
822
  }
823
823
  function resolveDisplay(cli, config) {
@@ -827,15 +827,15 @@ function resolveDisplay(cli, config) {
827
827
  return {
828
828
  format: cli["json"] === true || compact ? "json" : requested ?? "pretty",
829
829
  compact,
830
- output: read.string(cli["output"]),
830
+ output: read$1.string(cli["output"]),
831
831
  units: cli["si"] === true ? "si" : config.units ?? "iec",
832
- color: read.boolean(cli["color"]),
832
+ color: read$1.boolean(cli["color"]),
833
833
  progress: cli["progress"] !== false && cli["quiet"] !== true,
834
834
  quiet: cli["quiet"] === true,
835
835
  types: cli["types"] !== false,
836
- extensions: read.boolean(cli["extensions"]) ?? config.extensions ?? false,
837
- html: read.flag(cli["html"]),
838
- csv: read.flag(cli["csv"])
836
+ extensions: read$1.boolean(cli["extensions"]) ?? config.extensions ?? false,
837
+ html: read$1.flag(cli["html"]),
838
+ csv: read$1.flag(cli["csv"])
839
839
  };
840
840
  }
841
841
  // src/cli/progress.ts
@@ -1004,7 +1004,7 @@ Examples:
1004
1004
  function registerCompare(program, ctx) {
1005
1005
  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
1006
  addScanOptions(command);
1007
- command.addOption(new Option("--content", "compare same-size files by content (SHA-256)").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:"));
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
1008
  addOutputOptions(command, [
1009
1009
  "pretty",
1010
1010
  "json",
@@ -1016,7 +1016,7 @@ function registerCompare(program, ctx) {
1016
1016
  const cli = explicitOptions(cmd);
1017
1017
  const { config } = await ctx.loadConfig(cli, ctx.io.cwd);
1018
1018
  const display = resolveDisplay(cli, config);
1019
- const top = read.number(cli["top"]) ?? config.top;
1019
+ const top = read$1.number(cli["top"]) ?? config.top;
1020
1020
  if (display.output) await ctx.checkOutput(display.output);
1021
1021
  const progress = new ProgressLine(ctx.io.stderr, display.progress && ctx.io.stderr.isTTY === true, ctx.err, display.units);
1022
1022
  let result;
@@ -1074,12 +1074,12 @@ function registerExplain(program, ctx) {
1074
1074
  command.addHelpText("after", EXAMPLES$1);
1075
1075
  command.action(async (path, _options, cmd) => {
1076
1076
  const cli = explicitOptions(cmd);
1077
- const root = ctx.resolvePath(read.string(cli["root"]) ?? ".");
1077
+ const root = ctx.resolvePath(read$1.string(cli["root"]) ?? ".");
1078
1078
  const { config } = await ctx.loadConfig(cli, root);
1079
1079
  const settings = resolveScanSettings(cli, config);
1080
1080
  const json = cli["json"] === true;
1081
1081
  const units = cli["si"] === true ? "si" : config.units ?? "iec";
1082
- const style = ctx.outputStyle(read.boolean(cli["color"]), false);
1082
+ const style = ctx.outputStyle(read$1.boolean(cli["color"]), false);
1083
1083
  const width = terminalWidth(ctx.io);
1084
1084
  if (path !== void 0) {
1085
1085
  const target = ctx.resolvePath(path);
@@ -1100,7 +1100,7 @@ function registerExplain(program, ctx) {
1100
1100
  if (progress.enabled) progress.update("Scanning for skipped entries");
1101
1101
  result = await explainSkips(root, {
1102
1102
  ...settings,
1103
- limit: read.number(cli["limit"]),
1103
+ limit: read$1.number(cli["limit"]),
1104
1104
  signal: ctx.io.signal
1105
1105
  });
1106
1106
  } finally {
@@ -1458,8 +1458,8 @@ function registerWatch(program, ctx) {
1458
1458
  const { config } = await ctx.loadConfig(cli, target);
1459
1459
  const display = resolveDisplay(cli, config);
1460
1460
  const options = resolveAnalyzeOptions(cli, config);
1461
- const debounce = read.number(cli["debounce"]) ?? 300;
1462
- const pollSeconds = read.number(cli["poll"]);
1461
+ const debounce = read$1.number(cli["debounce"]) ?? 300;
1462
+ const pollSeconds = read$1.number(cli["poll"]);
1463
1463
  const clear = cli["clear"] !== false && display.format === "pretty" && ctx.io.stdout.isTTY === true;
1464
1464
  const signal = ctx.io.signal;
1465
1465
  await assertDirectory(target);
package/dist/index.d.ts CHANGED
@@ -212,7 +212,7 @@ export interface ComparisonResult {
212
212
  tool: ToolInfo;
213
213
  startedAt: string;
214
214
  durationMs: number;
215
- /** How `changed` was decided: by size only, or by size then content hash. */
215
+ /** How `changed` was decided: by size only, or by size and then by content. */
216
216
  mode: "size" | "content";
217
217
  left: ComparisonSide;
218
218
  right: ComparisonSide;
@@ -354,7 +354,10 @@ interface CompactOptions {
354
354
  */
355
355
  export declare function compactAnalysis(result: AnalysisResult, options: CompactOptions): AnalysisResult;
356
356
  interface CompareOptions extends ScanSettings {
357
- /** Also compare the contents of same-sized files (SHA-256). Default: `false`, size only. */
357
+ /**
358
+ * Also compare the contents of same-sized files, byte by byte. Default: `false`, size only.
359
+ * Progress for this step reports `phase: 'hash'`.
360
+ */
358
361
  content?: boolean | undefined;
359
362
  /** Length of the directory delta list. Default: 10. */
360
363
  top?: number | undefined;
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-c7R0EX5i.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-bXznpAvJ.js";
@@ -1,7 +1,9 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { createHash, hash } from "node:crypto";
3
- import { existsSync, readFile } from "node:fs";
4
- import { lstat, open, readFile as readFile$1, readdir, stat } from "node:fs/promises";
3
+ import { close, existsSync, open, read } from "node:fs";
4
+ import { lstat, open as open$1, readFile, readdir, stat } from "node:fs/promises";
5
+ import { availableParallelism } from "node:os";
6
+ import { Worker } from "node:worker_threads";
5
7
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
8
  // src/errors.ts
7
9
  /**
@@ -742,6 +744,212 @@ function emptyTypeStats() {
742
744
  }
743
745
  };
744
746
  }
747
+ // src/core/content.ts
748
+ /** Bytes read from each file per step when comparing contents. */
749
+ const COMPARE_CHUNK_BYTES = 262144;
750
+ /** Reuses read buffers, so reading many files allocates a fixed amount of memory. */
751
+ var BufferPool = class {
752
+ #free = [];
753
+ #bytes;
754
+ constructor(bytes) {
755
+ this.#bytes = bytes;
756
+ }
757
+ acquire() {
758
+ return this.#free.pop() ?? Buffer.allocUnsafe(this.#bytes);
759
+ }
760
+ release(buffer) {
761
+ this.#free.push(buffer);
762
+ }
763
+ };
764
+ /**
765
+ * Whether two files have the same contents, compared byte by byte in chunks
766
+ * and stopping at the first difference, so no hash is computed and a changed
767
+ * file is usually decided by its first chunk. Both files are read until they
768
+ * end, so a file that grew or shrank since it was measured still compares
769
+ * correctly; `size` (the expected length) only lets a small file be read in a
770
+ * single call. Rejects when either file cannot be opened or read.
771
+ */
772
+ async function sameContent(left, right, size, buffers) {
773
+ const a = buffers.acquire();
774
+ const b = buffers.acquire();
775
+ const fds = [];
776
+ try {
777
+ const opened = await Promise.allSettled([openFile(left), openFile(right)]);
778
+ for (const result of opened) if (result.status === "fulfilled") fds.push(result.value);
779
+ const [fdA, fdB] = settled(opened);
780
+ let length = Math.min(a.length, size + 1);
781
+ let position = 0;
782
+ for (;;) {
783
+ const [readA, readB] = settled(await Promise.allSettled([readInto(fdA, a, length, position), readInto(fdB, b, length, position)]));
784
+ if (readA !== readB) return false;
785
+ if (readA === 0) return true;
786
+ if (a.compare(b, 0, readB, 0, readA) !== 0) return false;
787
+ if (readA < length) return true;
788
+ position += readA;
789
+ length = a.length;
790
+ }
791
+ } finally {
792
+ await Promise.all(fds.map(closeFile));
793
+ buffers.release(a);
794
+ buffers.release(b);
795
+ }
796
+ }
797
+ /** The values of two settled promises, or the first failure. */
798
+ function settled(results) {
799
+ const [first, second] = results;
800
+ if (first.status === "rejected") throw first.reason;
801
+ if (second.status === "rejected") throw second.reason;
802
+ return [first.value, second.value];
803
+ }
804
+ /** Opens a file for reading; resolves to its descriptor. */
805
+ function openFile(path) {
806
+ return new Promise((resolve, reject) => {
807
+ open(path, "r", (error, fd) => error ? reject(error) : resolve(fd));
808
+ });
809
+ }
810
+ /** Reads up to `length` bytes at `position` into the start of `buffer`. */
811
+ function readInto(fd, buffer, length, position) {
812
+ return new Promise((resolve, reject) => {
813
+ read(fd, buffer, 0, length, position, (error, bytesRead) => error ? reject(error) : resolve(bytesRead));
814
+ });
815
+ }
816
+ function closeFile(fd) {
817
+ return new Promise((resolve) => close(fd, () => resolve()));
818
+ }
819
+ // src/core/hash-pool.ts
820
+ /** Bytes of the read buffer each worker keeps. */
821
+ const WORKER_BUFFER_BYTES = 524288;
822
+ /**
823
+ * Hashes files synchronously, exactly as the in-process path does: SHA-256
824
+ * of the whole file as it is now, or of its first and last 64 KiB for a
825
+ * sample. Runs inside a worker from its source text, so it must not use
826
+ * anything from outside its own body except its arguments and globals.
827
+ */
828
+ function hashJobs(jobs, fs, crypto, buffer) {
829
+ const SMALL_FILE_BYTES = 262144;
830
+ const SAMPLE_BYTES = 65536;
831
+ const results = [];
832
+ for (const [path, size, sample] of jobs) {
833
+ let fd;
834
+ try {
835
+ fd = fs.openSync(path, "r");
836
+ if (sample) {
837
+ const hasher = crypto.createHash("sha256");
838
+ for (const position of [0, Math.max(0, size - SAMPLE_BYTES)]) {
839
+ const bytesRead = fs.readSync(fd, buffer, 0, SAMPLE_BYTES, position);
840
+ hasher.update(buffer.subarray(0, bytesRead));
841
+ }
842
+ results.push(hasher.digest("hex"));
843
+ continue;
844
+ }
845
+ if (size <= SMALL_FILE_BYTES) {
846
+ const wanted = size + 1;
847
+ const bytesRead = fs.readSync(fd, buffer, 0, wanted, 0);
848
+ if (bytesRead < wanted) {
849
+ results.push(crypto.hash("sha256", buffer.subarray(0, bytesRead), "hex"));
850
+ continue;
851
+ }
852
+ }
853
+ const hasher = crypto.createHash("sha256");
854
+ let position = 0;
855
+ for (;;) {
856
+ const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, position);
857
+ if (bytesRead === 0) break;
858
+ hasher.update(buffer.subarray(0, bytesRead));
859
+ position += bytesRead;
860
+ }
861
+ results.push(hasher.digest("hex"));
862
+ } catch (error) {
863
+ const code = error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
864
+ results.push({
865
+ code,
866
+ message: error instanceof Error ? error.message : String(error)
867
+ });
868
+ } finally {
869
+ if (fd !== void 0) try {
870
+ fs.closeSync(fd);
871
+ } catch {}
872
+ }
873
+ }
874
+ return results;
875
+ }
876
+ const WORKER_SOURCE = `'use strict';
877
+ const { parentPort } = require('node:worker_threads');
878
+ const fs = require('node:fs');
879
+ const crypto = require('node:crypto');
880
+ const buffer = Buffer.allocUnsafe(${WORKER_BUFFER_BYTES});
881
+ const hashJobs = ${hashJobs.toString()};
882
+ parentPort.on('message', (message) => {
883
+ parentPort.postMessage({ id: message.id, results: hashJobs(message.jobs, fs, crypto, buffer) });
884
+ });
885
+ `;
886
+ /** Workers to start: at most 4, at most the cores less one, at most `limit`. */
887
+ function workerCount(limit) {
888
+ return Math.max(1, Math.min(4, availableParallelism() - 1, limit));
889
+ }
890
+ /**
891
+ * A fixed set of worker threads that read and hash files, so SHA-256 and
892
+ * the read calls run in parallel instead of on the main thread. Each worker
893
+ * keeps one read buffer, so memory is fixed by the worker count.
894
+ */
895
+ var HashPool = class {
896
+ #workers = [];
897
+ #pending = /* @__PURE__ */ new Map();
898
+ #nextId = 0;
899
+ #failure = null;
900
+ constructor(count) {
901
+ for (let i = 0; i < count; i++) {
902
+ const state = {
903
+ worker: new Worker(WORKER_SOURCE, {
904
+ eval: true,
905
+ resourceLimits: { maxYoungGenerationSizeMb: 2 }
906
+ }),
907
+ inFlight: 0
908
+ };
909
+ state.worker.on("message", (message) => {
910
+ const pending = this.#pending.get(message.id);
911
+ if (!pending) return;
912
+ this.#pending.delete(message.id);
913
+ pending.worker.inFlight--;
914
+ pending.resolve(message.results);
915
+ });
916
+ state.worker.on("error", (error) => this.#fail(error));
917
+ this.#workers.push(state);
918
+ }
919
+ }
920
+ get size() {
921
+ return this.#workers.length;
922
+ }
923
+ /** Hashes a batch on the least busy worker; results are in job order. */
924
+ run(jobs) {
925
+ if (this.#failure !== null) return Promise.reject(this.#failure);
926
+ let target = this.#workers[0];
927
+ for (const state of this.#workers) if (state.inFlight < target.inFlight) target = state;
928
+ const id = this.#nextId++;
929
+ return new Promise((resolve, reject) => {
930
+ this.#pending.set(id, {
931
+ worker: target,
932
+ resolve,
933
+ reject
934
+ });
935
+ target.inFlight++;
936
+ target.worker.postMessage({
937
+ id,
938
+ jobs
939
+ });
940
+ });
941
+ }
942
+ /** Stops the workers. Batches still running reject with `reason`. */
943
+ async close(reason = new AbortError()) {
944
+ this.#fail(reason);
945
+ await Promise.all(this.#workers.map((state) => state.worker.terminate()));
946
+ }
947
+ #fail(reason) {
948
+ if (this.#failure === null) this.#failure = reason;
949
+ for (const pending of this.#pending.values()) pending.reject(this.#failure);
950
+ this.#pending.clear();
951
+ }
952
+ };
745
953
  // src/core/limiter.ts
746
954
  /**
747
955
  * A tiny concurrency limiter for filesystem work.
@@ -867,12 +1075,19 @@ var Scanner = class {
867
1075
  const onAbort = () => this.#limiter.abort(new AbortError());
868
1076
  signal?.addEventListener("abort", onAbort, { once: true });
869
1077
  try {
870
- this.#limiter.run(() => this.#scanDir(index, root, chain));
1078
+ this.#limiter.run(() => this.#scanDir(index, root, chain, ""));
871
1079
  await this.#limiter.idle();
872
1080
  } finally {
873
1081
  signal?.removeEventListener("abort", onAbort);
874
1082
  }
875
1083
  }
1084
+ /**
1085
+ * Orders two entries as {@link comparePaths} orders their relative paths,
1086
+ * without building them. See {@link compareRelativePaths}.
1087
+ */
1088
+ compareRelative(dirA, nameA, dirB, nameB) {
1089
+ return compareRelativePaths(this.dirs, dirA, nameA, dirB, nameB);
1090
+ }
876
1091
  /** Root-relative path of a directory (or of `name` inside it), with `/` separators. */
877
1092
  relativePath(dirIndex, name) {
878
1093
  const parts = name === void 0 ? [] : [name];
@@ -901,7 +1116,12 @@ var Scanner = class {
901
1116
  this.#visitor.directory?.(index, node);
902
1117
  return index;
903
1118
  }
904
- async #scanDir(index, absPath, inherited) {
1119
+ /**
1120
+ * @param relDir Root-relative path of the directory when the excluder
1121
+ * matches paths (passed down from the parent, so it is never rebuilt
1122
+ * from the root), and `''` otherwise.
1123
+ */
1124
+ async #scanDir(index, absPath, inherited, relDir) {
905
1125
  const { excluder } = this.#options;
906
1126
  let entries;
907
1127
  try {
@@ -914,7 +1134,6 @@ var Scanner = class {
914
1134
  const node = this.dirs[index];
915
1135
  node.entries = entries.length;
916
1136
  if (entries.length === 0) return;
917
- const relDir = excluder.needsPaths ? this.relativePath(index) : "";
918
1137
  let chain = inherited;
919
1138
  if (excluder.gitignore && entries.some((e) => e.name === ".gitignore" && !e.isDirectory())) {
920
1139
  const scope = await excluder.loadScope(joinNative(absPath, ".gitignore"), relDir);
@@ -922,6 +1141,7 @@ var Scanner = class {
922
1141
  }
923
1142
  const base = absPath.endsWith(sep) ? absPath : absPath + sep;
924
1143
  const checkExclusion = excluder.active;
1144
+ const needsPaths = excluder.needsPaths;
925
1145
  for (const entry of entries) {
926
1146
  const name = entry.name;
927
1147
  const isDirectory = entry.isDirectory();
@@ -929,9 +1149,9 @@ var Scanner = class {
929
1149
  const isSymlink = !isDirectory && !isFile && entry.isSymbolicLink();
930
1150
  const isUnknown = !isDirectory && !isFile && !isSymlink && isUnknownType(entry);
931
1151
  if (!isDirectory && !isFile && !isSymlink && !isUnknown) continue;
1152
+ const rel = needsPaths ? relDir ? `${relDir}/${name}` : name : "";
932
1153
  if (checkExclusion) {
933
- const rel = relDir ? `${relDir}/${name}` : name;
934
- if (excluder.isExcluded(rel, name, isDirectory, chain)) {
1154
+ if (excluder.isExcluded(rel || name, name, isDirectory, chain)) {
935
1155
  this.counters.excluded++;
936
1156
  this.#options.onSkip?.({
937
1157
  kind: "excluded",
@@ -945,12 +1165,12 @@ var Scanner = class {
945
1165
  }
946
1166
  const fullPath = base + name;
947
1167
  if (this.#options.directoriesOnly && !isDirectory) continue;
948
- if (isDirectory && !this.#options.followSymlinks) this.#enterDir(index, name, fullPath, chain);
1168
+ if (isDirectory && !this.#options.followSymlinks) this.#enterDir(index, name, fullPath, chain, rel);
949
1169
  else if (isFile) this.#limiter.run(() => this.#statFile(index, name, fullPath));
950
- else this.#limiter.run(() => this.#resolveEntry(index, name, fullPath, chain, isSymlink, isDirectory));
1170
+ else this.#limiter.run(() => this.#resolveEntry(index, name, fullPath, chain, rel, isSymlink, isDirectory));
951
1171
  }
952
1172
  }
953
- #enterDir(parent, name, fullPath, chain) {
1173
+ #enterDir(parent, name, fullPath, chain, relPath) {
954
1174
  const depth = this.dirs[parent].depth + 1;
955
1175
  if (depth > this.#options.maxDepth) {
956
1176
  this.#options.onSkip?.({
@@ -962,7 +1182,7 @@ var Scanner = class {
962
1182
  return;
963
1183
  }
964
1184
  const child = this.#addDir(name, parent, depth);
965
- this.#limiter.run(() => this.#scanDir(child, fullPath, chain));
1185
+ this.#limiter.run(() => this.#scanDir(child, fullPath, chain, relPath));
966
1186
  }
967
1187
  async #statFile(dirIndex, name, fullPath) {
968
1188
  let stats;
@@ -979,7 +1199,7 @@ var Scanner = class {
979
1199
  * Handles symlinks, entries whose type the filesystem did not report, and
980
1200
  * (when following symlinks) directories, which then need their identity.
981
1201
  */
982
- async #resolveEntry(dirIndex, name, fullPath, chain, isSymlink, checkedAsDirectory) {
1202
+ async #resolveEntry(dirIndex, name, fullPath, chain, relPath, isSymlink, checkedAsDirectory) {
983
1203
  let stats;
984
1204
  try {
985
1205
  stats = await lstat(fullPath);
@@ -1015,8 +1235,7 @@ var Scanner = class {
1015
1235
  if (stats.isDirectory()) {
1016
1236
  const { excluder } = this.#options;
1017
1237
  if (excluder.active && !checkedAsDirectory) {
1018
- const rel = this.relativePath(dirIndex, name);
1019
- if (excluder.isExcluded(rel, name, true, chain)) {
1238
+ if (excluder.isExcluded(relPath || name, name, true, chain)) {
1020
1239
  this.counters.excluded++;
1021
1240
  this.#options.onSkip?.({
1022
1241
  kind: "excluded",
@@ -1031,7 +1250,7 @@ var Scanner = class {
1031
1250
  const key = await inodeKey(stats, fullPath);
1032
1251
  if (this.#seenDirs.has(key)) return;
1033
1252
  this.#seenDirs.add(key);
1034
- this.#enterDir(dirIndex, name, fullPath, chain);
1253
+ this.#enterDir(dirIndex, name, fullPath, chain, relPath);
1035
1254
  } else if (stats.isFile()) {
1036
1255
  const pending = this.#acceptFile(dirIndex, name, fullPath, stats);
1037
1256
  if (pending) await pending;
@@ -1115,6 +1334,59 @@ function rollUp(dirs) {
1115
1334
  }
1116
1335
  }
1117
1336
  }
1337
+ /** Code unit of the `/` that joins path segments. */
1338
+ const SLASH = 47;
1339
+ /**
1340
+ * Compares the root-relative paths of two entries, each a directory index
1341
+ * plus an optional name inside it. The result has the same sign as
1342
+ * `comparePaths(relativePath(dirA, nameA), relativePath(dirB, nameB))`.
1343
+ *
1344
+ * Building both paths costs O(depth) time and garbage on every call, which
1345
+ * made top-N tie-breaks on deep trees slow (#31). This walks parent indices
1346
+ * to the closest common directory instead, and compares only the first
1347
+ * segment where the paths part. That is not a segment-by-segment comparison:
1348
+ * when one segment is a prefix of the other, the shorter path continues with
1349
+ * `/` (or ends), and `/` sorts after characters such as `-` and `.`, exactly
1350
+ * as it does in the joined string.
1351
+ */
1352
+ function compareRelativePaths(dirs, dirA, nameA, dirB, nameB) {
1353
+ if (dirA === dirB) {
1354
+ if (nameA === void 0 || nameB === void 0) return nameA === nameB ? 0 : nameA === void 0 ? -1 : 1;
1355
+ return nameA < nameB ? -1 : nameA > nameB ? 1 : 0;
1356
+ }
1357
+ let a = dirA;
1358
+ let b = dirB;
1359
+ let belowA = -1;
1360
+ let belowB = -1;
1361
+ while (dirs[a].depth > dirs[b].depth) {
1362
+ belowA = a;
1363
+ a = dirs[a].parent;
1364
+ }
1365
+ while (dirs[b].depth > dirs[a].depth) {
1366
+ belowB = b;
1367
+ b = dirs[b].parent;
1368
+ }
1369
+ while (a !== b) {
1370
+ belowA = a;
1371
+ a = dirs[a].parent;
1372
+ belowB = b;
1373
+ b = dirs[b].parent;
1374
+ }
1375
+ const segmentA = belowA === -1 ? nameA : dirs[belowA].name;
1376
+ const segmentB = belowB === -1 ? nameB : dirs[belowB].name;
1377
+ if (segmentA === void 0) return segmentB === void 0 ? 0 : -1;
1378
+ if (segmentB === void 0) return 1;
1379
+ const length = Math.min(segmentA.length, segmentB.length);
1380
+ for (let i = 0; i < length; i++) {
1381
+ const diff = segmentA.charCodeAt(i) - segmentB.charCodeAt(i);
1382
+ if (diff !== 0) return diff;
1383
+ }
1384
+ return nextCode(segmentA, length, belowA !== -1 && (belowA !== dirA || nameA !== void 0)) - nextCode(segmentB, length, belowB !== -1 && (belowB !== dirB || nameB !== void 0));
1385
+ }
1386
+ function nextCode(segment, at, continues) {
1387
+ if (at < segment.length) return segment.charCodeAt(at);
1388
+ return continues ? SLASH : -1;
1389
+ }
1118
1390
  /**
1119
1391
  * `dev:ino` identity of a file or directory. `Stats.ino` is a Number, which is
1120
1392
  * exact only up to 2^53; Windows NTFS file IDs keep a sequence number in their
@@ -1175,12 +1447,23 @@ async function findDuplicates(sizeGroups, options) {
1175
1447
  if (distinct.length < 2) continue;
1176
1448
  (distinct[0].bytes <= SAMPLE_THRESHOLD ? small : large).push(distinct);
1177
1449
  }
1178
- const buffers = new BufferPool();
1179
- const sampled = await hashStage(large, "sample", options, buffers);
1180
- for (const group of sampled) small.push(group.members);
1181
- return hashStage(small, "full", options, buffers);
1450
+ const hashing = {
1451
+ buffers: new BufferPool(READ_BUFFER_BYTES),
1452
+ pool: null,
1453
+ workers: options.workers ?? workerCount(options.concurrency),
1454
+ threshold: options.workerThreshold ?? 4096
1455
+ };
1456
+ try {
1457
+ const sampled = await hashStage(large, "sample", options, hashing);
1458
+ for (const group of sampled) small.push(group.members);
1459
+ return await hashStage(small, "full", options, hashing);
1460
+ } finally {
1461
+ await hashing.pool?.close();
1462
+ }
1182
1463
  }
1183
- async function hashStage(groups, stage, options, buffers) {
1464
+ /** Files sent to a worker at once, so messaging costs little per file. */
1465
+ const WORKER_BATCH = 64;
1466
+ async function hashStage(groups, stage, options, hashing) {
1184
1467
  let total = 0;
1185
1468
  for (const group of groups) total += group.length;
1186
1469
  const results = [];
@@ -1199,38 +1482,97 @@ async function hashStage(groups, stage, options, buffers) {
1199
1482
  members
1200
1483
  });
1201
1484
  };
1202
- function* tasks() {
1485
+ /** Records one file's digest, or its error, the same way for both paths. */
1486
+ const record = (candidate, state, digest) => {
1487
+ if (typeof digest === "string") {
1488
+ const members = state.byHash.get(digest);
1489
+ if (members) members.push(candidate);
1490
+ else state.byHash.set(digest, [candidate]);
1491
+ } else options.onError?.(candidate, digest);
1492
+ done++;
1493
+ if (--state.pending === 0) finish(state);
1494
+ onProgress?.({
1495
+ stage,
1496
+ done,
1497
+ total
1498
+ });
1499
+ };
1500
+ function* files() {
1203
1501
  for (const group of groups) {
1204
1502
  const state = {
1205
1503
  bytes: group[0].bytes,
1206
1504
  pending: group.length,
1207
1505
  byHash: /* @__PURE__ */ new Map()
1208
1506
  };
1209
- for (const candidate of group) yield async () => {
1210
- try {
1211
- const path = options.pathOf(candidate);
1212
- const digest = stage === "sample" ? await sampleHash(path, candidate.bytes, buffers) : await hashFileOfSize(path, candidate.bytes, buffers);
1213
- const members = state.byHash.get(digest);
1214
- if (members) members.push(candidate);
1215
- else state.byHash.set(digest, [candidate]);
1216
- } catch (error) {
1217
- options.onError?.(candidate, error);
1218
- } finally {
1219
- done++;
1220
- if (--state.pending === 0) finish(state);
1221
- onProgress?.({
1222
- stage,
1223
- done,
1224
- total
1225
- });
1226
- }
1227
- };
1507
+ for (const candidate of group) yield [candidate, state];
1228
1508
  }
1229
1509
  }
1510
+ if (hashing.workers > 0 && total >= hashing.threshold) {
1511
+ hashing.pool ??= new HashPool(hashing.workers);
1512
+ await hashWithWorkers(files(), stage, options, hashing.pool, record);
1513
+ return results;
1514
+ }
1515
+ const { buffers } = hashing;
1516
+ function* tasks() {
1517
+ for (const [candidate, state] of files()) yield async () => {
1518
+ let digest;
1519
+ try {
1520
+ const path = options.pathOf(candidate);
1521
+ digest = stage === "sample" ? await sampleHash(path, candidate.bytes, buffers) : await hashFileOfSize(path, candidate.bytes, buffers);
1522
+ } catch (error) {
1523
+ digest = error instanceof Error ? error : new Error(String(error));
1524
+ }
1525
+ record(candidate, state, digest);
1526
+ };
1527
+ }
1230
1528
  await runLimited(tasks(), options.concurrency, signal);
1231
1529
  return results;
1232
1530
  }
1233
1531
  /**
1532
+ * Hashes a stage on the worker pool, in batches, with two batches in flight
1533
+ * per worker so none waits for the next. Workers finish in any order; the
1534
+ * results are grouped and later sorted the same way as on the main thread.
1535
+ */
1536
+ async function hashWithWorkers(files, stage, options, pool, record) {
1537
+ const sample = stage === "sample";
1538
+ function* batches() {
1539
+ for (;;) {
1540
+ const batch = [];
1541
+ const jobs = [];
1542
+ while (batch.length < WORKER_BATCH) {
1543
+ const next = files.next();
1544
+ if (next.done) break;
1545
+ const [candidate] = next.value;
1546
+ batch.push(next.value);
1547
+ jobs.push([
1548
+ options.pathOf(candidate),
1549
+ candidate.bytes,
1550
+ sample
1551
+ ]);
1552
+ }
1553
+ if (batch.length === 0) return;
1554
+ yield async () => {
1555
+ const outcomes = await pool.run(jobs);
1556
+ for (let i = 0; i < batch.length; i++) {
1557
+ const [candidate, state] = batch[i];
1558
+ const outcome = outcomes[i];
1559
+ record(candidate, state, typeof outcome === "string" ? outcome : Object.assign(new Error(outcome.message), { code: outcome.code }));
1560
+ }
1561
+ };
1562
+ }
1563
+ }
1564
+ const signal = options.signal;
1565
+ const onAbort = () => void pool.close();
1566
+ signal?.addEventListener("abort", onAbort, { once: true });
1567
+ try {
1568
+ await runLimited(batches(), pool.size * 2, signal);
1569
+ } catch (error) {
1570
+ throw signal?.aborted ? new AbortError() : error;
1571
+ } finally {
1572
+ signal?.removeEventListener("abort", onAbort);
1573
+ }
1574
+ }
1575
+ /**
1234
1576
  * Runs tasks from a lazy iterator with at most `concurrency` in flight, so a
1235
1577
  * million-file stage never materializes a million closures up front.
1236
1578
  */
@@ -1261,7 +1603,7 @@ async function runLimited(tasks, concurrency, signal) {
1261
1603
  /** Streams a file through SHA-256 and returns the hex digest. */
1262
1604
  async function hashFile(path, buffer) {
1263
1605
  const hasher = createHash(ALGORITHM);
1264
- const handle = await open(path, "r");
1606
+ const handle = await open$1(path, "r");
1265
1607
  try {
1266
1608
  const chunk = buffer ?? Buffer.allocUnsafe(READ_BUFFER_BYTES);
1267
1609
  let position = 0;
@@ -1276,25 +1618,48 @@ async function hashFile(path, buffer) {
1276
1618
  }
1277
1619
  return hasher.digest("hex");
1278
1620
  }
1279
- /** Hashes a file whose size is known: one read for small files, streaming otherwise. */
1621
+ /**
1622
+ * Hashes a file whose size is known: small files in a single read into a
1623
+ * pooled buffer, larger ones streamed. Either way the digest covers the
1624
+ * whole file as it is now, even if it changed size since it was measured.
1625
+ */
1280
1626
  async function hashFileOfSize(path, size, buffers) {
1281
- if (size <= SAMPLE_THRESHOLD) return hash(ALGORITHM, await readWhole(path), "hex");
1282
- const buffer = buffers?.acquire();
1627
+ const buffer = buffers.acquire();
1283
1628
  try {
1629
+ if (size <= SAMPLE_THRESHOLD) {
1630
+ const whole = await readSmall(path, size, buffer);
1631
+ if (whole !== null) return hash(ALGORITHM, whole, "hex");
1632
+ }
1284
1633
  return await hashFile(path, buffer);
1285
1634
  } finally {
1286
- if (buffer) buffers.release(buffer);
1635
+ buffers.release(buffer);
1287
1636
  }
1288
1637
  }
1289
- function readWhole(path) {
1638
+ /**
1639
+ * Reads a small file with open, one read and close: no `fstat` and no new
1640
+ * buffer, unlike `readFile`, and one promise for all three calls. Asking for
1641
+ * one byte more than expected makes a short read prove the end of the file.
1642
+ * Resolves to null when the file has grown past that, so the caller streams
1643
+ * it instead.
1644
+ */
1645
+ function readSmall(path, size, buffer) {
1290
1646
  return new Promise((resolve, reject) => {
1291
- readFile(path, (error, data) => error ? reject(error) : resolve(data));
1647
+ open(path, "r", (openError, fd) => {
1648
+ if (openError) return reject(openError);
1649
+ const wanted = size + 1;
1650
+ read(fd, buffer, 0, wanted, 0, (readError, bytesRead) => {
1651
+ close(fd, () => {
1652
+ if (readError) reject(readError);
1653
+ else resolve(bytesRead < wanted ? buffer.subarray(0, bytesRead) : null);
1654
+ });
1655
+ });
1656
+ });
1292
1657
  });
1293
1658
  }
1294
1659
  async function sampleHash(path, size, buffers) {
1295
1660
  const hasher = createHash(ALGORITHM);
1296
1661
  const buffer = buffers.acquire();
1297
- const handle = await open(path, "r");
1662
+ const handle = await open$1(path, "r");
1298
1663
  try {
1299
1664
  for (const position of [0, Math.max(0, size - SAMPLE_BYTES)]) {
1300
1665
  const { bytesRead } = await handle.read(buffer, 0, SAMPLE_BYTES, position);
@@ -1332,16 +1697,6 @@ async function distinctInodes(group, pathOf) {
1332
1697
  }
1333
1698
  return distinct;
1334
1699
  }
1335
- /** Reuses read buffers so streaming large files allocates a fixed amount of memory. */
1336
- var BufferPool = class {
1337
- #free = [];
1338
- acquire() {
1339
- return this.#free.pop() ?? Buffer.allocUnsafe(READ_BUFFER_BYTES);
1340
- }
1341
- release(buffer) {
1342
- this.#free.push(buffer);
1343
- }
1344
- };
1345
1700
  // src/core/gitignore.ts
1346
1701
  /**
1347
1702
  * The compiled rules of one ignore file.
@@ -1894,7 +2249,7 @@ var Excluder = class {
1894
2249
  }
1895
2250
  /** Builds the scope for a `.gitignore` found at `rootRelativeDir` (`''` for the root). */
1896
2251
  async loadScope(filePath, rootRelativeDir) {
1897
- const content = await readFile$1(filePath, "utf8").catch(() => null);
2252
+ const content = await readFile(filePath, "utf8").catch(() => null);
1898
2253
  if (content === null) return null;
1899
2254
  const matcher = this.#compile(content);
1900
2255
  if (!matcher.hasRules) return null;
@@ -1943,7 +2298,7 @@ var Excluder = class {
1943
2298
  const scopes = [];
1944
2299
  const outermostFirst = repoRoot === root ? [] : ancestors.reverse();
1945
2300
  const add = async (file, base, kind) => {
1946
- const content = await readFile$1(file, "utf8").catch(() => null);
2301
+ const content = await readFile(file, "utf8").catch(() => null);
1947
2302
  if (content === null) return;
1948
2303
  const matcher = this.#compile(content);
1949
2304
  if (!matcher.hasRules) return;
@@ -1978,12 +2333,12 @@ var Excluder = class {
1978
2333
  */
1979
2334
  async function findInfoExclude(repoRoot) {
1980
2335
  const dotGit = join(repoRoot, ".git");
1981
- const pointer = await readFile$1(dotGit, "utf8").catch(() => null);
2336
+ const pointer = await readFile(dotGit, "utf8").catch(() => null);
1982
2337
  if (pointer === null) return join(dotGit, "info", "exclude");
1983
2338
  const gitDir = /^gitdir:\s*(.+?)\s*$/m.exec(pointer)?.[1];
1984
2339
  if (gitDir === void 0) return null;
1985
2340
  const dir = resolve(repoRoot, gitDir);
1986
- const commonDir = await readFile$1(join(dir, "commondir"), "utf8").catch(() => null);
2341
+ const commonDir = await readFile(join(dir, "commondir"), "utf8").catch(() => null);
1987
2342
  return join(commonDir === null ? dir : resolve(dir, commonDir.trim()), "info", "exclude");
1988
2343
  }
1989
2344
  function isGitIgnored(chain, relPath, isDirectory) {
@@ -2493,7 +2848,7 @@ var Collector = class {
2493
2848
  return result;
2494
2849
  }
2495
2850
  #largestDirectories(scanner) {
2496
- const top = new TopK(this.#features.top, (a, b) => comparePaths(scanner.relativePath(a), scanner.relativePath(b)));
2851
+ const top = new TopK(this.#features.top, (a, b) => scanner.compareRelative(a, void 0, b, void 0));
2497
2852
  const dirs = scanner.dirs;
2498
2853
  for (let i = 1; i < dirs.length; i++) {
2499
2854
  const node = dirs[i];
@@ -2558,9 +2913,9 @@ var Collector = class {
2558
2913
  }
2559
2914
  return result;
2560
2915
  }
2916
+ /** Ties in the largest-files heap: path order, without building the paths (#31). */
2561
2917
  #compareRefs(a, b) {
2562
- const scanner = this.#scanner;
2563
- return comparePaths(scanner.relativePath(a.dir, a.name), scanner.relativePath(b.dir, b.name));
2918
+ return this.#scanner.compareRelative(a.dir, a.name, b.dir, b.name);
2564
2919
  }
2565
2920
  };
2566
2921
  function createProgressReporter(report, interval, snapshot) {
@@ -2817,15 +3172,14 @@ function side(root, scanner, index) {
2817
3172
  }
2818
3173
  async function findContentChanges(paths, sizeOf, leftRoot, rightRoot, options) {
2819
3174
  const differing = /* @__PURE__ */ new Set();
3175
+ const buffers = new BufferPool(COMPARE_CHUNK_BYTES);
2820
3176
  const limiter = new Limiter(options.concurrency ?? 32);
2821
3177
  const onAbort = () => limiter.abort(new AbortError());
2822
3178
  options.signal?.addEventListener("abort", onAbort, { once: true });
2823
3179
  let done = 0;
2824
3180
  for (const path of paths) limiter.run(async () => {
2825
3181
  try {
2826
- const bytes = sizeOf(path);
2827
- const [l, r] = await Promise.all([hashFileOfSize(joinRelative(leftRoot, path), bytes), hashFileOfSize(joinRelative(rightRoot, path), bytes)]);
2828
- if (l !== r) differing.add(path);
3182
+ if (!await sameContent(joinRelative(leftRoot, path), joinRelative(rightRoot, path), sizeOf(path), buffers)) differing.add(path);
2829
3183
  } catch {
2830
3184
  differing.add(path);
2831
3185
  } finally {
@@ -3856,7 +4210,7 @@ async function loadConfig(options) {
3856
4210
  };
3857
4211
  let text;
3858
4212
  try {
3859
- text = await readFile$1(path, "utf8");
4213
+ text = await readFile(path, "utf8");
3860
4214
  } catch (error) {
3861
4215
  throw new DatError(errorCode(error) === "ENOENT" ? `Config file not found: ${path}` : `Cannot read config ${path}: ${errorMessage(error)}`);
3862
4216
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dir-analysis-tool",
3
- "version": "3.5.4",
3
+ "version": "3.5.6",
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": {
@@ -712,7 +712,7 @@
712
712
  },
713
713
  "mode": {
714
714
  "enum": ["size", "content"],
715
- "description": "How changed was decided: by size only, or by size then content hash."
715
+ "description": "How changed was decided: by size only, or by size and then by content."
716
716
  },
717
717
  "left": {
718
718
  "$ref": "#/$defs/side"