dir-analysis-tool 3.5.1 → 3.5.2

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
@@ -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`. |
@@ -550,7 +556,7 @@ The benchmark script reports scan and duplicate timings plus process peak RSS (n
550
556
  | `0` | Success, including every `dat explain` decision |
551
557
  | `1` | Error: invalid option or config, missing directory, and so on |
552
558
  | `2` | A budget failed |
553
- | `130` | Interrupted (Ctrl+C) |
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";
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-CwIrKaAV.js";
3
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";
4
+ import { 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) {
@@ -1422,6 +1422,7 @@ Examples:
1422
1422
  $ dat watch ./downloads -l 1GB keep an eye on large downloads
1423
1423
  $ dat watch . --json | jq -c .summary
1424
1424
  one JSON document per line (NDJSON)
1425
+ $ dat watch . -j -o report.json keep report.json up to date
1425
1426
  `;
1426
1427
  function registerWatch(program, ctx) {
1427
1428
  const command = program.command("watch").description("re-analyze a directory whenever it changes").argument("[directory]", "directory to watch", ".");
@@ -1441,18 +1442,23 @@ function registerWatch(program, ctx) {
1441
1442
  const pollSeconds = read.number(cli["poll"]);
1442
1443
  const clear = cli["clear"] !== false && display.format === "pretty" && ctx.io.stdout.isTTY === true;
1443
1444
  const signal = ctx.io.signal;
1445
+ await assertDirectory(target);
1444
1446
  let previous = null;
1447
+ let previousKey = "";
1445
1448
  let running = false;
1446
1449
  let pending = false;
1447
1450
  let timer = null;
1448
1451
  let changes = 0;
1449
- let polling = false;
1452
+ let polling = pollSeconds !== void 0;
1453
+ let rootGone = false;
1454
+ let rootCheck = null;
1450
1455
  const excluder = new Excluder({
1451
1456
  patterns: options.exclude ?? [],
1452
1457
  defaultExcludes: options.defaultExcludes ?? true
1453
1458
  });
1459
+ let ownFiles = /* @__PURE__ */ new Set();
1454
1460
  const render = async (result) => {
1455
- if (display.format === "json") {
1461
+ if (display.format === "json" && !display.output) {
1456
1462
  await ctx.stdout(`${stringifyJson(result)}\n`);
1457
1463
  return;
1458
1464
  }
@@ -1462,6 +1468,7 @@ function registerWatch(program, ctx) {
1462
1468
  html: void 0,
1463
1469
  csv: void 0
1464
1470
  }, listLimit(options.top));
1471
+ if (display.format === "json") return;
1465
1472
  const status = previous ? describeChange(previous, result, display.units) : "initial scan";
1466
1473
  ctx.info(ctx.err.dim(`watching ${escapeControl(target)} · ${status} · ${(/* @__PURE__ */ new Date()).toLocaleTimeString()} · Ctrl+C to stop`), display.quiet);
1467
1474
  };
@@ -1469,7 +1476,83 @@ function registerWatch(program, ctx) {
1469
1476
  const stopped = new Promise((resolve) => stopWatching = resolve);
1470
1477
  const readerGone = () => ctx.stdoutClosed;
1471
1478
  let watcher = null;
1472
- const run = async () => {
1479
+ let poller = null;
1480
+ const closeWatcher = () => {
1481
+ watcher?.close();
1482
+ watcher = null;
1483
+ };
1484
+ const schedule = () => {
1485
+ changes++;
1486
+ if (timer) clearTimeout(timer);
1487
+ timer = setTimeout(() => void run(), debounce);
1488
+ };
1489
+ const startPolling = (seconds) => {
1490
+ polling = true;
1491
+ if (rootCheck) clearInterval(rootCheck);
1492
+ rootCheck = null;
1493
+ poller = setInterval(() => void run(), seconds * 1e3);
1494
+ };
1495
+ const markRootGone = () => {
1496
+ if (rootGone) return;
1497
+ rootGone = true;
1498
+ ctx.warn(`${escapeControl(target)} was removed; waiting for it to come back (Ctrl+C to stop)`);
1499
+ closeWatcher();
1500
+ };
1501
+ const checkRoot = async () => {
1502
+ if (running) return;
1503
+ if (rootGone || !await isDirectory(target)) await run();
1504
+ };
1505
+ const watchFailed = async (failed, error) => {
1506
+ failed.close();
1507
+ if (watcher === failed) watcher = null;
1508
+ if (!await isDirectory(target)) {
1509
+ schedule();
1510
+ return;
1511
+ }
1512
+ ctx.warn(`file watching failed (${escapeControl(error.message)}); falling back to polling every 5 seconds`);
1513
+ if (!poller) startPolling(5);
1514
+ };
1515
+ const syncWatcher = async () => {
1516
+ if (polling || signal?.aborted) return;
1517
+ if (!watcher) {
1518
+ if (display.output) ownFiles = await ownFileEvents(target, ctx.resolvePath(display.output));
1519
+ const created = new TreeWatcher({
1520
+ root: target,
1521
+ isIgnored: (rel) => ownFiles.has(rel) || excluder.isPathExcluded(rel),
1522
+ onChange: schedule,
1523
+ onError: (error) => void watchFailed(created, error)
1524
+ });
1525
+ watcher = created;
1526
+ if (created.recursive) {
1527
+ created.sync([]);
1528
+ return;
1529
+ }
1530
+ }
1531
+ if (watcher && !watcher.recursive) watcher.sync(await listDirectories(target, options));
1532
+ };
1533
+ const scan = async () => {
1534
+ if (!await isDirectory(target)) {
1535
+ markRootGone();
1536
+ return null;
1537
+ }
1538
+ if (rootGone) {
1539
+ rootGone = false;
1540
+ changes++;
1541
+ }
1542
+ try {
1543
+ return await runAnalysis(ctx, target, options, {
1544
+ ...display,
1545
+ progress: display.progress && previous === null
1546
+ });
1547
+ } catch (error) {
1548
+ if (!(error instanceof AbortError) && !await isDirectory(target)) {
1549
+ markRootGone();
1550
+ return null;
1551
+ }
1552
+ throw error;
1553
+ }
1554
+ };
1555
+ const run = async (initial = false) => {
1473
1556
  if (running) {
1474
1557
  pending = true;
1475
1558
  return;
@@ -1478,11 +1561,10 @@ function registerWatch(program, ctx) {
1478
1561
  try {
1479
1562
  for (;;) {
1480
1563
  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)) {
1564
+ const result = await scan();
1565
+ if (!result) break;
1566
+ const key = reportKey(result);
1567
+ if (!polling || !previous || changes > 0 || key !== previousKey) {
1486
1568
  await render(result);
1487
1569
  if (readerGone()) {
1488
1570
  stopWatching();
@@ -1490,57 +1572,76 @@ function registerWatch(program, ctx) {
1490
1572
  }
1491
1573
  }
1492
1574
  previous = result;
1575
+ previousKey = key;
1493
1576
  changes = 0;
1494
- if (watcher && !watcher.recursive) watcher.sync(await listDirectories(target, options));
1577
+ try {
1578
+ await syncWatcher();
1579
+ } catch (error) {
1580
+ if (await isDirectory(target)) throw error;
1581
+ markRootGone();
1582
+ break;
1583
+ }
1495
1584
  if (!pending || signal?.aborted) break;
1496
1585
  }
1497
1586
  } catch (error) {
1498
1587
  if (error instanceof AbortError) return;
1588
+ if (initial) throw error;
1499
1589
  ctx.io.stderr.write(`${ctx.err.red("error")} ${escapeControlInLines(errorMessage(error))}\n`);
1500
1590
  } finally {
1501
1591
  running = false;
1502
1592
  }
1503
1593
  };
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));
1594
+ await run(true);
1595
+ if (!signal?.aborted && !readerGone()) {
1596
+ if (pollSeconds) startPolling(pollSeconds);
1597
+ else rootCheck = setInterval(() => void checkRoot(), 1e3);
1598
+ await Promise.race([stopped, new Promise((resolve) => {
1599
+ if (!signal) return;
1600
+ if (signal.aborted) resolve();
1601
+ signal.addEventListener("abort", () => resolve(), { once: true });
1602
+ })]);
1530
1603
  }
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
1604
  if (timer) clearTimeout(timer);
1537
1605
  if (poller) clearInterval(poller);
1538
- watcher?.close();
1606
+ if (rootCheck) clearInterval(rootCheck);
1607
+ closeWatcher();
1608
+ if (signal?.aborted) throw new AbortError();
1609
+ });
1610
+ }
1611
+ /** The result without the fields that change on every scan even when nothing on disk did. */
1612
+ function reportKey(result) {
1613
+ const { startedAt: _startedAt, durationMs: _durationMs, settings, staleFiles, ...rest } = result;
1614
+ return stringifyJson({
1615
+ ...rest,
1616
+ settings: {
1617
+ ...settings,
1618
+ modifiedAfter: null,
1619
+ modifiedBefore: null
1620
+ },
1621
+ staleFiles: staleFiles && {
1622
+ ...staleFiles,
1623
+ modifiedBefore: ""
1624
+ }
1539
1625
  });
1540
1626
  }
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("|")}`;
1627
+ async function isDirectory(path) {
1628
+ return stat(path).then((stats) => stats.isDirectory(), () => false);
1629
+ }
1630
+ /**
1631
+ * The root-relative `/` paths under which the watcher may report `file`: as given, and through
1632
+ * real paths, since FSEvents can report `/private/var` for a root under `/var`.
1633
+ */
1634
+ async function ownFileEvents(root, file) {
1635
+ const paths = /* @__PURE__ */ new Set();
1636
+ const add = (base, path) => {
1637
+ const rel = relative(base, path);
1638
+ if (rel && !rel.startsWith("..") && !isAbsolute(rel)) paths.add(rel.split(sep).join("/"));
1639
+ };
1640
+ add(root, file);
1641
+ const realRoot = await realpath(root).catch(() => root);
1642
+ const realDir = await realpath(dirname(file)).catch(() => dirname(file));
1643
+ add(realRoot, join(realDir, basename(file)));
1644
+ return paths;
1544
1645
  }
1545
1646
  function describeChange(previous, current, units) {
1546
1647
  const bytes = current.summary.bytes - previous.summary.bytes;
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-CwIrKaAV.js";
@@ -4969,4 +4969,4 @@ function renderSkipsExplanation(result, options = {}) {
4969
4969
  }
4970
4970
  return `${lines.join("\n")}\n`;
4971
4971
  }
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 };
4972
+ 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.2",
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"