dir-analysis-tool 3.5.7 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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-bXznpAvJ.js";
2
+ import { A as compactComparison, B as listDirectories, C as MAX_EXPLAIN_LIMIT, D as outsideRootError, E as isOutside, F as analyze, G as compareRelativePaths, I as createProgressReporter, J as relativePathOf, K as diskBytesOf, L as resolveFeatures, M as Collector, O as compare, Q as joinRelative, T as explainSkips, U as Excluder, V as resolveScan, W as Scanner, X as scanError, Y as rollUp, Z as comparePaths, a as renderComparisonCsv, at as formatBytes, c as renderAnalysis, ct as VERSION, d as escapeControlInLines, dt as AbortError, f as formatCount, ft as DatError, h as supportsColor, i as renderAnalysisCsv, it as parseBudget, j as CANDIDATE_DIGESTS, k as compactAnalysis, l as renderComparison, m as createStyle, mt as errorMessage, n as renderSkipsExplanation, nt as evaluateBudgets, o as renderAnalysisMarkdown, ot as parseSize, p as stringifyJson, pt as errorCode, q as passesFilters, r as renderAnalysisHtml, rt as formatBudgetActual, s as renderComparisonMarkdown, t as renderPathExplanation, u as escapeControl, ut as parsePointInTime, v as loadConfig, w as explainPath, z as assertDirectory } from "./shared-CR5IVm-D.js";
3
3
  import { constants, existsSync, watch } from "node:fs";
4
4
  import { access, mkdir, realpath, stat, writeFile } from "node:fs/promises";
5
5
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
@@ -746,7 +746,7 @@ function addReportOptions(command) {
746
746
  function addOutputOptions(command, formats = FORMATS) {
747
747
  return command.addOption(option("-f, --format <format>", "output format", OUTPUT_GROUP).choices(formats)).addOption(option("-j, --json", "same as --format json", OUTPUT_GROUP)).addOption(option("-o, --output <file>", "write the report to a file instead of stdout", OUTPUT_GROUP)).addOption(option("--si", "use decimal units (kB, MB) instead of binary (KiB, MiB)", OUTPUT_GROUP)).addOption(option("--color", "force colors", OUTPUT_GROUP)).addOption(option("--no-color", "disable colors (also honors NO_COLOR)", OUTPUT_GROUP)).addOption(option("--no-progress", "hide the progress line", OUTPUT_GROUP)).addOption(option("-q, --quiet", "print only the report and errors", OUTPUT_GROUP));
748
748
  }
749
- /** Bounded JSON for scripts and agents. Analyze only. */
749
+ /** Bounded JSON for scripts and agents (analyze and compare). */
750
750
  function addCompactOption(command) {
751
751
  return command.addOption(option("--compact", "print one-line JSON with every list cut to --top items (implies --json)", OUTPUT_GROUP));
752
752
  }
@@ -926,10 +926,10 @@ function registerAnalyze(program, ctx) {
926
926
  reportBudgets(ctx, result, display);
927
927
  });
928
928
  }
929
- async function runAnalysis(ctx, target, options, display) {
929
+ async function runAnalysis(ctx, target, options, display, analyzer = analyze) {
930
930
  const progress = new ProgressLine(ctx.io.stderr, display.progress && ctx.io.stderr.isTTY === true, ctx.err, display.units);
931
931
  try {
932
- return await analyze(target, {
932
+ return await analyzer(target, {
933
933
  ...options,
934
934
  signal: ctx.io.signal,
935
935
  ...progress.enabled ? { onProgress: (p) => progress.analysis(p) } : {}
@@ -1000,17 +1000,19 @@ Examples:
1000
1000
  $ dat compare ./a ./b --content also detect same-size content changes
1001
1001
  $ dat compare old new -f markdown a table for a pull request comment
1002
1002
  $ dat compare old new --json | jq .delta
1003
+ $ dat compare old new --compact bounded one-line JSON for scripts and agents
1003
1004
  `;
1004
1005
  function registerCompare(program, ctx) {
1005
1006
  const command = program.command("compare").description("compare two directories: added, removed, and changed files, and size changes").argument("<left>", "the baseline directory").argument("<right>", "the directory to compare against the baseline");
1006
1007
  addScanOptions(command);
1007
- command.addOption(new Option("--content", "compare same-size files by content, byte by byte").helpGroup("Report options:")).addOption(new Option("-n, --top <n>", "items per list (default: 10; 0 lists none); JSON and CSV list every file").argParser(integer(0)).helpGroup("Report options:"));
1008
+ command.addOption(new Option("--content", "compare same-size files by content, byte by byte").helpGroup("Report options:")).addOption(new Option("-n, --top <n>", "items per list (default: 10; 0 lists none); JSON and CSV list every file, --compact cuts them to this many (10 with 0)").argParser(integer(0)).helpGroup("Report options:"));
1008
1009
  addOutputOptions(command, [
1009
1010
  "pretty",
1010
1011
  "json",
1011
1012
  "markdown",
1012
1013
  "csv"
1013
1014
  ]);
1015
+ addCompactOption(command);
1014
1016
  command.addHelpText("after", EXAMPLES$2);
1015
1017
  command.action(async (left, right, _options, cmd) => {
1016
1018
  const cli = explicitOptions(cmd);
@@ -1031,7 +1033,7 @@ function registerCompare(program, ctx) {
1031
1033
  } finally {
1032
1034
  progress.clear();
1033
1035
  }
1034
- const text = renderComparisonAs(display.format, result, {
1036
+ const text = display.compact ? stringifyJson(compactComparison(result, { limit: listLimit(top) })) : renderComparisonAs(display.format, result, {
1035
1037
  style: ctx.outputStyle(display.color, display.output !== void 0),
1036
1038
  units: display.units,
1037
1039
  width: terminalWidth(ctx.io),
@@ -1366,6 +1368,417 @@ function validateWith(value, parse) {
1366
1368
  async function isFile(path) {
1367
1369
  return stat(path).then((stats) => !stats.isDirectory(), () => false);
1368
1370
  }
1371
+ const MIN_DIRTY_FOLDERS = 32;
1372
+ /**
1373
+ * An analysis kept up to date folder by folder, for `dat watch`.
1374
+ *
1375
+ * Each folder keeps what its own entries contribute: totals, file types and
1376
+ * extensions, its own top files and the entries of opt-in reports, through a
1377
+ * {@link Collector} of its own. A change re-reads only the folders it touched
1378
+ * (and scans new subfolders), then every report is built by merging the
1379
+ * folders' collectors with the same code `analyze` uses, so it is what a full
1380
+ * scan would report. Memory grows with the folders, not the files, except for
1381
+ * duplicate candidates, which `-d` keeps per file as it always does.
1382
+ *
1383
+ * Options it cannot follow incrementally make {@link LiveAnalysis.create}
1384
+ * return null: following symlinks (folders are then identified across the
1385
+ * tree) and relative dates, whose cutoffs move between reports.
1386
+ */
1387
+ var LiveAnalysis = class LiveAnalysis {
1388
+ #options;
1389
+ #scan;
1390
+ #features;
1391
+ #folders = /* @__PURE__ */ new Map();
1392
+ #stamps;
1393
+ constructor(options, scan, features) {
1394
+ this.#options = options;
1395
+ this.#scan = scan;
1396
+ this.#features = features;
1397
+ this.#stamps = features.duplicates;
1398
+ }
1399
+ /** Scans `path` in full, or returns null when the options rule out incremental updates. */
1400
+ static async create(path, options = {}) {
1401
+ if (options.followSymlinks) return null;
1402
+ const now = Date.now();
1403
+ const scan = await resolveScan(path, options, now);
1404
+ const features = resolveFeatures(options, now);
1405
+ const later = now + 3456e7;
1406
+ const moved = await resolveScan(path, options, later);
1407
+ if (moved.settings.modifiedAfter !== scan.settings.modifiedAfter || moved.settings.modifiedBefore !== scan.settings.modifiedBefore || resolveFeatures(options, later).staleBefore !== features.staleBefore) return null;
1408
+ const { onProgress, ...kept } = options;
1409
+ const live = new LiveAnalysis(kept, scan, features);
1410
+ return {
1411
+ live,
1412
+ update: await live.rescan(onProgress)
1413
+ };
1414
+ }
1415
+ /** Root-relative paths of every folder the analysis entered, the root as `''`. */
1416
+ get directories() {
1417
+ return [...this.#folders.keys()];
1418
+ }
1419
+ /** Scans everything again, reporting progress like `analyze` when asked to. */
1420
+ async rescan(onProgress) {
1421
+ const started = performance.now();
1422
+ const startedAt = Date.now();
1423
+ this.#folders.clear();
1424
+ let scanned = null;
1425
+ const progress = createProgressReporter(onProgress, this.#options.progressInterval, () => ({
1426
+ phase: "scan",
1427
+ files: scanned?.counters.files ?? 0,
1428
+ directories: scanned?.counters.directories ?? 0,
1429
+ bytes: scanned?.counters.bytes ?? 0,
1430
+ errors: scanned?.counters.errors ?? 0
1431
+ }));
1432
+ try {
1433
+ await this.#scanTree("", null, null, 0, (scanner) => scanned = scanner);
1434
+ progress.flush();
1435
+ } finally {
1436
+ progress.stop();
1437
+ }
1438
+ return {
1439
+ result: await this.#build(startedAt, started),
1440
+ mode: "full",
1441
+ folders: this.#folders.size
1442
+ };
1443
+ }
1444
+ /**
1445
+ * Updates the analysis after changes at `paths` (root-relative, `/`
1446
+ * separators, as a watcher reports them: the entry that changed, or a
1447
+ * folder whose contents did). Falls back to a full scan when that is
1448
+ * cheaper or when a change can affect folders it does not name.
1449
+ */
1450
+ async update(paths) {
1451
+ const started = performance.now();
1452
+ const startedAt = Date.now();
1453
+ const changed = [...new Set(paths)];
1454
+ if (changed.length > 1e3 || !this.#folders.has("")) return this.rescan();
1455
+ if (this.#scan.options.excluder.gitignore && changed.some(isIgnoreFile)) return this.rescan();
1456
+ const named = new Set(changed);
1457
+ const dirty = /* @__PURE__ */ new Set();
1458
+ for (const path of changed) {
1459
+ const folder = this.#folders.get(path);
1460
+ if (folder) dirty.add(folder);
1461
+ let parent = parentOf(path);
1462
+ while (parent !== null && !this.#folders.has(parent)) parent = parentOf(parent);
1463
+ if (parent !== null) dirty.add(this.#folders.get(parent));
1464
+ }
1465
+ if (dirty.size > Math.max(MIN_DIRTY_FOLDERS, this.#folders.size * .1)) return this.rescan();
1466
+ const queue = [...dirty].sort((a, b) => a.depth - b.depth);
1467
+ let folders = 0;
1468
+ while (queue.length > 0) {
1469
+ const folder = queue.shift();
1470
+ if (this.#folders.get(folder.rel) !== folder) continue;
1471
+ folders += await this.#relist(folder, queue, named);
1472
+ }
1473
+ return {
1474
+ result: await this.#build(startedAt, started),
1475
+ mode: "incremental",
1476
+ folders
1477
+ };
1478
+ }
1479
+ /** Re-reads one folder's own entries; removes vanished subfolders and scans new ones. */
1480
+ async #relist(folder, queue, named) {
1481
+ const subfolders = /* @__PURE__ */ new Map();
1482
+ const fresh = await this.#scanFolder(folder, subfolders);
1483
+ if (this.#stamps) keepDigests(folder, fresh, named);
1484
+ if (fresh.node.entries === -1 && folder.parent && isGone(fresh.errors ?? [])) {
1485
+ if (!queue.includes(folder.parent)) queue.unshift(folder.parent);
1486
+ return 1;
1487
+ }
1488
+ Object.assign(folder, {
1489
+ ...fresh,
1490
+ children: folder.children
1491
+ });
1492
+ let read = 1;
1493
+ for (const [name, child] of folder.children ?? []) if (!subfolders.has(name)) this.#remove(child);
1494
+ for (const [name, chain] of subfolders) {
1495
+ if (folder.children?.has(name)) continue;
1496
+ const rel = folder.rel ? `${folder.rel}/${name}` : name;
1497
+ read += await this.#scanTree(rel, folder, chain, folder.depth + 1);
1498
+ }
1499
+ return read;
1500
+ }
1501
+ #remove(folder) {
1502
+ for (const child of folder.children?.values() ?? []) this.#remove(child);
1503
+ this.#folders.delete(folder.rel);
1504
+ const siblings = folder.parent?.children;
1505
+ siblings?.delete(basename(folder.rel));
1506
+ if (siblings?.size === 0) folder.parent.children = null;
1507
+ }
1508
+ /** Scans a folder and everything below it, adding a record for each folder. */
1509
+ async #scanTree(rel, parent, chain, depth, onScanner) {
1510
+ const local = [];
1511
+ const scanner = this.#scanner(rel, chain === null ? void 0 : {
1512
+ rel,
1513
+ chain,
1514
+ depth,
1515
+ shallow: false
1516
+ }, {
1517
+ directory: (index, node, inherited) => {
1518
+ const up = node.parent >= 0 ? local[node.parent] : parent;
1519
+ const folderRel = up && index > 0 ? join$1(up.rel, node.name) : rel;
1520
+ const folder = this.#newFolder(folderRel, up, node, inherited);
1521
+ local[index] = folder;
1522
+ this.#folders.set(folderRel, folder);
1523
+ if (up) (up.children ??= /* @__PURE__ */ new Map()).set(basename(folderRel), folder);
1524
+ },
1525
+ folderOf: (index) => local[index]
1526
+ });
1527
+ onScanner?.(scanner);
1528
+ await scanner.run();
1529
+ return local.length;
1530
+ }
1531
+ /** Reads only `folder`'s own entries, into a fresh record; subfolders go to `subfolders`. */
1532
+ async #scanFolder(folder, subfolders) {
1533
+ let fresh = null;
1534
+ await this.#scanner(folder.rel, {
1535
+ rel: folder.rel,
1536
+ chain: folder.chain,
1537
+ depth: folder.depth,
1538
+ shallow: true
1539
+ }, {
1540
+ directory: (_index, node, inherited) => {
1541
+ fresh = this.#newFolder(folder.rel, folder.parent, node, inherited);
1542
+ },
1543
+ folderOf: () => fresh,
1544
+ subfolder: (name, chain) => subfolders.set(name, chain)
1545
+ }).run();
1546
+ return fresh;
1547
+ }
1548
+ #scanner(rel, start, route) {
1549
+ const base = this.#scan.options;
1550
+ return new Scanner({
1551
+ ...base,
1552
+ root: joinRelative(base.root, rel),
1553
+ start,
1554
+ signal: this.#options.signal,
1555
+ onSkip: (event) => {
1556
+ const folder = route.folderOf(event.dir);
1557
+ if (event.kind === "excluded") folder.excluded++;
1558
+ else if (event.kind === "filtered") folder.filtered++;
1559
+ else if (event.kind === "symlink") folder.symlinks++;
1560
+ },
1561
+ onLinkedFile: (dir, name, stats, key) => {
1562
+ (route.folderOf(dir).links ??= []).push({
1563
+ name,
1564
+ stats,
1565
+ key
1566
+ });
1567
+ },
1568
+ onError: (dir, detail) => {
1569
+ const folder = route.folderOf(dir);
1570
+ const path = join$1(rel, detail.path === "." ? "" : detail.path) || ".";
1571
+ addError(folder, {
1572
+ ...detail,
1573
+ path
1574
+ });
1575
+ }
1576
+ }, {
1577
+ directory: route.directory,
1578
+ file: (dir, name, stats) => route.folderOf(dir).collector.file(0, name, stats),
1579
+ ...route.subfolder ? { subfolder: (_parent, name, chain) => route.subfolder(name, chain) } : {}
1580
+ });
1581
+ }
1582
+ #newFolder(rel, parent, node, chain) {
1583
+ const collector = new Collector(this.#features, this.#stamps);
1584
+ collector.attach(new FolderView(node));
1585
+ return {
1586
+ rel,
1587
+ parent,
1588
+ depth: node.depth,
1589
+ chain,
1590
+ node,
1591
+ collector,
1592
+ excluded: 0,
1593
+ filtered: 0,
1594
+ symlinks: 0,
1595
+ errorCount: 0,
1596
+ errors: null,
1597
+ links: null,
1598
+ children: null
1599
+ };
1600
+ }
1601
+ /** Merges every folder into one report, the way `analyze` builds it from one scan. */
1602
+ async #build(startedAt, started) {
1603
+ const features = this.#features;
1604
+ const tree = new MergedTree(this.#scan.options.root);
1605
+ const collector = new Collector(features, this.#stamps);
1606
+ collector.attach(tree);
1607
+ const index = /* @__PURE__ */ new Map();
1608
+ const errors = [];
1609
+ const visit = (folder, parent) => {
1610
+ const node = folder.node;
1611
+ const i = tree.dirs.push({
1612
+ name: folder.parent ? basename(folder.rel) : "",
1613
+ parent,
1614
+ depth: folder.depth,
1615
+ entries: node.entries,
1616
+ ownFiles: node.ownFiles,
1617
+ ownBytes: node.ownBytes,
1618
+ ownDiskBytes: node.ownDiskBytes,
1619
+ files: 0,
1620
+ bytes: 0,
1621
+ diskBytes: 0,
1622
+ largestChild: 0
1623
+ }) - 1;
1624
+ index.set(folder, i);
1625
+ const c = tree.counters;
1626
+ c.directories++;
1627
+ c.files += node.ownFiles;
1628
+ c.bytes += node.ownBytes;
1629
+ c.diskBytes += node.ownDiskBytes;
1630
+ c.excluded += folder.excluded;
1631
+ c.filtered += folder.filtered;
1632
+ c.symlinks += folder.symlinks;
1633
+ c.errors += folder.errorCount;
1634
+ if (folder.errors) errors.push(...folder.errors);
1635
+ collector.directory(i, tree.dirs[i]);
1636
+ collector.absorb(folder.collector, i);
1637
+ for (const child of folder.children?.values() ?? []) visit(child, i);
1638
+ };
1639
+ visit(this.#folders.get(""), -1);
1640
+ this.#countLinks(tree, collector, index);
1641
+ errors.sort((a, b) => comparePaths(a.path, b.path));
1642
+ tree.errors.push(...errors.slice(0, 100));
1643
+ rollUp(tree.dirs);
1644
+ let duplicates;
1645
+ if (features.duplicates) duplicates = await collector.findDuplicates(tree, this.#scan.options.concurrency, this.#options.signal, () => {}, CANDIDATE_DIGESTS);
1646
+ const result = collector.build(tree, {
1647
+ root: this.#scan.options.root,
1648
+ startedAt,
1649
+ settings: this.#scan.settings,
1650
+ duplicates
1651
+ });
1652
+ if (features.budgets.length > 0) result.budgets = evaluateBudgets(features.budgets, result);
1653
+ result.durationMs = Math.round(performance.now() - started);
1654
+ return result;
1655
+ }
1656
+ /**
1657
+ * Counts each set of hard links once, under the link whose path sorts
1658
+ * first, so the choice never depends on which link a scan reached first.
1659
+ */
1660
+ #countLinks(tree, collector, index) {
1661
+ const byKey = /* @__PURE__ */ new Map();
1662
+ for (const folder of this.#folders.values()) for (const file of folder.links ?? []) {
1663
+ const links = byKey.get(file.key);
1664
+ if (links) links.push({
1665
+ folder,
1666
+ file
1667
+ });
1668
+ else byKey.set(file.key, [{
1669
+ folder,
1670
+ file
1671
+ }]);
1672
+ }
1673
+ const options = this.#scan.options;
1674
+ for (const links of byKey.values()) {
1675
+ tree.counters.hardlinks += links.length - 1;
1676
+ const { folder, file } = links.reduce((a, b) => comparePaths(join$1(a.folder.rel, a.file.name), join$1(b.folder.rel, b.file.name)) <= 0 ? a : b);
1677
+ if (!passesFilters(options, file.stats)) {
1678
+ tree.counters.filtered++;
1679
+ continue;
1680
+ }
1681
+ const dir = index.get(folder);
1682
+ const node = tree.dirs[dir];
1683
+ const diskBytes = diskBytesOf(file.stats);
1684
+ node.ownFiles++;
1685
+ node.ownBytes += file.stats.size;
1686
+ node.ownDiskBytes += diskBytes;
1687
+ tree.counters.files++;
1688
+ tree.counters.bytes += file.stats.size;
1689
+ tree.counters.diskBytes += diskBytes;
1690
+ collector.file(dir, file.name, file.stats);
1691
+ }
1692
+ }
1693
+ };
1694
+ /** The merged folders of a live analysis, as one scan's tree for {@link Collector.build}. */
1695
+ var MergedTree = class {
1696
+ dirs = [];
1697
+ errors = [];
1698
+ counters = emptyCounters();
1699
+ #root;
1700
+ constructor(root) {
1701
+ this.#root = root;
1702
+ }
1703
+ relativePath(dir, name) {
1704
+ return relativePathOf(this.dirs, dir, name);
1705
+ }
1706
+ absolutePath(dir, name) {
1707
+ return joinRelative(this.#root, this.relativePath(dir, name));
1708
+ }
1709
+ compareRelative(dirA, nameA, dirB, nameB) {
1710
+ return compareRelativePaths(this.dirs, dirA, nameA, dirB, nameB);
1711
+ }
1712
+ recordError(path, error) {
1713
+ this.counters.errors++;
1714
+ if (this.errors.length < 100) this.errors.push(scanError(path, error));
1715
+ }
1716
+ };
1717
+ /** One folder seen as a whole tree, for that folder's own collector. */
1718
+ var FolderView = class {
1719
+ dirs;
1720
+ constructor(node) {
1721
+ this.dirs = [node];
1722
+ }
1723
+ /** Within one folder, paths differ only by name. */
1724
+ compareRelative(_dirA, nameA, _dirB, nameB) {
1725
+ return comparePaths(nameA ?? "", nameB ?? "");
1726
+ }
1727
+ };
1728
+ /**
1729
+ * Moves digests from a folder's old candidates to the new ones for files that
1730
+ * kept their size, timestamps and identity and that no event named, so only
1731
+ * files that changed are read again.
1732
+ */
1733
+ function keepDigests(old, fresh, named) {
1734
+ const before = /* @__PURE__ */ new Map();
1735
+ for (const candidate of old.collector.candidates()) if (candidate.digests) before.set(candidate.name, candidate);
1736
+ if (before.size === 0) return;
1737
+ for (const candidate of fresh.collector.candidates()) {
1738
+ const previous = before.get(candidate.name);
1739
+ const digests = previous?.digests;
1740
+ if (previous && digests && previous.bytes === candidate.bytes && previous.mtimeMs === candidate.mtimeMs && previous.ctimeMs === candidate.ctimeMs && previous.ino === candidate.ino && previous.dev === candidate.dev && !named.has(join$1(old.rel, candidate.name))) candidate.digests = digests;
1741
+ }
1742
+ }
1743
+ function emptyCounters() {
1744
+ return {
1745
+ files: 0,
1746
+ bytes: 0,
1747
+ diskBytes: 0,
1748
+ directories: 0,
1749
+ symlinks: 0,
1750
+ hardlinks: 0,
1751
+ excluded: 0,
1752
+ filtered: 0,
1753
+ errors: 0
1754
+ };
1755
+ }
1756
+ /** Adds an error to a folder, keeping only the {@link MAX_ERROR_DETAILS} first by path. */
1757
+ function addError(folder, detail) {
1758
+ folder.errorCount++;
1759
+ const errors = folder.errors ??= [];
1760
+ errors.push(detail);
1761
+ if (errors.length > 100) {
1762
+ errors.sort((a, b) => comparePaths(a.path, b.path));
1763
+ errors.pop();
1764
+ }
1765
+ }
1766
+ function isGone(errors) {
1767
+ return errors.some((e) => e.code === "ENOENT" || e.code === "ENOTDIR");
1768
+ }
1769
+ function isIgnoreFile(path) {
1770
+ return path === ".gitignore" || path.endsWith("/.gitignore");
1771
+ }
1772
+ function join$1(dir, name) {
1773
+ if (!dir) return name;
1774
+ return name ? `${dir}/${name}` : dir;
1775
+ }
1776
+ /** The folder a root-relative path is in: `''` for the root's entries, null for the root. */
1777
+ function parentOf(path) {
1778
+ if (path === "") return null;
1779
+ const slash = path.lastIndexOf("/");
1780
+ return slash < 0 ? "" : path.slice(0, slash);
1781
+ }
1369
1782
  // src/cli/watcher.ts
1370
1783
  /**
1371
1784
  * Watches a directory tree with the platform's native facility.
@@ -1436,6 +1849,15 @@ var TreeWatcher = class {
1436
1849
  };
1437
1850
  // src/cli/commands/watch.ts
1438
1851
  const CLEAR_SCREEN = "\x1B[2J\x1B[3J\x1B[H";
1852
+ /**
1853
+ * Events can be lost without a word (a full kernel queue, a sleeping laptop), so while changes keep
1854
+ * coming, a report is a full scan again at least this often.
1855
+ */
1856
+ const FULL_SCAN_EVERY_MS = 6e5;
1857
+ /** Whether the next report must come from a full scan instead of the changed folders. */
1858
+ function needsFullScan(lastFullScan, now) {
1859
+ return now - lastFullScan >= FULL_SCAN_EVERY_MS;
1860
+ }
1439
1861
  const EXAMPLES = `
1440
1862
  Examples:
1441
1863
  $ dat watch re-analyze the current directory on every change
@@ -1477,6 +1899,10 @@ function registerWatch(program, ctx) {
1477
1899
  let polling = pollSeconds !== void 0;
1478
1900
  let rootGone = false;
1479
1901
  let rootCheck = null;
1902
+ let incremental = pollSeconds === void 0;
1903
+ let live = null;
1904
+ let lastFullScan = 0;
1905
+ const changed = /* @__PURE__ */ new Set();
1480
1906
  const excluder = new Excluder({
1481
1907
  patterns: options.exclude ?? [],
1482
1908
  defaultExcludes: options.defaultExcludes ?? true
@@ -1509,13 +1935,25 @@ function registerWatch(program, ctx) {
1509
1935
  watcher?.close();
1510
1936
  watcher = null;
1511
1937
  };
1512
- const schedule = () => {
1938
+ const schedule = (path) => {
1513
1939
  changes++;
1940
+ if (path !== void 0) changed.add(path);
1514
1941
  if (timer) clearTimeout(timer);
1515
1942
  timer = setTimeout(() => void run(), debounce);
1516
1943
  };
1944
+ const startLive = async (path, settings) => {
1945
+ const created = await LiveAnalysis.create(path, settings);
1946
+ if (!created) {
1947
+ incremental = false;
1948
+ return analyze(path, settings);
1949
+ }
1950
+ live = created.live;
1951
+ return created.update.result;
1952
+ };
1517
1953
  const startPolling = (seconds) => {
1518
1954
  polling = true;
1955
+ incremental = false;
1956
+ live = null;
1519
1957
  if (rootCheck) clearInterval(rootCheck);
1520
1958
  rootCheck = null;
1521
1959
  const tick = async () => {
@@ -1551,7 +1989,7 @@ function registerWatch(program, ctx) {
1551
1989
  const created = new TreeWatcher({
1552
1990
  root: target,
1553
1991
  isIgnored: (rel) => ownFiles.has(rel) || excluder.isPathExcluded(rel),
1554
- onChange: schedule,
1992
+ onChange: (path) => schedule(path),
1555
1993
  onError: (error) => void watchFailed(created, error)
1556
1994
  });
1557
1995
  watcher = created;
@@ -1560,7 +1998,7 @@ function registerWatch(program, ctx) {
1560
1998
  return;
1561
1999
  }
1562
2000
  }
1563
- if (watcher && !watcher.recursive) watcher.sync(await listDirectories(target, options));
2001
+ if (watcher && !watcher.recursive) watcher.sync(live ? live.directories : await listDirectories(target, options));
1564
2002
  };
1565
2003
  const scan = async () => {
1566
2004
  if (!await isDirectory(target)) {
@@ -1570,12 +2008,22 @@ function registerWatch(program, ctx) {
1570
2008
  if (rootGone) {
1571
2009
  rootGone = false;
1572
2010
  changes++;
2011
+ live = null;
1573
2012
  }
2013
+ const paths = [...changed];
2014
+ changed.clear();
1574
2015
  try {
2016
+ if (incremental && live && !needsFullScan(lastFullScan, Date.now())) {
2017
+ const update = await live.update(paths);
2018
+ if (update.mode === "full") lastFullScan = Date.now();
2019
+ return update.result;
2020
+ }
2021
+ lastFullScan = Date.now();
2022
+ if (incremental && live) return (await live.rescan()).result;
1575
2023
  return await runAnalysis(ctx, target, options, {
1576
2024
  ...display,
1577
2025
  progress: display.progress && previous === null
1578
- });
2026
+ }, incremental ? startLive : void 0);
1579
2027
  } catch (error) {
1580
2028
  if (!(error instanceof AbortError) && !await isDirectory(target)) {
1581
2029
  markRootGone();
package/dist/index.d.ts CHANGED
@@ -179,7 +179,13 @@ export interface AnalysisResult {
179
179
  }
180
180
  /** Lists that compact output can cut, named by their JSON path. */
181
181
  export type CompactList = "extensions" | "errors" | "largeFiles.items" | "duplicates.items" | "duplicates.items[].files" | "emptyFiles.items" | "emptyDirectories.items" | "staleFiles.items";
182
- export interface CompactInfo {
182
+ /** Lists that compact comparison output can cut, named by their JSON path. */
183
+ export type ComparisonCompactList = "added.items" | "removed.items" | "changed.items";
184
+ /**
185
+ * What compact output cut. `List` names the lists that can be cut:
186
+ * {@link CompactList} for an analysis, {@link ComparisonCompactList} for a comparison.
187
+ */
188
+ export interface CompactInfo<List extends string = CompactList> {
183
189
  /** Maximum number of items kept in each list. */
184
190
  limit: number;
185
191
  /** Whether any list was cut. */
@@ -188,7 +194,7 @@ export interface CompactInfo {
188
194
  * Items not listed, per cut list, in document order. A list that is absent
189
195
  * here was not cut. `duplicates.items[].files` is the sum over listed groups.
190
196
  */
191
- omitted: Partial<Record<CompactList, number>>;
197
+ omitted: Partial<Record<List, number>>;
192
198
  }
193
199
  export interface ChangedFile {
194
200
  path: string;
@@ -222,7 +228,7 @@ export interface ComparisonResult {
222
228
  files: number;
223
229
  directories: number;
224
230
  };
225
- /** Every added file, whatever `top` is; the CLI cuts only pretty and Markdown output. */
231
+ /** Every added file, whatever `top` is; the CLI cuts pretty, Markdown and compact output. */
226
232
  added: ItemList<FileEntry>;
227
233
  /** Every removed file, whatever `top` is. */
228
234
  removed: ItemList<FileEntry>;
@@ -235,7 +241,27 @@ export interface ComparisonResult {
235
241
  unchanged: number;
236
242
  /** At most `top` directories with the largest size change, largest absolute change first. */
237
243
  directories: DirectoryDelta[];
244
+ /** Present only in compact output (`compare --compact`, `compactComparison`): what was cut. */
245
+ compact?: CompactInfo<ComparisonCompactList>;
238
246
  }
247
+ /** A feature a metric depends on; requesting the metric turns the feature on. */
248
+ type BudgetFeature = "largeFiles" | "duplicates" | "empty" | "stale";
249
+ interface MetricSpec {
250
+ kind: "size" | "count";
251
+ description: string;
252
+ requires?: BudgetFeature;
253
+ read: (result: AnalysisResult) => number;
254
+ }
255
+ export declare const BUDGET_METRICS: Readonly<Record<BudgetMetric, MetricSpec>>;
256
+ interface Budget {
257
+ rule: string;
258
+ metric: BudgetMetric;
259
+ operator: BudgetOperator;
260
+ limit: number;
261
+ }
262
+ /** Parses a rule such as `size<=500MB`, `duplicates=0`, or `files < 10000`. */
263
+ export declare function parseBudget(rule: string): Budget;
264
+ export declare function evaluateBudgets(budgets: readonly Budget[], result: AnalysisResult): BudgetResult[];
239
265
  interface DuplicateProgress {
240
266
  stage: "sample" | "full";
241
267
  done: number;
@@ -353,6 +379,16 @@ interface CompactOptions {
353
379
  * already bounded by `top` or by the tree's own per-folder limit.
354
380
  */
355
381
  export declare function compactAnalysis(result: AnalysisResult, options: CompactOptions): AnalysisResult;
382
+ /**
383
+ * Bounds the file lists of a comparison to `limit` items, as
384
+ * {@link compactAnalysis} does for an analysis. Counts, sizes and deltas stay
385
+ * the full totals; what was cut is listed in `compact.omitted`. Returns a new
386
+ * result and leaves the input untouched.
387
+ *
388
+ * Cut: the `items` of `added`, `removed`, and `changed`. Not cut: the sides'
389
+ * summaries and types, `delta`, and `directories`, which `top` already bounds.
390
+ */
391
+ export declare function compactComparison(result: ComparisonResult, options: CompactOptions): ComparisonResult;
356
392
  interface CompareOptions extends ScanSettings {
357
393
  /**
358
394
  * Also compare the contents of same-sized files, byte by byte. Default: `false`, size only.
@@ -538,24 +574,6 @@ export declare function explainSkips(root: string, options?: ExplainSkipsOptions
538
574
  export declare function extensionOf(fileName: string): string;
539
575
  /** Classifies a file by its well-known name first, then by extension. */
540
576
  export declare function classify(fileName: string, extension?: string): Category;
541
- /** A feature a metric depends on; requesting the metric turns the feature on. */
542
- type BudgetFeature = "largeFiles" | "duplicates" | "empty" | "stale";
543
- interface MetricSpec {
544
- kind: "size" | "count";
545
- description: string;
546
- requires?: BudgetFeature;
547
- read: (result: AnalysisResult) => number;
548
- }
549
- export declare const BUDGET_METRICS: Readonly<Record<BudgetMetric, MetricSpec>>;
550
- interface Budget {
551
- rule: string;
552
- metric: BudgetMetric;
553
- operator: BudgetOperator;
554
- limit: number;
555
- }
556
- /** Parses a rule such as `size<=500MB`, `duplicates=0`, or `files < 10000`. */
557
- export declare function parseBudget(rule: string): Budget;
558
- export declare function evaluateBudgets(budgets: readonly Budget[], result: AnalysisResult): BudgetResult[];
559
577
  /** Settings accepted in a config file. CLI flags always take precedence. */
560
578
  interface DatConfig {
561
579
  exclude?: string[];
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-bXznpAvJ.js";
1
+ export { dt as AbortError, tt as BUDGET_METRICS, st as CATEGORIES, g as CONFIG_FILE_NAMES, R as DEFAULT_CONCURRENCY, H as DEFAULT_EXCLUDES, x as DEFAULT_EXPLAIN_LIMIT, N as DEFAULT_LARGE_FILE_THRESHOLD, P as DEFAULT_STALE_AGE, ft as DatError, S as EXPLAIN_VERSION, C as MAX_EXPLAIN_LIMIT, ct as VERSION, F as analyze, y as buildJsonSchema, $ as classify, k as compactAnalysis, A as compactComparison, O as compare, m as createStyle, nt as evaluateBudgets, w as explainPath, T as explainSkips, et as extensionOf, _ as findConfigFile, at as formatBytes, B as listDirectories, v as loadConfig, it as parseBudget, lt as parseDuration, ut as parsePointInTime, ot as parseSize, c as renderAnalysis, i as renderAnalysisCsv, r as renderAnalysisHtml, o as renderAnalysisMarkdown, l as renderComparison, a as renderComparisonCsv, s as renderComparisonMarkdown, t as renderPathExplanation, n as renderSkipsExplanation, b as validateConfig } from "./shared-CR5IVm-D.js";