dir-analysis-tool 3.5.5 → 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,7 +532,8 @@ 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
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
 
@@ -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. On a 500-level chain of folders holding 2,000 files of one size, 3.5.5 scans in 44 ms where 3.5.4 took 90 ms (Linux in Docker on the same M4, median of nine), the same as with the largest-files list turned off. Compared with v2.0.7 on a 140,237-file tree, v3 scans about 3× faster and finds duplicates about 4× faster, with identical results. Run `pnpm bench` (or `pnpm bench <directory>`) to measure on your machine.
549
+ 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-15TspuKg.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-15TspuKg.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.
@@ -1239,12 +1447,23 @@ async function findDuplicates(sizeGroups, options) {
1239
1447
  if (distinct.length < 2) continue;
1240
1448
  (distinct[0].bytes <= SAMPLE_THRESHOLD ? small : large).push(distinct);
1241
1449
  }
1242
- const buffers = new BufferPool();
1243
- const sampled = await hashStage(large, "sample", options, buffers);
1244
- for (const group of sampled) small.push(group.members);
1245
- 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
+ }
1246
1463
  }
1247
- 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) {
1248
1467
  let total = 0;
1249
1468
  for (const group of groups) total += group.length;
1250
1469
  const results = [];
@@ -1263,38 +1482,97 @@ async function hashStage(groups, stage, options, buffers) {
1263
1482
  members
1264
1483
  });
1265
1484
  };
1266
- 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() {
1267
1501
  for (const group of groups) {
1268
1502
  const state = {
1269
1503
  bytes: group[0].bytes,
1270
1504
  pending: group.length,
1271
1505
  byHash: /* @__PURE__ */ new Map()
1272
1506
  };
1273
- for (const candidate of group) yield async () => {
1274
- try {
1275
- const path = options.pathOf(candidate);
1276
- const digest = stage === "sample" ? await sampleHash(path, candidate.bytes, buffers) : await hashFileOfSize(path, candidate.bytes, buffers);
1277
- const members = state.byHash.get(digest);
1278
- if (members) members.push(candidate);
1279
- else state.byHash.set(digest, [candidate]);
1280
- } catch (error) {
1281
- options.onError?.(candidate, error);
1282
- } finally {
1283
- done++;
1284
- if (--state.pending === 0) finish(state);
1285
- onProgress?.({
1286
- stage,
1287
- done,
1288
- total
1289
- });
1290
- }
1291
- };
1507
+ for (const candidate of group) yield [candidate, state];
1292
1508
  }
1293
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
+ }
1294
1528
  await runLimited(tasks(), options.concurrency, signal);
1295
1529
  return results;
1296
1530
  }
1297
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
+ /**
1298
1576
  * Runs tasks from a lazy iterator with at most `concurrency` in flight, so a
1299
1577
  * million-file stage never materializes a million closures up front.
1300
1578
  */
@@ -1325,7 +1603,7 @@ async function runLimited(tasks, concurrency, signal) {
1325
1603
  /** Streams a file through SHA-256 and returns the hex digest. */
1326
1604
  async function hashFile(path, buffer) {
1327
1605
  const hasher = createHash(ALGORITHM);
1328
- const handle = await open(path, "r");
1606
+ const handle = await open$1(path, "r");
1329
1607
  try {
1330
1608
  const chunk = buffer ?? Buffer.allocUnsafe(READ_BUFFER_BYTES);
1331
1609
  let position = 0;
@@ -1340,25 +1618,48 @@ async function hashFile(path, buffer) {
1340
1618
  }
1341
1619
  return hasher.digest("hex");
1342
1620
  }
1343
- /** 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
+ */
1344
1626
  async function hashFileOfSize(path, size, buffers) {
1345
- if (size <= SAMPLE_THRESHOLD) return hash(ALGORITHM, await readWhole(path), "hex");
1346
- const buffer = buffers?.acquire();
1627
+ const buffer = buffers.acquire();
1347
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
+ }
1348
1633
  return await hashFile(path, buffer);
1349
1634
  } finally {
1350
- if (buffer) buffers.release(buffer);
1635
+ buffers.release(buffer);
1351
1636
  }
1352
1637
  }
1353
- 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) {
1354
1646
  return new Promise((resolve, reject) => {
1355
- 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
+ });
1356
1657
  });
1357
1658
  }
1358
1659
  async function sampleHash(path, size, buffers) {
1359
1660
  const hasher = createHash(ALGORITHM);
1360
1661
  const buffer = buffers.acquire();
1361
- const handle = await open(path, "r");
1662
+ const handle = await open$1(path, "r");
1362
1663
  try {
1363
1664
  for (const position of [0, Math.max(0, size - SAMPLE_BYTES)]) {
1364
1665
  const { bytesRead } = await handle.read(buffer, 0, SAMPLE_BYTES, position);
@@ -1396,16 +1697,6 @@ async function distinctInodes(group, pathOf) {
1396
1697
  }
1397
1698
  return distinct;
1398
1699
  }
1399
- /** Reuses read buffers so streaming large files allocates a fixed amount of memory. */
1400
- var BufferPool = class {
1401
- #free = [];
1402
- acquire() {
1403
- return this.#free.pop() ?? Buffer.allocUnsafe(READ_BUFFER_BYTES);
1404
- }
1405
- release(buffer) {
1406
- this.#free.push(buffer);
1407
- }
1408
- };
1409
1700
  // src/core/gitignore.ts
1410
1701
  /**
1411
1702
  * The compiled rules of one ignore file.
@@ -1958,7 +2249,7 @@ var Excluder = class {
1958
2249
  }
1959
2250
  /** Builds the scope for a `.gitignore` found at `rootRelativeDir` (`''` for the root). */
1960
2251
  async loadScope(filePath, rootRelativeDir) {
1961
- const content = await readFile$1(filePath, "utf8").catch(() => null);
2252
+ const content = await readFile(filePath, "utf8").catch(() => null);
1962
2253
  if (content === null) return null;
1963
2254
  const matcher = this.#compile(content);
1964
2255
  if (!matcher.hasRules) return null;
@@ -2007,7 +2298,7 @@ var Excluder = class {
2007
2298
  const scopes = [];
2008
2299
  const outermostFirst = repoRoot === root ? [] : ancestors.reverse();
2009
2300
  const add = async (file, base, kind) => {
2010
- const content = await readFile$1(file, "utf8").catch(() => null);
2301
+ const content = await readFile(file, "utf8").catch(() => null);
2011
2302
  if (content === null) return;
2012
2303
  const matcher = this.#compile(content);
2013
2304
  if (!matcher.hasRules) return;
@@ -2042,12 +2333,12 @@ var Excluder = class {
2042
2333
  */
2043
2334
  async function findInfoExclude(repoRoot) {
2044
2335
  const dotGit = join(repoRoot, ".git");
2045
- const pointer = await readFile$1(dotGit, "utf8").catch(() => null);
2336
+ const pointer = await readFile(dotGit, "utf8").catch(() => null);
2046
2337
  if (pointer === null) return join(dotGit, "info", "exclude");
2047
2338
  const gitDir = /^gitdir:\s*(.+?)\s*$/m.exec(pointer)?.[1];
2048
2339
  if (gitDir === void 0) return null;
2049
2340
  const dir = resolve(repoRoot, gitDir);
2050
- const commonDir = await readFile$1(join(dir, "commondir"), "utf8").catch(() => null);
2341
+ const commonDir = await readFile(join(dir, "commondir"), "utf8").catch(() => null);
2051
2342
  return join(commonDir === null ? dir : resolve(dir, commonDir.trim()), "info", "exclude");
2052
2343
  }
2053
2344
  function isGitIgnored(chain, relPath, isDirectory) {
@@ -2881,15 +3172,14 @@ function side(root, scanner, index) {
2881
3172
  }
2882
3173
  async function findContentChanges(paths, sizeOf, leftRoot, rightRoot, options) {
2883
3174
  const differing = /* @__PURE__ */ new Set();
3175
+ const buffers = new BufferPool(COMPARE_CHUNK_BYTES);
2884
3176
  const limiter = new Limiter(options.concurrency ?? 32);
2885
3177
  const onAbort = () => limiter.abort(new AbortError());
2886
3178
  options.signal?.addEventListener("abort", onAbort, { once: true });
2887
3179
  let done = 0;
2888
3180
  for (const path of paths) limiter.run(async () => {
2889
3181
  try {
2890
- const bytes = sizeOf(path);
2891
- const [l, r] = await Promise.all([hashFileOfSize(joinRelative(leftRoot, path), bytes), hashFileOfSize(joinRelative(rightRoot, path), bytes)]);
2892
- if (l !== r) differing.add(path);
3182
+ if (!await sameContent(joinRelative(leftRoot, path), joinRelative(rightRoot, path), sizeOf(path), buffers)) differing.add(path);
2893
3183
  } catch {
2894
3184
  differing.add(path);
2895
3185
  } finally {
@@ -3920,7 +4210,7 @@ async function loadConfig(options) {
3920
4210
  };
3921
4211
  let text;
3922
4212
  try {
3923
- text = await readFile$1(path, "utf8");
4213
+ text = await readFile(path, "utf8");
3924
4214
  } catch (error) {
3925
4215
  throw new DatError(errorCode(error) === "ENOENT" ? `Config file not found: ${path}` : `Cannot read config ${path}: ${errorMessage(error)}`);
3926
4216
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dir-analysis-tool",
3
- "version": "3.5.5",
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"