dir-analysis-tool 3.5.1 → 3.5.3

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
@@ -186,18 +186,18 @@ A size tree (`dat src -t --tree-depth 2`):
186
186
 
187
187
  **Output options:**
188
188
 
189
- | Option | Description |
190
- | ----------------------- | -------------------------------------------------------------------------------------- |
191
- | `-f, --format <format>` | `pretty` (default), `json`, `markdown`, `csv`, or `html`. |
192
- | `-j, --json` | Same as `--format json`. |
193
- | `--compact` | One-line JSON with every list cut to `--top` items. See [Compact JSON](#compact-json). |
194
- | `-o, --output <file>` | Write the report to a file instead of stdout. |
195
- | `--html [file.html]` | Also write an HTML report. Default name `directory-analysis-<date>.html`. |
196
- | `--csv [file.csv]` | Also write a CSV export. Default name `directory-analysis.csv`. |
197
- | `--si` | Decimal units (kB, MB, powers of 1000) instead of binary (KiB, MiB, powers of 1024). |
198
- | `--color`, `--no-color` | Force colors on or off. `NO_COLOR` and `FORCE_COLOR` are honored. |
199
- | `--no-progress` | Hide the progress line. It is only ever drawn on an interactive stderr. |
200
- | `-q, --quiet` | Print only the report and errors. |
189
+ | Option | Description |
190
+ | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
191
+ | `-f, --format <format>` | `pretty` (default), `json`, `markdown`, `csv`, or `html`. |
192
+ | `-j, --json` | Same as `--format json`. |
193
+ | `--compact` | One-line JSON with every list cut to `--top` items. See [Compact JSON](#compact-json). |
194
+ | `-o, --output <file>` | Write the report to a file instead of stdout. Missing folders are created. A path that can't be written (a directory, a read-only folder) is an error before the scan starts, as for `--html` and `--csv`. |
195
+ | `--html [file.html]` | Also write an HTML report. Default name `directory-analysis-<date>.html`. |
196
+ | `--csv [file.csv]` | Also write a CSV export. Default name `directory-analysis.csv`. |
197
+ | `--si` | Decimal units (kB, MB, powers of 1000) instead of binary (KiB, MiB, powers of 1024). |
198
+ | `--color`, `--no-color` | Force colors on or off. `NO_COLOR` and `FORCE_COLOR` are honored. |
199
+ | `--no-progress` | Hide the progress line. It is only ever drawn on an interactive stderr. |
200
+ | `-q, --quiet` | Print only the report and errors. |
201
201
 
202
202
  ### `dat compare`
203
203
 
@@ -228,11 +228,11 @@ A size tree (`dat src -t --tree-depth 2`):
228
228
  2 files unchanged (compared by size)
229
229
  ```
230
230
 
231
- | Option | Description |
232
- | ----------------------- | ------------------------------------------------------------------------------------------- |
233
- | `--content` | Also compare same-sized files by content (SHA-256). By default, files are compared by size. |
234
- | `-n, --top <n>` | Items per list. Default `10`. |
235
- | `-f, --format <format>` | `pretty`, `json`, `markdown`, or `csv`. |
231
+ | Option | Description |
232
+ | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
233
+ | `--content` | Also compare same-sized files by content (SHA-256). By default, files are compared by size. |
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
+ | `-f, --format <format>` | `pretty`, `json`, `markdown`, or `csv`. |
236
236
 
237
237
  All scan options and shared output options above are accepted too; `--html`, `--csv`, and HTML format are analyze-only. Use `--format csv` to export a comparison.
238
238
 
@@ -289,13 +289,19 @@ All scan options are accepted, as are `--si`, `--color`, `--no-color`, `--no-pro
289
289
 
290
290
  ### `dat watch`
291
291
 
292
- `dat watch [directory] [options]` re-analyzes whenever something changes. It uses the operating system's native file watching: recursive on macOS and Windows; on Linux, one watcher per scanned folder, so skipped folders like `node_modules` are never watched. If watching fails, it falls back to polling.
292
+ `dat watch [directory] [options]` re-analyzes whenever something changes. It uses the operating system's native file watching: recursive on macOS and Windows; on Linux, one watcher per scanned folder, so skipped folders like `node_modules` are never watched. If watching fails, it falls back to polling every 5 seconds.
293
293
 
294
294
  ```bash
295
295
  dat watch . -l 1GB # keep an eye on large files
296
296
  dat watch . --json | jq -c .summary # one JSON document per line (NDJSON)
297
+ dat watch . -j -o report.json # keep report.json up to date
297
298
  ```
298
299
 
300
+ - **Output.** Without `-o`, each report goes to stdout: pretty reports replace the previous one on a terminal (`--no-clear` keeps them), and JSON reports are printed one per line (NDJSON). With `-o`, the file is rewritten with the latest report on each change, in either format. The report file counts in the analysis like any other file, but writing it never starts a new scan, even inside the watched folder.
301
+ - **`--poll`.** A new report is printed only when it would differ from the previous one, for any reason: a size, a date, a stale or empty file, a duplicate.
302
+ - **A missing root.** A directory that doesn't exist (or isn't a directory) when `watch` starts is an error: one message, exit code `1`. If the watched directory is deleted later, `watch` says so once and waits; when it comes back, it reports again and resumes watching, on every platform and with `--poll`.
303
+ - **Stopping.** Ctrl+C stops `watch` with exit code `130`, as for every command. It also stops on its own, with exit code `0`, when the reader of its output goes away (`dat watch --json | head -1`).
304
+
299
305
  | Option | Description |
300
306
  | ------------------ | ---------------------------------------------------------- |
301
307
  | `--debounce <ms>` | Wait this long after the last change. Default `300`. |
@@ -545,12 +551,12 @@ The benchmark script reports scan and duplicate timings plus process peak RSS (n
545
551
 
546
552
  ## Exit codes
547
553
 
548
- | Code | Meaning |
549
- | ----- | ------------------------------------------------------------- |
550
- | `0` | Success, including every `dat explain` decision |
551
- | `1` | Error: invalid option or config, missing directory, and so on |
552
- | `2` | A budget failed |
553
- | `130` | Interrupted (Ctrl+C) |
554
+ | Code | Meaning |
555
+ | ----- | -------------------------------------------------------------------------------------------------- |
556
+ | `0` | Success, including every `dat explain` decision |
557
+ | `1` | Error: invalid option or config, missing directory, a report file that can't be written, and so on |
558
+ | `2` | A budget failed |
559
+ | `130` | Interrupted (Ctrl+C), including stopping `dat watch` |
554
560
 
555
561
  A reader that stops early (`dat . --json | head`) doesn't change the exit code: a failed budget still exits `2`.
556
562
 
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import { $ as errorMessage, C as MAX_EXPLAIN_LIMIT, D as outsideRootError, E as isOutside, G as parseSize, H as formatBudgetActual, I as Excluder, L as joinRelative, M as analyze, O as compare, P as listDirectories, Q as errorCode, T as explainSkips, U as parseBudget, W as formatBytes, X as AbortError, Y as parsePointInTime, Z as DatError, a as renderComparisonCsv, c as renderAnalysis, d as escapeControlInLines, 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, q as VERSION, r as renderAnalysisHtml, s as renderComparisonMarkdown, t as renderPathExplanation, u as escapeControl, v as loadConfig, w as explainPath } from "./shared-zG-LAgcd.js";
3
- import { existsSync, watch } from "node:fs";
4
- import { mkdir, writeFile } from "node:fs/promises";
5
- import { dirname, join, relative, resolve, sep } from "node:path";
2
+ import { $ as errorCode, C as MAX_EXPLAIN_LIMIT, D as outsideRootError, E as isOutside, F as listDirectories, G as formatBytes, J as VERSION, K as parseSize, L as Excluder, M as analyze, O as compare, P as assertDirectory, Q as DatError, R as joinRelative, T as explainSkips, U as formatBudgetActual, W as parseBudget, X as parsePointInTime, Z as AbortError, a as renderComparisonCsv, c as renderAnalysis, d as escapeControlInLines, et as errorMessage, f as formatCount, h as supportsColor, i as renderAnalysisCsv, k as compactAnalysis, l as renderComparison, m as createStyle, n as renderSkipsExplanation, o as renderAnalysisMarkdown, p as stringifyJson, r as renderAnalysisHtml, s as renderComparisonMarkdown, t as renderPathExplanation, u as escapeControl, v as loadConfig, w as explainPath } from "./shared-BJ-V9aTZ.js";
3
+ import { constants, existsSync, watch } from "node:fs";
4
+ import { access, mkdir, realpath, stat, writeFile } from "node:fs/promises";
5
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
6
  import { createInterface } from "node:readline";
7
7
  // src/cli/io.ts
8
8
  function processIO(signal) {
@@ -920,6 +920,7 @@ function registerAnalyze(program, ctx) {
920
920
  const { config } = await ctx.loadConfig(cli, target);
921
921
  const display = resolveDisplay(cli, config);
922
922
  const options = resolveAnalyzeOptions(cli, config);
923
+ await checkOutputs(ctx, display);
923
924
  const result = await runAnalysis(ctx, target, options, display);
924
925
  await emit(ctx, result, display, listLimit(options.top));
925
926
  reportBudgets(ctx, result, display);
@@ -937,18 +938,34 @@ async function runAnalysis(ctx, target, options, display) {
937
938
  progress.clear();
938
939
  }
939
940
  }
940
- async function emit(ctx, result, display, limit) {
941
+ /** The files a run writes, with the name each error message uses. */
942
+ function outputFiles(ctx, display) {
941
943
  const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
942
- if (display.html) {
943
- const file = await ctx.writeFile(display.html === true ? `directory-analysis-${today}.html` : display.html, renderAnalysisHtml(result, { units: display.units }));
944
- ctx.info(`${ctx.err.green("✔")} HTML report written to ${displayPath(ctx, file)}`, display.quiet);
944
+ const output = display.output ?? (display.format === "html" && ctx.io.stdout.isTTY ? `directory-analysis-${today}.html` : void 0);
945
+ return {
946
+ ...display.html ? { html: display.html === true ? `directory-analysis-${today}.html` : display.html } : {},
947
+ ...display.csv ? { csv: display.csv === true ? "directory-analysis.csv" : display.csv } : {},
948
+ ...output ? { output } : {}
949
+ };
950
+ }
951
+ /** Fails before the scan when a report file can't be written, instead of after it. */
952
+ async function checkOutputs(ctx, display) {
953
+ const files = outputFiles(ctx, display);
954
+ if (files.html) await ctx.checkOutput(files.html, "the HTML report");
955
+ if (files.csv) await ctx.checkOutput(files.csv, "the CSV export");
956
+ if (files.output) await ctx.checkOutput(files.output);
957
+ }
958
+ async function emit(ctx, result, display, limit) {
959
+ const files = outputFiles(ctx, display);
960
+ if (files.html) {
961
+ const file = await ctx.writeFile(files.html, renderAnalysisHtml(result, { units: display.units }), "the HTML report");
962
+ ctx.info(`${ctx.err.green("✔")} HTML report written to ${ctx.displayPath(file)}`, display.quiet);
945
963
  }
946
- if (display.csv) {
947
- const file = await ctx.writeFile(display.csv === true ? "directory-analysis.csv" : display.csv, renderAnalysisCsv(result));
948
- ctx.info(`${ctx.err.green("✔")} CSV written to ${displayPath(ctx, file)}`, display.quiet);
964
+ if (files.csv) {
965
+ const file = await ctx.writeFile(files.csv, renderAnalysisCsv(result), "the CSV export");
966
+ ctx.info(`${ctx.err.green("✔")} CSV written to ${ctx.displayPath(file)}`, display.quiet);
949
967
  }
950
- let output = display.output;
951
- if (!output && display.format === "html" && ctx.io.stdout.isTTY) output = `directory-analysis-${today}.html`;
968
+ const output = files.output;
952
969
  const text = display.compact ? stringifyJson(compactAnalysis(result, { limit })) : renderAnalysisAs(display.format, result, {
953
970
  style: ctx.outputStyle(display.color, output !== void 0),
954
971
  units: display.units,
@@ -959,7 +976,7 @@ async function emit(ctx, result, display, limit) {
959
976
  });
960
977
  if (output) {
961
978
  const file = await ctx.writeFile(output, text);
962
- ctx.info(`${ctx.err.green("✔")} Report written to ${displayPath(ctx, file)}`, display.quiet);
979
+ ctx.info(`${ctx.err.green("✔")} Report written to ${ctx.displayPath(file)}`, display.quiet);
963
980
  } else await ctx.stdout(text.endsWith("\n") ? text : `${text}\n`);
964
981
  }
965
982
  function reportBudgets(ctx, result, display) {
@@ -972,10 +989,6 @@ function reportBudgets(ctx, result, display) {
972
989
  ctx.io.stderr.write(`${ctx.err.red("budget failed")} ${budget.rule} (actual ${actual})\n`);
973
990
  }
974
991
  }
975
- function displayPath(ctx, file) {
976
- const rel = relative(ctx.io.cwd, file);
977
- return escapeControl(rel && !rel.startsWith("..") ? rel : file);
978
- }
979
992
  /** Items printed per list: the --top value, or 10 when the top lists are turned off. */
980
993
  function listLimit(top) {
981
994
  return top !== void 0 && top > 0 ? top : 10;
@@ -991,7 +1004,7 @@ Examples:
991
1004
  function registerCompare(program, ctx) {
992
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");
993
1006
  addScanOptions(command);
994
- 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)").argParser(integer(0)).helpGroup("Report options:"));
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:"));
995
1008
  addOutputOptions(command, [
996
1009
  "pretty",
997
1010
  "json",
@@ -1004,6 +1017,7 @@ function registerCompare(program, ctx) {
1004
1017
  const { config } = await ctx.loadConfig(cli, ctx.io.cwd);
1005
1018
  const display = resolveDisplay(cli, config);
1006
1019
  const top = read.number(cli["top"]) ?? config.top;
1020
+ if (display.output) await ctx.checkOutput(display.output);
1007
1021
  const progress = new ProgressLine(ctx.io.stderr, display.progress && ctx.io.stderr.isTTY === true, ctx.err, display.units);
1008
1022
  let result;
1009
1023
  try {
@@ -1021,13 +1035,13 @@ function registerCompare(program, ctx) {
1021
1035
  style: ctx.outputStyle(display.color, display.output !== void 0),
1022
1036
  units: display.units,
1023
1037
  width: terminalWidth(ctx.io),
1024
- limit: listLimit(top),
1038
+ limit: top ?? 10,
1025
1039
  types: display.types,
1026
1040
  extensions: false
1027
1041
  });
1028
1042
  if (display.output) {
1029
1043
  const file = await ctx.writeFile(display.output, text);
1030
- ctx.info(`${ctx.err.green("✔")} Comparison written to ${escapeControl(file)}`, display.quiet);
1044
+ ctx.info(`${ctx.err.green("✔")} Comparison written to ${ctx.displayPath(file)}`, display.quiet);
1031
1045
  } else await ctx.stdout(text.endsWith("\n") ? text : `${text}\n`);
1032
1046
  });
1033
1047
  }
@@ -1232,7 +1246,9 @@ var Prompter = class {
1232
1246
  const SCHEMA_URL = "https://unpkg.com/dir-analysis-tool@3/schema.json";
1233
1247
  function registerInit(program, ctx) {
1234
1248
  program.command("init").description("create a .dir-analyzer.json config file").argument("[directory]", "where to create the file", ".").addOption(new Option("-y, --yes", "skip the questions and write a starter config")).addOption(new Option("--force", "overwrite an existing config file")).action(async (directory, options) => {
1235
- const path = join(ctx.resolvePath(directory), ".dir-analyzer.json");
1249
+ const folder = ctx.resolvePath(directory);
1250
+ if (await isFile(folder)) throw new DatError(`dat init: ${ctx.displayPath(folder)} is not a directory`);
1251
+ const path = join(folder, ".dir-analyzer.json");
1236
1252
  const exists = existsSync(path);
1237
1253
  if (exists && !options.force && (options.yes || !ctx.io.stdinIsTTY)) throw new DatError(`${path} already exists.`, { hint: "Use --force to overwrite it." });
1238
1254
  let config;
@@ -1249,7 +1265,7 @@ function registerInit(program, ctx) {
1249
1265
  const file = await ctx.writeFile(path, `${JSON.stringify({
1250
1266
  $schema: SCHEMA_URL,
1251
1267
  ...config
1252
- }, null, 4)}\n`);
1268
+ }, null, 4)}\n`, "the config file");
1253
1269
  ctx.info(`${ctx.err.green("✔")} Wrote ${escapeControl(file)}`, false);
1254
1270
  });
1255
1271
  }
@@ -1346,6 +1362,10 @@ function validateWith(value, parse) {
1346
1362
  return errorMessage(error);
1347
1363
  }
1348
1364
  }
1365
+ /** True when `path` exists and is not a directory (dat init creates a missing one). */
1366
+ async function isFile(path) {
1367
+ return stat(path).then((stats) => !stats.isDirectory(), () => false);
1368
+ }
1349
1369
  // src/cli/watcher.ts
1350
1370
  /**
1351
1371
  * Watches a directory tree with the platform's native facility.
@@ -1422,6 +1442,7 @@ Examples:
1422
1442
  $ dat watch ./downloads -l 1GB keep an eye on large downloads
1423
1443
  $ dat watch . --json | jq -c .summary
1424
1444
  one JSON document per line (NDJSON)
1445
+ $ dat watch . -j -o report.json keep report.json up to date
1425
1446
  `;
1426
1447
  function registerWatch(program, ctx) {
1427
1448
  const command = program.command("watch").description("re-analyze a directory whenever it changes").argument("[directory]", "directory to watch", ".");
@@ -1441,18 +1462,28 @@ function registerWatch(program, ctx) {
1441
1462
  const pollSeconds = read.number(cli["poll"]);
1442
1463
  const clear = cli["clear"] !== false && display.format === "pretty" && ctx.io.stdout.isTTY === true;
1443
1464
  const signal = ctx.io.signal;
1465
+ await assertDirectory(target);
1466
+ await checkOutputs(ctx, {
1467
+ ...display,
1468
+ html: void 0,
1469
+ csv: void 0
1470
+ });
1444
1471
  let previous = null;
1472
+ let previousKey = "";
1445
1473
  let running = false;
1446
1474
  let pending = false;
1447
1475
  let timer = null;
1448
1476
  let changes = 0;
1449
- let polling = false;
1477
+ let polling = pollSeconds !== void 0;
1478
+ let rootGone = false;
1479
+ let rootCheck = null;
1450
1480
  const excluder = new Excluder({
1451
1481
  patterns: options.exclude ?? [],
1452
1482
  defaultExcludes: options.defaultExcludes ?? true
1453
1483
  });
1484
+ let ownFiles = /* @__PURE__ */ new Set();
1454
1485
  const render = async (result) => {
1455
- if (display.format === "json") {
1486
+ if (display.format === "json" && !display.output) {
1456
1487
  await ctx.stdout(`${stringifyJson(result)}\n`);
1457
1488
  return;
1458
1489
  }
@@ -1462,6 +1493,7 @@ function registerWatch(program, ctx) {
1462
1493
  html: void 0,
1463
1494
  csv: void 0
1464
1495
  }, listLimit(options.top));
1496
+ if (display.format === "json") return;
1465
1497
  const status = previous ? describeChange(previous, result, display.units) : "initial scan";
1466
1498
  ctx.info(ctx.err.dim(`watching ${escapeControl(target)} · ${status} · ${(/* @__PURE__ */ new Date()).toLocaleTimeString()} · Ctrl+C to stop`), display.quiet);
1467
1499
  };
@@ -1469,7 +1501,83 @@ function registerWatch(program, ctx) {
1469
1501
  const stopped = new Promise((resolve) => stopWatching = resolve);
1470
1502
  const readerGone = () => ctx.stdoutClosed;
1471
1503
  let watcher = null;
1472
- const run = async () => {
1504
+ let poller = null;
1505
+ const closeWatcher = () => {
1506
+ watcher?.close();
1507
+ watcher = null;
1508
+ };
1509
+ const schedule = () => {
1510
+ changes++;
1511
+ if (timer) clearTimeout(timer);
1512
+ timer = setTimeout(() => void run(), debounce);
1513
+ };
1514
+ const startPolling = (seconds) => {
1515
+ polling = true;
1516
+ if (rootCheck) clearInterval(rootCheck);
1517
+ rootCheck = null;
1518
+ poller = setInterval(() => void run(), seconds * 1e3);
1519
+ };
1520
+ const markRootGone = () => {
1521
+ if (rootGone) return;
1522
+ rootGone = true;
1523
+ ctx.warn(`${escapeControl(target)} was removed; waiting for it to come back (Ctrl+C to stop)`);
1524
+ closeWatcher();
1525
+ };
1526
+ const checkRoot = async () => {
1527
+ if (running) return;
1528
+ if (rootGone || !await isDirectory(target)) await run();
1529
+ };
1530
+ const watchFailed = async (failed, error) => {
1531
+ failed.close();
1532
+ if (watcher === failed) watcher = null;
1533
+ if (!await isDirectory(target)) {
1534
+ schedule();
1535
+ return;
1536
+ }
1537
+ ctx.warn(`file watching failed (${escapeControl(error.message)}); falling back to polling every 5 seconds`);
1538
+ if (!poller) startPolling(5);
1539
+ };
1540
+ const syncWatcher = async () => {
1541
+ if (polling || signal?.aborted) return;
1542
+ if (!watcher) {
1543
+ if (display.output) ownFiles = await ownFileEvents(target, ctx.resolvePath(display.output));
1544
+ const created = new TreeWatcher({
1545
+ root: target,
1546
+ isIgnored: (rel) => ownFiles.has(rel) || excluder.isPathExcluded(rel),
1547
+ onChange: schedule,
1548
+ onError: (error) => void watchFailed(created, error)
1549
+ });
1550
+ watcher = created;
1551
+ if (created.recursive) {
1552
+ created.sync([]);
1553
+ return;
1554
+ }
1555
+ }
1556
+ if (watcher && !watcher.recursive) watcher.sync(await listDirectories(target, options));
1557
+ };
1558
+ const scan = async () => {
1559
+ if (!await isDirectory(target)) {
1560
+ markRootGone();
1561
+ return null;
1562
+ }
1563
+ if (rootGone) {
1564
+ rootGone = false;
1565
+ changes++;
1566
+ }
1567
+ try {
1568
+ return await runAnalysis(ctx, target, options, {
1569
+ ...display,
1570
+ progress: display.progress && previous === null
1571
+ });
1572
+ } catch (error) {
1573
+ if (!(error instanceof AbortError) && !await isDirectory(target)) {
1574
+ markRootGone();
1575
+ return null;
1576
+ }
1577
+ throw error;
1578
+ }
1579
+ };
1580
+ const run = async (initial = false) => {
1473
1581
  if (running) {
1474
1582
  pending = true;
1475
1583
  return;
@@ -1478,11 +1586,10 @@ function registerWatch(program, ctx) {
1478
1586
  try {
1479
1587
  for (;;) {
1480
1588
  pending = false;
1481
- const result = await runAnalysis(ctx, target, options, {
1482
- ...display,
1483
- progress: display.progress && previous === null
1484
- });
1485
- if (!polling || !previous || changes > 0 || fingerprint(previous) !== fingerprint(result)) {
1589
+ const result = await scan();
1590
+ if (!result) break;
1591
+ const key = reportKey(result);
1592
+ if (!polling || !previous || changes > 0 || key !== previousKey) {
1486
1593
  await render(result);
1487
1594
  if (readerGone()) {
1488
1595
  stopWatching();
@@ -1490,57 +1597,76 @@ function registerWatch(program, ctx) {
1490
1597
  }
1491
1598
  }
1492
1599
  previous = result;
1600
+ previousKey = key;
1493
1601
  changes = 0;
1494
- if (watcher && !watcher.recursive) watcher.sync(await listDirectories(target, options));
1602
+ try {
1603
+ await syncWatcher();
1604
+ } catch (error) {
1605
+ if (await isDirectory(target)) throw error;
1606
+ markRootGone();
1607
+ break;
1608
+ }
1495
1609
  if (!pending || signal?.aborted) break;
1496
1610
  }
1497
1611
  } catch (error) {
1498
1612
  if (error instanceof AbortError) return;
1613
+ if (initial) throw error;
1499
1614
  ctx.io.stderr.write(`${ctx.err.red("error")} ${escapeControlInLines(errorMessage(error))}\n`);
1500
1615
  } finally {
1501
1616
  running = false;
1502
1617
  }
1503
1618
  };
1504
- const schedule = () => {
1505
- changes++;
1506
- if (timer) clearTimeout(timer);
1507
- timer = setTimeout(() => void run(), debounce);
1508
- };
1509
- await run();
1510
- if (signal?.aborted || readerGone()) return;
1511
- let poller = null;
1512
- const startPolling = (seconds) => {
1513
- polling = true;
1514
- poller = setInterval(() => void run(), seconds * 1e3);
1515
- };
1516
- if (pollSeconds) startPolling(pollSeconds);
1517
- else {
1518
- watcher = new TreeWatcher({
1519
- root: target,
1520
- isIgnored: (rel) => excluder.isPathExcluded(rel),
1521
- onChange: schedule,
1522
- onError: (error) => {
1523
- ctx.warn(`file watching failed (${escapeControl(error.message)}); falling back to polling every 5 seconds`);
1524
- watcher?.close();
1525
- watcher = null;
1526
- if (!poller) startPolling(5);
1527
- }
1528
- });
1529
- watcher.sync(watcher.recursive ? [] : await listDirectories(target, options));
1619
+ await run(true);
1620
+ if (!signal?.aborted && !readerGone()) {
1621
+ if (pollSeconds) startPolling(pollSeconds);
1622
+ else rootCheck = setInterval(() => void checkRoot(), 1e3);
1623
+ await Promise.race([stopped, new Promise((resolve) => {
1624
+ if (!signal) return;
1625
+ if (signal.aborted) resolve();
1626
+ signal.addEventListener("abort", () => resolve(), { once: true });
1627
+ })]);
1530
1628
  }
1531
- await Promise.race([stopped, new Promise((resolve) => {
1532
- if (!signal) return;
1533
- if (signal.aborted) resolve();
1534
- signal.addEventListener("abort", () => resolve(), { once: true });
1535
- })]);
1536
1629
  if (timer) clearTimeout(timer);
1537
1630
  if (poller) clearInterval(poller);
1538
- watcher?.close();
1631
+ if (rootCheck) clearInterval(rootCheck);
1632
+ closeWatcher();
1633
+ if (signal?.aborted) throw new AbortError();
1539
1634
  });
1540
1635
  }
1541
- function fingerprint(result) {
1542
- const s = result.summary;
1543
- return `${s.bytes}:${s.files}:${s.directories}:${result.largestFiles.map((f) => `${f.path}@${f.modified}`).join("|")}`;
1636
+ /** The result without the fields that change on every scan even when nothing on disk did. */
1637
+ function reportKey(result) {
1638
+ const { startedAt: _startedAt, durationMs: _durationMs, settings, staleFiles, ...rest } = result;
1639
+ return stringifyJson({
1640
+ ...rest,
1641
+ settings: {
1642
+ ...settings,
1643
+ modifiedAfter: null,
1644
+ modifiedBefore: null
1645
+ },
1646
+ staleFiles: staleFiles && {
1647
+ ...staleFiles,
1648
+ modifiedBefore: ""
1649
+ }
1650
+ });
1651
+ }
1652
+ async function isDirectory(path) {
1653
+ return stat(path).then((stats) => stats.isDirectory(), () => false);
1654
+ }
1655
+ /**
1656
+ * The root-relative `/` paths under which the watcher may report `file`: as given, and through
1657
+ * real paths, since FSEvents can report `/private/var` for a root under `/var`.
1658
+ */
1659
+ async function ownFileEvents(root, file) {
1660
+ const paths = /* @__PURE__ */ new Set();
1661
+ const add = (base, path) => {
1662
+ const rel = relative(base, path);
1663
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel)) paths.add(rel.split(sep).join("/"));
1664
+ };
1665
+ add(root, file);
1666
+ const realRoot = await realpath(root).catch(() => root);
1667
+ const realDir = await realpath(dirname(file)).catch(() => dirname(file));
1668
+ add(realRoot, join(realDir, basename(file)));
1669
+ return paths;
1544
1670
  }
1545
1671
  function describeChange(previous, current, units) {
1546
1672
  const bytes = current.summary.bytes - previous.summary.bytes;
@@ -1590,12 +1716,36 @@ var Context = class {
1590
1716
  for (const warning of loaded.warnings) this.warn(warning);
1591
1717
  return loaded;
1592
1718
  }
1593
- async writeFile(path, content) {
1719
+ /** A path for messages: relative to the working directory when inside it, escaped. */
1720
+ displayPath(file) {
1721
+ const rel = relative(this.io.cwd, file);
1722
+ return escapeControl(rel && !rel.startsWith("..") ? rel : file);
1723
+ }
1724
+ /**
1725
+ * Fails before any work starts when `path` can't be written: it is a directory, a parent is a
1726
+ * file, or the folder is read-only. Creates nothing. `what` names the file in the message.
1727
+ */
1728
+ async checkOutput(path, what = "the report") {
1594
1729
  const absolute = this.resolvePath(path);
1595
- await mkdir(dirname(absolute), { recursive: true });
1596
- await writeFile(absolute, content);
1730
+ const problem = await outputProblem(absolute, (p) => this.displayPath(p));
1731
+ if (problem) throw this.#outputError(absolute, what, problem);
1732
+ }
1733
+ async writeFile(path, content, what = "the report") {
1734
+ const absolute = this.resolvePath(path);
1735
+ try {
1736
+ await mkdir(dirname(absolute), { recursive: true });
1737
+ await writeFile(absolute, content);
1738
+ } catch (error) {
1739
+ const problem = await outputProblem(absolute, (p) => this.displayPath(p)) ?? errorMessage(error);
1740
+ throw this.#outputError(absolute, what, problem);
1741
+ }
1597
1742
  return absolute;
1598
1743
  }
1744
+ #outputError(absolute, what, problem) {
1745
+ const shown = this.displayPath(absolute);
1746
+ const hint = problem === "it is a directory" ? `Give a file name, for example ${shown}${sep}${exampleName(what)}.` : void 0;
1747
+ return new DatError(`Cannot write ${what} to ${shown}: ${problem}`, hint ? { hint } : {});
1748
+ }
1599
1749
  stdout(text) {
1600
1750
  return write(this.io.stdout, text);
1601
1751
  }
@@ -1604,6 +1754,33 @@ var Context = class {
1604
1754
  return isClosed(this.io.stdout);
1605
1755
  }
1606
1756
  };
1757
+ /** Why `file` can't be written, or null when it can (as far as can be told without writing). */
1758
+ async function outputProblem(file, show) {
1759
+ try {
1760
+ if ((await stat(file)).isDirectory()) return "it is a directory";
1761
+ return await writable(file) ? null : "permission denied";
1762
+ } catch (error) {
1763
+ const code = errorCode(error);
1764
+ if (code === "EACCES" || code === "EPERM") return "permission denied";
1765
+ if (code !== "ENOENT" && code !== "ENOTDIR") return errorMessage(error);
1766
+ }
1767
+ for (let dir = dirname(file);; dir = dirname(dir)) try {
1768
+ if (!(await stat(dir)).isDirectory()) return `${show(dir)} is not a directory`;
1769
+ return await writable(dir) ? null : "permission denied";
1770
+ } catch (error) {
1771
+ const code = errorCode(error);
1772
+ if (code !== "ENOENT" && code !== "ENOTDIR") return code === "EACCES" || code === "EPERM" ? "permission denied" : errorMessage(error);
1773
+ if (dirname(dir) === dir) return null;
1774
+ }
1775
+ }
1776
+ async function writable(path) {
1777
+ return access(path, constants.W_OK).then(() => true, () => false);
1778
+ }
1779
+ function exampleName(what) {
1780
+ if (what.includes("HTML")) return "report.html";
1781
+ if (what.includes("CSV")) return "report.csv";
1782
+ return "report.txt";
1783
+ }
1607
1784
  // src/cli/program.ts
1608
1785
  function createProgram(ctx) {
1609
1786
  const { io } = ctx;
package/dist/index.d.ts CHANGED
@@ -222,15 +222,18 @@ export interface ComparisonResult {
222
222
  files: number;
223
223
  directories: number;
224
224
  };
225
+ /** Every added file, whatever `top` is; the CLI cuts only pretty and Markdown output. */
225
226
  added: ItemList<FileEntry>;
227
+ /** Every removed file, whatever `top` is. */
226
228
  removed: ItemList<FileEntry>;
229
+ /** Every changed file, whatever `top` is. */
227
230
  changed: {
228
231
  count: number;
229
232
  delta: number;
230
233
  items: ChangedFile[];
231
234
  };
232
235
  unchanged: number;
233
- /** Directories with the largest size change, largest absolute change first. */
236
+ /** At most `top` directories with the largest size change, largest absolute change first. */
234
237
  directories: DirectoryDelta[];
235
238
  }
236
239
  interface DuplicateProgress {
@@ -642,7 +645,7 @@ interface PrettyOptions {
642
645
  units?: ByteUnits;
643
646
  /** Terminal width used to fit paths. Default: 100. */
644
647
  width?: number;
645
- /** Maximum items printed per list. Default: 10. */
648
+ /** Maximum items printed per list. Default: 10. A comparison lists none with 0. */
646
649
  limit?: number;
647
650
  /** Show the file type breakdown. Default: true. */
648
651
  types?: boolean;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { X as AbortError, B as BUDGET_METRICS, K as CATEGORIES, g as CONFIG_FILE_NAMES, N as DEFAULT_CONCURRENCY, F as DEFAULT_EXCLUDES, x as DEFAULT_EXPLAIN_LIMIT, A as DEFAULT_LARGE_FILE_THRESHOLD, j as DEFAULT_STALE_AGE, Z as DatError, S as EXPLAIN_VERSION, C as MAX_EXPLAIN_LIMIT, q as VERSION, M as analyze, y as buildJsonSchema, R as classify, k as compactAnalysis, O as compare, m as createStyle, V as evaluateBudgets, w as explainPath, T as explainSkips, z as extensionOf, _ as findConfigFile, W as formatBytes, P as listDirectories, v as loadConfig, U as parseBudget, J as parseDuration, Y as parsePointInTime, G 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-zG-LAgcd.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-BJ-V9aTZ.js";
@@ -4180,6 +4180,8 @@ function renderTree(r, root) {
4180
4180
  function renderComparison(result, options = {}) {
4181
4181
  const r = new Renderer(options);
4182
4182
  const { s } = r;
4183
+ const limit = Math.max(0, options.limit ?? 10);
4184
+ const more = (shown, total) => limit === 0 ? r.more(0, total, `${total === 1 ? "file" : "files"} not listed (--top 0)`) : r.more(shown, total);
4183
4185
  const signed = (n) => n > 0 ? s.green(`+${r.bytes(n)}`) : n < 0 ? s.red(r.bytes(n)) : s.dim("±0");
4184
4186
  const signedCount = (n) => n > 0 ? s.green(`+${formatCount(n)}`) : n < 0 ? s.red(`-${formatCount(-n)}`) : s.dim("±0");
4185
4187
  const pct = (left, right) => {
@@ -4212,22 +4214,22 @@ function renderComparison(result, options = {}) {
4212
4214
  const fileSection = (title, list, mark) => {
4213
4215
  if (list.count === 0) return;
4214
4216
  r.heading(title, `${plural(list.count, "file")} · ${r.bytes(list.bytes)}`);
4215
- for (const f of list.items.slice(0, r.limit)) r.line(` ${mark} ${r.size(f.bytes)} ${fitPath(f.path, r.room(17))}`);
4216
- r.more(Math.min(r.limit, list.items.length), list.count);
4217
+ for (const f of list.items.slice(0, limit)) r.line(` ${mark} ${r.size(f.bytes)} ${fitPath(f.path, r.room(17))}`);
4218
+ more(Math.min(limit, list.items.length), list.count);
4217
4219
  };
4218
4220
  fileSection("Added", result.added, s.green("+"));
4219
4221
  fileSection("Removed", result.removed, s.red("-"));
4220
4222
  if (result.changed.count > 0) {
4221
4223
  r.heading("Changed", `${plural(result.changed.count, "file")} · ${result.changed.delta > 0 ? "+" : ""}${formatBytes(result.changed.delta, r.units)} net`);
4222
- for (const c of result.changed.items.slice(0, r.limit)) {
4224
+ for (const c of result.changed.items.slice(0, limit)) {
4223
4225
  const detail = c.delta === 0 ? "content" : `${r.bytes(c.leftBytes)} → ${r.bytes(c.rightBytes)}`;
4224
4226
  r.line(` ${s.yellow("~")} ${padStartVisible(signed(c.delta), SIZE_WIDTH)} ${fitPath(c.path, r.room(19 + detail.length))} ${s.dim(detail)}`);
4225
4227
  }
4226
- r.more(Math.min(r.limit, result.changed.items.length), result.changed.count);
4228
+ more(Math.min(limit, result.changed.items.length), result.changed.count);
4227
4229
  }
4228
4230
  if (result.directories.length > 0) {
4229
4231
  r.heading("Folders that changed most");
4230
- for (const d of result.directories.slice(0, r.limit)) r.line(` ${padStartVisible(signed(d.delta), 12)} ${fitPath(`${d.path}/`, r.room(17))}`);
4232
+ for (const d of result.directories.slice(0, limit)) r.line(` ${padStartVisible(signed(d.delta), 12)} ${fitPath(`${d.path}/`, r.room(17))}`);
4231
4233
  }
4232
4234
  r.line("");
4233
4235
  const identical = result.added.count + result.removed.count + result.changed.count === 0;
@@ -4426,16 +4428,22 @@ function renderComparisonMarkdown(result, options = {}) {
4426
4428
  "r",
4427
4429
  "r"
4428
4430
  ]));
4431
+ const notListed = (count) => {
4432
+ if (limit > 0) return false;
4433
+ out.push(`<sub>${plural(count, "file")} not listed (--top 0)</sub>`);
4434
+ return true;
4435
+ };
4429
4436
  const section = (title, list) => {
4430
4437
  if (list.count === 0) return;
4431
4438
  out.push("", `### ${title}: ${plural(list.count, "file")}, ${b(list.bytes)}`, "");
4439
+ if (notListed(list.count)) return;
4432
4440
  out.push(...table(["Size", "Path"], list.items.slice(0, limit).map((f) => [b(f.bytes), mdCode(f.path)]), ["r", "l"]));
4433
4441
  if (list.count > limit) out.push("", `<sub>…and ${formatCount(list.count - limit)} more</sub>`);
4434
4442
  };
4435
4443
  section("Added", result.added);
4436
4444
  section("Removed", result.removed);
4437
- if (result.changed.count > 0) {
4438
- out.push("", `### Changed: ${plural(result.changed.count, "file")}, ${signed(result.changed.delta)} net`, "");
4445
+ if (result.changed.count > 0) out.push("", `### Changed: ${plural(result.changed.count, "file")}, ${signed(result.changed.delta)} net`, "");
4446
+ if (result.changed.count > 0 && !notListed(result.changed.count)) {
4439
4447
  out.push(...table([
4440
4448
  "Change",
4441
4449
  "Path",
@@ -4969,4 +4977,4 @@ function renderSkipsExplanation(result, options = {}) {
4969
4977
  }
4970
4978
  return `${lines.join("\n")}\n`;
4971
4979
  }
4972
- export { errorMessage as $, DEFAULT_LARGE_FILE_THRESHOLD as A, BUDGET_METRICS as B, MAX_EXPLAIN_LIMIT as C, outsideRootError as D, isOutside as E, DEFAULT_EXCLUDES as F, parseSize as G, formatBudgetActual as H, Excluder as I, parseDuration as J, CATEGORIES as K, joinRelative as L, analyze as M, DEFAULT_CONCURRENCY as N, compare as O, listDirectories as P, errorCode as Q, classify as R, EXPLAIN_VERSION as S, explainSkips as T, parseBudget as U, evaluateBudgets as V, formatBytes as W, AbortError as X, parsePointInTime as Y, DatError as Z, findConfigFile as _, renderComparisonCsv as a, validateConfig as b, renderAnalysis as c, escapeControlInLines as d, formatCount as f, CONFIG_FILE_NAMES as g, supportsColor as h, renderAnalysisCsv as i, DEFAULT_STALE_AGE as j, compactAnalysis as k, renderComparison as l, createStyle as m, renderSkipsExplanation as n, renderAnalysisMarkdown as o, stringifyJson as p, VERSION as q, renderAnalysisHtml as r, renderComparisonMarkdown as s, renderPathExplanation as t, escapeControl as u, loadConfig as v, explainPath as w, DEFAULT_EXPLAIN_LIMIT as x, buildJsonSchema as y, extensionOf as z };
4980
+ export { errorCode as $, DEFAULT_LARGE_FILE_THRESHOLD as A, extensionOf as B, MAX_EXPLAIN_LIMIT as C, outsideRootError as D, isOutside as E, listDirectories as F, formatBytes as G, evaluateBudgets as H, DEFAULT_EXCLUDES as I, VERSION as J, parseSize as K, Excluder as L, analyze as M, DEFAULT_CONCURRENCY as N, compare as O, assertDirectory as P, DatError as Q, joinRelative as R, EXPLAIN_VERSION as S, explainSkips as T, formatBudgetActual as U, BUDGET_METRICS as V, parseBudget as W, parsePointInTime as X, parseDuration as Y, AbortError as Z, findConfigFile as _, renderComparisonCsv as a, validateConfig as b, renderAnalysis as c, escapeControlInLines as d, errorMessage as et, formatCount as f, CONFIG_FILE_NAMES as g, supportsColor as h, renderAnalysisCsv as i, DEFAULT_STALE_AGE as j, compactAnalysis as k, renderComparison as l, createStyle as m, renderSkipsExplanation as n, renderAnalysisMarkdown as o, stringifyJson as p, CATEGORIES as q, renderAnalysisHtml as r, renderComparisonMarkdown as s, renderPathExplanation as t, escapeControl as u, loadConfig as v, explainPath as w, DEFAULT_EXPLAIN_LIMIT as x, buildJsonSchema as y, classify as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dir-analysis-tool",
3
- "version": "3.5.1",
3
+ "version": "3.5.3",
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": {
@@ -99,7 +99,7 @@
99
99
  "oxlint-tsgolint": "^7.0.2004",
100
100
  "prettier": "^3.9.10",
101
101
  "publint": "^0.3.25",
102
- "semantic-release": "^25.0.9",
102
+ "semantic-release": "^26.0.1",
103
103
  "tsdown": "^0.23.1",
104
104
  "typescript": "^7.0.2",
105
105
  "vitest": "^5.0.5"
@@ -739,12 +739,15 @@
739
739
  }
740
740
  },
741
741
  "added": {
742
+ "description": "Every added file, whatever --top is.",
742
743
  "$ref": "#/$defs/fileList"
743
744
  },
744
745
  "removed": {
746
+ "description": "Every removed file, whatever --top is.",
745
747
  "$ref": "#/$defs/fileList"
746
748
  },
747
749
  "changed": {
750
+ "description": "Every changed file, whatever --top is.",
748
751
  "type": "object",
749
752
  "required": ["count", "delta", "items"],
750
753
  "properties": {
@@ -785,6 +788,7 @@
785
788
  "minimum": 0
786
789
  },
787
790
  "directories": {
791
+ "description": "At most --top folders with the largest size change; none with --top 0.",
788
792
  "type": "array",
789
793
  "items": {
790
794
  "type": "object",