dir-analysis-tool 3.2.1 → 3.3.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.
@@ -2,8 +2,8 @@ import { createRequire } from "node:module";
2
2
  import { createHash, hash } from "node:crypto";
3
3
  import { existsSync, readFile } from "node:fs";
4
4
  import { lstat, open, readFile as readFile$1, readdir, stat } from "node:fs/promises";
5
- import { dirname, join, relative, resolve, sep } from "node:path";
6
- //#region src/errors.ts
5
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
+ // src/errors.ts
7
7
  /**
8
8
  * An expected, user-facing failure (bad input, missing directory, invalid
9
9
  * config). The CLI prints its message without a stack trace.
@@ -32,8 +32,7 @@ function errorMessage(error) {
32
32
  function errorCode(error) {
33
33
  if (typeof error === "object" && error !== null && "code" in error && typeof error.code === "string") return error.code;
34
34
  }
35
- //#endregion
36
- //#region src/format/time.ts
35
+ // src/format/time.ts
37
36
  /**
38
37
  * Date, age, and duration helpers used by filters, reports, and the CLI.
39
38
  */
@@ -97,8 +96,7 @@ function formatAge(timestampMs, now = Date.now()) {
97
96
  for (const [label, size] of units) if (diff >= size) return `${Math.floor(diff / size)}${label}`;
98
97
  return "now";
99
98
  }
100
- //#endregion
101
- //#region src/version.ts
99
+ // src/version.ts
102
100
  /**
103
101
  * Read from the package manifest at runtime, so the reported version always
104
102
  * matches the installed package, whatever step of the release built `dist/`.
@@ -115,8 +113,7 @@ const TOOL = {
115
113
  name: "dir-analysis-tool",
116
114
  version: VERSION
117
115
  };
118
- //#endregion
119
- //#region src/types.ts
116
+ // src/types.ts
120
117
  const CATEGORIES = [
121
118
  "code",
122
119
  "documents",
@@ -128,8 +125,7 @@ const CATEGORIES = [
128
125
  "data",
129
126
  "other"
130
127
  ];
131
- //#endregion
132
- //#region src/format/bytes.ts
128
+ // src/format/bytes.ts
133
129
  const IEC_LABELS = [
134
130
  "B",
135
131
  "KiB",
@@ -229,8 +225,7 @@ function parseSize(input) {
229
225
  if (!match || multiplier === void 0) throw new RangeError(`Invalid size "${input}". Use bytes or a unit, for example 512, 10k, 25MiB, or 1GB.`);
230
226
  return Math.floor(Number(match[1]) * multiplier);
231
227
  }
232
- //#endregion
233
- //#region src/core/budgets.ts
228
+ // src/core/budgets.ts
234
229
  const BUDGET_METRICS = {
235
230
  size: {
236
231
  kind: "size",
@@ -365,8 +360,7 @@ function formatBudgetActual(budget, units) {
365
360
  if (BUDGET_METRICS[budget.metric].kind === "count") return budget.actual.toLocaleString("en-US");
366
361
  return formatBytes(budget.actual, unitsOf(budget.limit, units));
367
362
  }
368
- //#endregion
369
- //#region src/core/classify.ts
363
+ // src/core/classify.ts
370
364
  const EXTENSIONS = {
371
365
  code: [
372
366
  "js",
@@ -721,8 +715,7 @@ function emptyTypeStats() {
721
715
  }
722
716
  };
723
717
  }
724
- //#endregion
725
- //#region src/core/duplicates.ts
718
+ // src/core/duplicates.ts
726
719
  /** Files up to this size are read in one call and hashed in full straight away. */
727
720
  const SAMPLE_THRESHOLD = 262144;
728
721
  /** Bytes read from each end of a larger file for its sample hash. */
@@ -900,8 +893,7 @@ var BufferPool = class {
900
893
  this.#free.push(buffer);
901
894
  }
902
895
  };
903
- //#endregion
904
- //#region src/core/gitignore.ts
896
+ // src/core/gitignore.ts
905
897
  /**
906
898
  * The compiled rules of one ignore file.
907
899
  *
@@ -956,7 +948,7 @@ var GitignoreMatcher = class GitignoreMatcher {
956
948
  }
957
949
  /** Compiles the contents of an ignore file (or a list of patterns). */
958
950
  static compile(source, options = {}) {
959
- const lines = typeof source === "string" ? source.replace(/^\uFEFF/, "").split(EOL) : source;
951
+ const lines = typeof source === "string" ? splitRuleLines(source) : source;
960
952
  const ignoreCase = options.ignoreCase === true;
961
953
  const flags = ignoreCase ? "i" : "";
962
954
  const runs = [];
@@ -1186,6 +1178,13 @@ var LinearGlob = class {
1186
1178
  const LITERAL = /^[^*?[\\]+$/;
1187
1179
  /** A line ending; a final CR counts because Git treats the end of a file as a newline. */
1188
1180
  const EOL = /\r?\n|\r$/;
1181
+ /**
1182
+ * Splits an ignore file into lines as {@link GitignoreMatcher.compile} reads
1183
+ * them, so index + 1 is the line number Git reports.
1184
+ */
1185
+ function splitRuleLines(source) {
1186
+ return source.replace(/^\uFEFF/, "").split(EOL);
1187
+ }
1189
1188
  /** Removes unescaped trailing spaces. Tabs are significant, as they are in Git. */
1190
1189
  function trimTrailingSpaces(line) {
1191
1190
  let end = line.length;
@@ -1372,8 +1371,7 @@ function escapeRegex(c) {
1372
1371
  function escapeInClass(c) {
1373
1372
  return /[\\\]^[-]/.test(c) ? `\\${c}` : c;
1374
1373
  }
1375
- //#endregion
1376
- //#region src/core/exclude.ts
1374
+ // src/core/exclude.ts
1377
1375
  /** Directories skipped unless default excludes are turned off. */
1378
1376
  const DEFAULT_EXCLUDES = [
1379
1377
  ".git",
@@ -1393,14 +1391,25 @@ var Excluder = class {
1393
1391
  #defaults;
1394
1392
  #user;
1395
1393
  #ignoreCase;
1394
+ /** Trimmed, non-empty user patterns, as they were compiled. */
1395
+ patterns;
1396
1396
  constructor(options = {}) {
1397
1397
  this.gitignore = options.gitignore ?? false;
1398
1398
  this.#ignoreCase = options.ignoreCase ?? process.platform !== "linux";
1399
1399
  this.#defaults = options.defaultExcludes ?? true ? new Set(DEFAULT_EXCLUDES) : null;
1400
1400
  const patterns = (options.patterns ?? []).map((p) => p.trim()).filter(Boolean);
1401
+ this.patterns = patterns;
1401
1402
  const user = patterns.length > 0 ? this.#compile(patterns) : null;
1402
1403
  this.#user = user?.hasRules ? user : null;
1403
1404
  }
1405
+ /** Whether rules match case-insensitively. */
1406
+ get ignoreCase() {
1407
+ return this.#ignoreCase;
1408
+ }
1409
+ /** Whether the default directory names are excluded. */
1410
+ get defaultExcludes() {
1411
+ return this.#defaults !== null;
1412
+ }
1404
1413
  /** True when at least one rule could exclude something. */
1405
1414
  get active() {
1406
1415
  return this.#defaults !== null || this.#user !== null || this.gitignore;
@@ -1443,7 +1452,12 @@ var Excluder = class {
1443
1452
  return {
1444
1453
  matcher,
1445
1454
  prefix: "",
1446
- strip: rootRelativeDir ? rootRelativeDir.length + 1 : 0
1455
+ strip: rootRelativeDir ? rootRelativeDir.length + 1 : 0,
1456
+ source: {
1457
+ kind: "gitignore",
1458
+ file: filePath,
1459
+ content
1460
+ }
1447
1461
  };
1448
1462
  }
1449
1463
  /**
@@ -1452,7 +1466,14 @@ var Excluder = class {
1452
1466
  * `.git/info/exclude`, so a sub-directory scan matches Git's view.
1453
1467
  */
1454
1468
  async loadAncestorChain(root) {
1455
- if (!this.gitignore) return EMPTY_CHAIN;
1469
+ return (await this.loadAncestors(root)).chain;
1470
+ }
1471
+ /** {@link loadAncestorChain}, plus the repository root it found (null outside a repository). */
1472
+ async loadAncestors(root) {
1473
+ if (!this.gitignore) return {
1474
+ chain: EMPTY_CHAIN,
1475
+ repoRoot: null
1476
+ };
1456
1477
  const ancestors = [];
1457
1478
  let repoRoot = null;
1458
1479
  let current = root;
@@ -1466,10 +1487,13 @@ var Excluder = class {
1466
1487
  ancestors.push(parent);
1467
1488
  current = parent;
1468
1489
  }
1469
- if (repoRoot === null) return EMPTY_CHAIN;
1490
+ if (repoRoot === null) return {
1491
+ chain: EMPTY_CHAIN,
1492
+ repoRoot: null
1493
+ };
1470
1494
  const scopes = [];
1471
1495
  const outermostFirst = repoRoot === root ? [] : ancestors.reverse();
1472
- const add = async (file, base) => {
1496
+ const add = async (file, base, kind) => {
1473
1497
  const content = await readFile$1(file, "utf8").catch(() => null);
1474
1498
  if (content === null) return;
1475
1499
  const matcher = this.#compile(content);
@@ -1478,13 +1502,21 @@ var Excluder = class {
1478
1502
  scopes.push({
1479
1503
  matcher,
1480
1504
  prefix: prefix ? `${prefix}/` : "",
1481
- strip: 0
1505
+ strip: 0,
1506
+ source: {
1507
+ kind,
1508
+ file,
1509
+ content
1510
+ }
1482
1511
  });
1483
1512
  };
1484
1513
  const infoExclude = await findInfoExclude(repoRoot);
1485
- if (infoExclude !== null) await add(infoExclude, repoRoot);
1486
- for (const dir of outermostFirst) await add(join(dir, ".gitignore"), dir);
1487
- return scopes;
1514
+ if (infoExclude !== null) await add(infoExclude, repoRoot, "info-exclude");
1515
+ for (const dir of outermostFirst) await add(join(dir, ".gitignore"), dir, "gitignore");
1516
+ return {
1517
+ chain: scopes,
1518
+ repoRoot
1519
+ };
1488
1520
  }
1489
1521
  #compile(source) {
1490
1522
  return GitignoreMatcher.compile(source, { ignoreCase: this.#ignoreCase });
@@ -1515,8 +1547,7 @@ function isGitIgnored(chain, relPath, isDirectory) {
1515
1547
  }
1516
1548
  return ignored;
1517
1549
  }
1518
- //#endregion
1519
- //#region src/core/limiter.ts
1550
+ // src/core/limiter.ts
1520
1551
  /**
1521
1552
  * A tiny concurrency limiter for filesystem work.
1522
1553
  *
@@ -1582,8 +1613,7 @@ var Limiter = class {
1582
1613
  this.abort(error);
1583
1614
  };
1584
1615
  };
1585
- //#endregion
1586
- //#region src/core/paths.ts
1616
+ // src/core/paths.ts
1587
1617
  /** Ordinal comparison, so output order never depends on the locale. */
1588
1618
  function comparePaths(a, b) {
1589
1619
  return a < b ? -1 : a > b ? 1 : 0;
@@ -1708,6 +1738,13 @@ var Scanner = class {
1708
1738
  const rel = relDir ? `${relDir}/${name}` : name;
1709
1739
  if (excluder.isExcluded(rel, name, isDirectory, chain)) {
1710
1740
  this.counters.excluded++;
1741
+ this.#options.onSkip?.({
1742
+ kind: "excluded",
1743
+ dir: index,
1744
+ name,
1745
+ isDirectory,
1746
+ chain
1747
+ });
1711
1748
  continue;
1712
1749
  }
1713
1750
  }
@@ -1720,7 +1757,15 @@ var Scanner = class {
1720
1757
  }
1721
1758
  #enterDir(parent, name, fullPath, chain) {
1722
1759
  const depth = this.dirs[parent].depth + 1;
1723
- if (depth > this.#options.maxDepth) return;
1760
+ if (depth > this.#options.maxDepth) {
1761
+ this.#options.onSkip?.({
1762
+ kind: "depth",
1763
+ dir: parent,
1764
+ name,
1765
+ depth
1766
+ });
1767
+ return;
1768
+ }
1724
1769
  const child = this.#addDir(name, parent, depth);
1725
1770
  this.#limiter.run(() => this.#scanDir(child, fullPath, chain));
1726
1771
  }
@@ -1746,6 +1791,11 @@ var Scanner = class {
1746
1791
  isSymlink = true;
1747
1792
  if (!this.#options.followSymlinks) {
1748
1793
  this.counters.symlinks++;
1794
+ this.#options.onSkip?.({
1795
+ kind: "symlink",
1796
+ dir: dirIndex,
1797
+ name
1798
+ });
1749
1799
  return;
1750
1800
  }
1751
1801
  stats = await stat(fullPath);
@@ -1766,6 +1816,13 @@ var Scanner = class {
1766
1816
  const rel = this.relativePath(dirIndex, name);
1767
1817
  if (excluder.isExcluded(rel, name, true, chain)) {
1768
1818
  this.counters.excluded++;
1819
+ this.#options.onSkip?.({
1820
+ kind: "excluded",
1821
+ dir: dirIndex,
1822
+ name,
1823
+ isDirectory: true,
1824
+ chain
1825
+ });
1769
1826
  return;
1770
1827
  }
1771
1828
  }
@@ -1790,6 +1847,12 @@ var Scanner = class {
1790
1847
  const mtime = stats.mtimeMs;
1791
1848
  if (size < o.minSize || size > o.maxSize || mtime < o.modifiedAfter || mtime > o.modifiedBefore) {
1792
1849
  this.counters.filtered++;
1850
+ o.onSkip?.({
1851
+ kind: "filtered",
1852
+ dir: dirIndex,
1853
+ name,
1854
+ stats
1855
+ });
1793
1856
  return;
1794
1857
  }
1795
1858
  }
@@ -1853,8 +1916,7 @@ const ERROR_DESCRIPTIONS = {
1853
1916
  EIO: "input/output error",
1854
1917
  EBUSY: "resource busy"
1855
1918
  };
1856
- //#endregion
1857
- //#region src/core/options.ts
1919
+ // src/core/options.ts
1858
1920
  /** Default number of concurrent filesystem operations. */
1859
1921
  const DEFAULT_CONCURRENCY = 32;
1860
1922
  /** Validates the root and turns user-facing settings into scanner options. */
@@ -1950,8 +2012,7 @@ async function listDirectories(path, settings = {}) {
1950
2012
  await scanner.run();
1951
2013
  return scanner.dirs.map((_, index) => scanner.relativePath(index));
1952
2014
  }
1953
- //#endregion
1954
- //#region src/core/top.ts
2015
+ // src/core/top.ts
1955
2016
  /**
1956
2017
  * Keeps the `limit` largest items seen, in O(limit) memory and O(log limit)
1957
2018
  * time per insertion, using a binary min-heap keyed by `score`.
@@ -2022,8 +2083,7 @@ var TopK = class {
2022
2083
  }
2023
2084
  }
2024
2085
  };
2025
- //#endregion
2026
- //#region src/core/analyze.ts
2086
+ // src/core/analyze.ts
2027
2087
  /** Default size for "large file" detection: 100 MiB. */
2028
2088
  const DEFAULT_LARGE_FILE_THRESHOLD = 104857600;
2029
2089
  /** Default age for stale-file detection. */
@@ -2440,8 +2500,7 @@ function createProgressReporter(report, interval, snapshot) {
2440
2500
  }
2441
2501
  };
2442
2502
  }
2443
- //#endregion
2444
- //#region src/core/compare.ts
2503
+ // src/core/compare.ts
2445
2504
  const PASS_THROUGH_SHARE = .95;
2446
2505
  /** Records every file by its root-relative path, for diffing. */
2447
2506
  var FileIndex = class {
@@ -2658,8 +2717,640 @@ function directoryDeltas(leftScanner, leftIndex, rightScanner, rightIndex, top)
2658
2717
  deltas.sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta) || comparePaths(x.path, y.path));
2659
2718
  return deltas.slice(0, top);
2660
2719
  }
2661
- //#endregion
2662
- //#region src/config/schema.ts
2720
+ // src/core/explain.ts
2721
+ /** Version of the `explain` JSON shape, independent of the analysis `schemaVersion`. */
2722
+ const EXPLAIN_VERSION = 1;
2723
+ /** Default number of entries listed per group by {@link explainSkips}. */
2724
+ const DEFAULT_EXPLAIN_LIMIT = 20;
2725
+ /** Largest accepted `limit` for {@link explainSkips}. */
2726
+ const MAX_EXPLAIN_LIMIT = 1e3;
2727
+ function compileLines(lines, ignoreCase) {
2728
+ const rules = [];
2729
+ for (let i = 0; i < lines.length; i++) {
2730
+ const text = lines[i];
2731
+ const matcher = GitignoreMatcher.compile([text], { ignoreCase });
2732
+ if (matcher.hasRules) rules.push({
2733
+ line: i + 1,
2734
+ text,
2735
+ matcher
2736
+ });
2737
+ }
2738
+ return rules;
2739
+ }
2740
+ function lastMatch(rules, path, isDirectory) {
2741
+ for (let i = rules.length - 1; i >= 0; i--) {
2742
+ const rule = rules[i];
2743
+ const result = rule.matcher.test(path, isDirectory);
2744
+ if (result !== void 0) return {
2745
+ rule,
2746
+ ignored: result
2747
+ };
2748
+ }
2749
+ }
2750
+ /**
2751
+ * Re-evaluates the {@link Excluder}'s decision one rule at a time, so the
2752
+ * deciding rule's file and line are known. Ordinary scans never build this:
2753
+ * their matcher merges rules for speed and keeps no rule identity.
2754
+ */
2755
+ var RuleBook = class {
2756
+ #excluder;
2757
+ #root;
2758
+ #user;
2759
+ /** Maps each compiled user rule (`line` is its position in the trimmed list) to `settings.exclude`. */
2760
+ #userIndex;
2761
+ #files = /* @__PURE__ */ new WeakMap();
2762
+ #defaults;
2763
+ constructor(excluder, root, rawPatterns) {
2764
+ this.#excluder = excluder;
2765
+ this.#root = root;
2766
+ this.#defaults = excluder.defaultExcludes ? new Set(DEFAULT_EXCLUDES) : null;
2767
+ const trimmed = [];
2768
+ this.#userIndex = [];
2769
+ rawPatterns.forEach((raw, index) => {
2770
+ const text = raw.trim();
2771
+ if (!text) return;
2772
+ trimmed.push(text);
2773
+ this.#userIndex.push(index);
2774
+ });
2775
+ this.#user = compileLines(trimmed, excluder.ignoreCase);
2776
+ }
2777
+ get ignoreCase() {
2778
+ return this.#excluder.ignoreCase;
2779
+ }
2780
+ rulesOf(source) {
2781
+ let rules = this.#files.get(source);
2782
+ if (rules === void 0) {
2783
+ rules = compileLines(splitRuleLines(source.content), this.ignoreCase);
2784
+ this.#files.set(source, rules);
2785
+ }
2786
+ return rules;
2787
+ }
2788
+ /** Root-relative, `/`-separated name of an ignore file. */
2789
+ fileName(source) {
2790
+ return relative(this.#root, source.file).split(sep).join("/");
2791
+ }
2792
+ userIndex(rule) {
2793
+ return this.#userIndex[rule.line - 1];
2794
+ }
2795
+ /** The same checks, in the same order, as `Excluder.isExcluded`. */
2796
+ match(relPath, name, isDirectory, chain) {
2797
+ const user = lastMatch(this.#user, relPath, isDirectory);
2798
+ const git = this.#excluder.gitignore ? this.#gitMatch(chain, relPath, isDirectory) : void 0;
2799
+ let verdict = null;
2800
+ if (isDirectory && this.#defaults?.has(name)) verdict = {
2801
+ source: "default",
2802
+ name
2803
+ };
2804
+ else if (user?.ignored === true) verdict = {
2805
+ source: "pattern",
2806
+ match: user,
2807
+ index: this.userIndex(user.rule)
2808
+ };
2809
+ else if (git?.ignored === true) verdict = {
2810
+ source: git.scope.source.kind,
2811
+ match: git
2812
+ };
2813
+ return {
2814
+ verdict,
2815
+ user,
2816
+ git
2817
+ };
2818
+ }
2819
+ #gitMatch(chain, relPath, isDirectory) {
2820
+ for (let i = chain.length - 1; i >= 0; i--) {
2821
+ const scope = chain[i];
2822
+ const local = scope.prefix + relPath.slice(scope.strip);
2823
+ if (local === "") continue;
2824
+ const found = lastMatch(this.rulesOf(scope.source), local, isDirectory);
2825
+ if (found) return {
2826
+ ...found,
2827
+ scope,
2828
+ local
2829
+ };
2830
+ }
2831
+ }
2832
+ /** True when a rule matched only because matching ignores case. */
2833
+ reliesOnCase(rule, path, isDirectory) {
2834
+ if (!this.ignoreCase) return false;
2835
+ return GitignoreMatcher.compile([rule.text]).test(path, isDirectory) !== true;
2836
+ }
2837
+ };
2838
+ function emptyReason(source, at, ancestor) {
2839
+ return {
2840
+ source,
2841
+ at,
2842
+ ancestor,
2843
+ file: null,
2844
+ line: null,
2845
+ rule: null,
2846
+ index: null,
2847
+ limit: null,
2848
+ actual: null,
2849
+ code: null
2850
+ };
2851
+ }
2852
+ function reasonFromVerdict(book, verdict, at, ancestor) {
2853
+ if (verdict === null) return emptyReason("unknown", at, ancestor);
2854
+ const reason = emptyReason(verdict.source, at, ancestor);
2855
+ if (verdict.source === "default") reason.rule = verdict.name;
2856
+ else if (verdict.source === "pattern") {
2857
+ reason.rule = verdict.match.rule.text;
2858
+ reason.index = verdict.index;
2859
+ } else {
2860
+ reason.file = book.fileName(verdict.match.scope.source);
2861
+ reason.line = verdict.match.rule.line;
2862
+ reason.rule = verdict.match.rule.text;
2863
+ }
2864
+ return reason;
2865
+ }
2866
+ function ruleNote(book, code, match, message) {
2867
+ if ("scope" in match) return {
2868
+ code,
2869
+ message,
2870
+ file: book.fileName(match.scope.source),
2871
+ line: match.rule.line,
2872
+ rule: match.rule.text
2873
+ };
2874
+ return {
2875
+ code,
2876
+ message,
2877
+ rule: match.rule.text,
2878
+ index: book.userIndex(match.rule)
2879
+ };
2880
+ }
2881
+ function describeRule(book, match) {
2882
+ if ("scope" in match) return `${book.fileName(match.scope.source)}:${match.rule.line} ${match.rule.text}`;
2883
+ return `exclude pattern ${match.rule.text}`;
2884
+ }
2885
+ /** Notes about rules that look like they should have changed an exclusion but cannot. */
2886
+ function verdictNotes(book, matched, relPath, isDirectory) {
2887
+ const notes = [];
2888
+ const { verdict, user, git } = matched;
2889
+ if (verdict?.source === "default") for (const negation of [user, git]) {
2890
+ if (negation?.ignored !== false) continue;
2891
+ notes.push(ruleNote(book, "negation-cannot-reach-default", negation, `${describeRule(book, negation)} has no effect: ${verdict.name} is a default exclude. Use --all to include it.`));
2892
+ }
2893
+ else if ((verdict?.source === "gitignore" || verdict?.source === "info-exclude") && user?.ignored === false) notes.push(ruleNote(book, "negation-cannot-reach-gitignore", user, `${describeRule(book, user)} has no effect: exclude patterns are checked before .gitignore and cannot re-include what it ignores.`));
2894
+ if (verdict !== null && verdict.source !== "default") {
2895
+ const match = verdict.match;
2896
+ const path = "scope" in match ? match.local : relPath;
2897
+ if (match.ignored && book.reliesOnCase(match.rule, path, isDirectory)) notes.push(ruleNote(book, "case-rule-from-platform", match, `${describeRule(book, match)} matches only because matching ignores case on this platform; Git follows the repository's core.ignorecase instead.`));
2898
+ }
2899
+ return notes;
2900
+ }
2901
+ function globalExcludesNote() {
2902
+ return {
2903
+ code: "global-excludes-not-read",
2904
+ message: "Git's global excludes file (core.excludesFile, usually ~/.config/git/ignore) is not read; Git may ignore more than dat does."
2905
+ };
2906
+ }
2907
+ /**
2908
+ * When the root sits inside a repository, reports the first directory between
2909
+ * the repository root and the scan root that Git ignores. dat scans it anyway,
2910
+ * because it was asked to.
2911
+ */
2912
+ function rootIgnoredNote(book, root, repoRoot, chain) {
2913
+ const parts = relative(repoRoot, root).split(sep).filter(Boolean);
2914
+ for (let k = 1; k <= parts.length; k++) {
2915
+ const abs = resolve(repoRoot, ...parts.slice(0, k));
2916
+ for (let i = chain.length - 1; i >= 0; i--) {
2917
+ const scope = chain[i];
2918
+ const base = scope.source.kind === "info-exclude" ? repoRoot : dirname(scope.source.file);
2919
+ const local = relative(base, abs);
2920
+ if (local === "" || local.startsWith("..") || isAbsolute(local)) continue;
2921
+ const found = lastMatch(book.rulesOf(scope.source), local.split(sep).join("/"), true);
2922
+ if (found === void 0) continue;
2923
+ if (!found.ignored) break;
2924
+ const path = parts.slice(0, k).join("/");
2925
+ return {
2926
+ code: "root-ignored-by-git",
2927
+ message: `Git ignores ${path} (${book.fileName(scope.source)}:${found.rule.line} ${found.rule.text}), which contains the scan root. dat scans the root anyway because it was asked to.`,
2928
+ path,
2929
+ file: book.fileName(scope.source),
2930
+ line: found.rule.line,
2931
+ rule: found.rule.text
2932
+ };
2933
+ }
2934
+ }
2935
+ return null;
2936
+ }
2937
+ function nestedRepositoryNote(path) {
2938
+ return {
2939
+ code: "nested-repository",
2940
+ message: `${path} is a separate Git repository: rules from outside it still apply, and its own .git/info/exclude is not read.`,
2941
+ path
2942
+ };
2943
+ }
2944
+ function hardlinkNote(path) {
2945
+ return {
2946
+ code: "hardlink-order-dependent",
2947
+ message: "A file with several hard links is counted once; which of its paths is counted depends on scan order.",
2948
+ ...path === void 0 ? {} : { path }
2949
+ };
2950
+ }
2951
+ function symlinkOrderNote(path) {
2952
+ return {
2953
+ code: "symlink-order-dependent",
2954
+ message: "With --follow-symlinks, a directory reached by several paths is entered once; which path depends on scan order.",
2955
+ ...path === void 0 ? {} : { path }
2956
+ };
2957
+ }
2958
+ function filterReason(options, stats, at, ancestor) {
2959
+ const size = stats.size;
2960
+ const mtime = stats.mtimeMs;
2961
+ const make = (source, rule, limit, actual) => ({
2962
+ ...emptyReason(source, at, ancestor),
2963
+ rule,
2964
+ limit,
2965
+ actual
2966
+ });
2967
+ if (size < options.minSize) return make("size", "minSize", options.minSize, size);
2968
+ if (size > options.maxSize) return make("size", "maxSize", options.maxSize, size);
2969
+ const iso = (ms) => new Date(ms).toISOString();
2970
+ if (mtime < options.modifiedAfter) return make("date", "modifiedAfter", iso(options.modifiedAfter), iso(mtime));
2971
+ if (mtime > options.modifiedBefore) return make("date", "modifiedBefore", iso(options.modifiedBefore), iso(mtime));
2972
+ return null;
2973
+ }
2974
+ function entryType(stats) {
2975
+ if (stats.isSymbolicLink()) return "symlink";
2976
+ if (stats.isDirectory()) return "directory";
2977
+ if (stats.isFile()) return "file";
2978
+ return "other";
2979
+ }
2980
+ function isSpecial(entry) {
2981
+ return entry.isBlockDevice() || entry.isCharacterDevice() || entry.isFIFO() || entry.isSocket();
2982
+ }
2983
+ /**
2984
+ * Explains what a scan of `root` with these settings does with one path:
2985
+ * whether it is counted, and if not, which rule or limit decided and where.
2986
+ *
2987
+ * Runs no full scan. It walks from the root down to the path the way the
2988
+ * scanner does, reading only the directories on the way, and stops at the
2989
+ * first ancestor the scan would not enter. `path` is relative to `root` or
2990
+ * absolute; it must be inside `root`.
2991
+ *
2992
+ * @example
2993
+ * ```ts
2994
+ * import { explainPath } from 'dir-analysis-tool';
2995
+ *
2996
+ * const result = await explainPath('.', 'build/keep/k.txt', { gitignore: true });
2997
+ * console.log(result.decision, result.reason?.file, result.reason?.line);
2998
+ * ```
2999
+ */
3000
+ async function explainPath(root, path, settings = {}) {
3001
+ const { options, settings: resolved } = await resolveScan(root, settings, Date.now());
3002
+ const absRoot = options.root;
3003
+ const target = resolve(absRoot, path);
3004
+ const fromRoot = relative(absRoot, target);
3005
+ if (fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) throw new DatError(`${path} is outside the root ${absRoot}.`, { hint: "Pass the directory that contains it with --root." });
3006
+ const relPath = fromRoot.split(sep).join("/");
3007
+ const segments = relPath ? relPath.split("/") : [];
3008
+ const excluder = options.excluder;
3009
+ const book = new RuleBook(excluder, absRoot, resolved.exclude);
3010
+ const notes = [];
3011
+ const { chain: ancestors, repoRoot } = await excluder.loadAncestors(absRoot);
3012
+ if (excluder.gitignore && repoRoot !== null) {
3013
+ notes.push(globalExcludesNote());
3014
+ if (repoRoot !== absRoot) {
3015
+ const note = rootIgnoredNote(book, absRoot, repoRoot, ancestors);
3016
+ if (note) notes.push(note);
3017
+ }
3018
+ }
3019
+ const result = (decision, type, reason, displayPath = relPath) => ({
3020
+ explainVersion: 1,
3021
+ root: absRoot,
3022
+ path: displayPath,
3023
+ type,
3024
+ decision,
3025
+ reason,
3026
+ descendants: null,
3027
+ notes: [...notes.filter((n) => n.code !== "global-excludes-not-read"), ...notes.filter((n) => n.code === "global-excludes-not-read")],
3028
+ ignoreCase: excluder.ignoreCase,
3029
+ settings: resolved
3030
+ });
3031
+ if (segments.length === 0) return result("included", "directory", null);
3032
+ const targetType = async () => {
3033
+ const stats = await lstat(target).catch(() => null);
3034
+ return stats === null ? null : entryType(stats);
3035
+ };
3036
+ const chain = [...ancestors];
3037
+ let dirAbs = absRoot;
3038
+ let relDir = "";
3039
+ let depth = 0;
3040
+ const onDisk = [];
3041
+ for (let i = 0; i < segments.length; i++) {
3042
+ const isLast = i === segments.length - 1;
3043
+ let entries;
3044
+ try {
3045
+ entries = await readdir(dirAbs, { withFileTypes: true });
3046
+ } catch (error) {
3047
+ const reason = emptyReason("error", relDir, true);
3048
+ reason.code = errorCode(error) ?? "UNKNOWN";
3049
+ return result("skipped", await targetType(), reason);
3050
+ }
3051
+ if (i > 0 && entries.some((e) => e.name === ".git")) notes.push(nestedRepositoryNote(relDir));
3052
+ if (excluder.gitignore && entries.some((e) => e.name === ".gitignore" && !e.isDirectory())) {
3053
+ const scope = await excluder.loadScope(joinRelative(dirAbs, ".gitignore"), relDir);
3054
+ if (scope) chain.push(scope);
3055
+ }
3056
+ const wanted = segments[i];
3057
+ let entry = entries.find((e) => e.name === wanted);
3058
+ if (entry === void 0 && excluder.ignoreCase) {
3059
+ const lower = wanted.toLowerCase();
3060
+ const candidates = entries.filter((e) => e.name.toLowerCase() === lower);
3061
+ if (candidates.length === 1) entry = candidates[0];
3062
+ }
3063
+ if (entry === void 0) return result("not-found", null, null);
3064
+ const name = entry.name;
3065
+ onDisk.push(name);
3066
+ const entryRel = relDir ? `${relDir}/${name}` : name;
3067
+ const fullPath = joinRelative(dirAbs, name);
3068
+ const shownPath = () => [...onDisk, ...segments.slice(i + 1)].join("/");
3069
+ const isDirectory = entry.isDirectory();
3070
+ const isFile = !isDirectory && entry.isFile();
3071
+ if (!isDirectory && !isFile && !entry.isSymbolicLink() && isSpecial(entry)) return result(isLast ? "skipped" : "not-found", isLast ? "other" : null, isLast ? emptyReason("special-file", entryRel, false) : null, shownPath());
3072
+ const excluded = async (asDirectory) => {
3073
+ const matched = book.match(entryRel, name, asDirectory, chain);
3074
+ const reason = reasonFromVerdict(book, matched.verdict, entryRel, !isLast);
3075
+ if (matched.verdict === null) notes.push({
3076
+ code: "explanation-unavailable",
3077
+ message: `The scan excludes ${entryRel}, but no single rule could be identified as the reason.`,
3078
+ path: entryRel
3079
+ });
3080
+ notes.push(...verdictNotes(book, matched, entryRel, asDirectory));
3081
+ const type = await targetType();
3082
+ if (!isLast) {
3083
+ for (let j = i + 1; j < segments.length; j++) {
3084
+ const below = [entryRel, ...segments.slice(i + 1, j + 1)].join("/");
3085
+ const belowIsDirectory = j < segments.length - 1 || type === "directory";
3086
+ const inner = book.match(below, segments[j], belowIsDirectory, chain);
3087
+ const negation = [inner.user, inner.git].find((m) => m?.ignored === false);
3088
+ if (negation) {
3089
+ notes.push(ruleNote(book, "negation-blocked-by-parent", negation, `${describeRule(book, negation)} cannot re-include this: its parent directory ${entryRel} is excluded.`));
3090
+ break;
3091
+ }
3092
+ }
3093
+ if (type === null) notes.push({
3094
+ code: "not-found",
3095
+ message: `${shownPath()} does not exist; its excluded ancestor decides anyway.`,
3096
+ path: shownPath()
3097
+ });
3098
+ }
3099
+ return result("excluded", type, reason, shownPath());
3100
+ };
3101
+ const accept = async (stats, type) => {
3102
+ if (!options.countHardlinks && stats.nlink > 1) notes.push(hardlinkNote(entryRel));
3103
+ const reason = filterReason(options, stats, entryRel, false);
3104
+ return result(reason ? "filtered" : "included", type, reason, shownPath());
3105
+ };
3106
+ const enter = async (type) => {
3107
+ if (depth + 1 > options.maxDepth) {
3108
+ const reason = emptyReason("max-depth", entryRel, !isLast);
3109
+ reason.rule = "maxDepth";
3110
+ reason.limit = options.maxDepth;
3111
+ reason.actual = depth + 1;
3112
+ return result("skipped", isLast ? type : await targetType(), reason, shownPath());
3113
+ }
3114
+ if (isLast) return result("included", type, null, shownPath());
3115
+ dirAbs = fullPath;
3116
+ relDir = entryRel;
3117
+ depth++;
3118
+ return null;
3119
+ };
3120
+ if (excluder.active && excluder.isExcluded(entryRel, name, isDirectory, chain)) return excluded(isDirectory);
3121
+ if (isDirectory && !options.followSymlinks) {
3122
+ const done = await enter("directory");
3123
+ if (done) return done;
3124
+ continue;
3125
+ }
3126
+ if (isFile) {
3127
+ if (!isLast) return result("not-found", null, null);
3128
+ let stats;
3129
+ try {
3130
+ stats = await lstat(fullPath);
3131
+ } catch (error) {
3132
+ const reason = emptyReason("error", entryRel, false);
3133
+ reason.code = errorCode(error) ?? "UNKNOWN";
3134
+ return result("skipped", "file", reason);
3135
+ }
3136
+ return accept(stats, "file");
3137
+ }
3138
+ let stats;
3139
+ let isSymlink = entry.isSymbolicLink();
3140
+ try {
3141
+ stats = await lstat(fullPath);
3142
+ if (stats.isSymbolicLink()) {
3143
+ isSymlink = true;
3144
+ if (!options.followSymlinks) {
3145
+ const reason = emptyReason("symlink", entryRel, !isLast);
3146
+ return result("skipped", isLast ? "symlink" : await targetType(), reason, shownPath());
3147
+ }
3148
+ stats = await stat(fullPath);
3149
+ }
3150
+ } catch (error) {
3151
+ const code = errorCode(error) ?? "UNKNOWN";
3152
+ const reason = emptyReason(isSymlink && (code === "ENOENT" || code === "ELOOP") ? "symlink" : "error", entryRel, !isLast);
3153
+ reason.code = code;
3154
+ return result("skipped", isLast ? isSymlink ? "symlink" : null : null, reason, shownPath());
3155
+ }
3156
+ const type = isSymlink ? "symlink" : entryType(stats);
3157
+ if (stats.isDirectory()) {
3158
+ if (excluder.active && !isDirectory && excluder.isExcluded(entryRel, name, true, chain)) return excluded(true);
3159
+ if (isSymlink) notes.push(symlinkOrderNote(entryRel));
3160
+ const done = await enter(type);
3161
+ if (done) return done;
3162
+ continue;
3163
+ }
3164
+ if (!isLast) return result("not-found", null, null);
3165
+ if (stats.isFile()) return accept(stats, type);
3166
+ return result("skipped", type, emptyReason("special-file", entryRel, false), shownPath());
3167
+ }
3168
+ /* c8 ignore next */
3169
+ return result("not-found", null, null);
3170
+ }
3171
+ /** Keeps the first `limit` paths in path order, whatever order they arrive in. */
3172
+ var Sample = class {
3173
+ #limit;
3174
+ items = [];
3175
+ count = 0;
3176
+ constructor(limit) {
3177
+ this.#limit = limit;
3178
+ }
3179
+ add(path) {
3180
+ this.count++;
3181
+ const items = this.items;
3182
+ if (this.#limit === 0) return;
3183
+ if (items.length === this.#limit && comparePaths(path, items.at(-1)) >= 0) return;
3184
+ let lo = 0;
3185
+ let hi = items.length;
3186
+ while (lo < hi) {
3187
+ const mid = lo + hi >>> 1;
3188
+ if (comparePaths(items[mid], path) < 0) lo = mid + 1;
3189
+ else hi = mid;
3190
+ }
3191
+ items.splice(lo, 0, path);
3192
+ if (items.length > this.#limit) items.pop();
3193
+ }
3194
+ };
3195
+ const SOURCE_ORDER = [
3196
+ "default",
3197
+ "pattern",
3198
+ "info-exclude",
3199
+ "gitignore",
3200
+ "size",
3201
+ "date",
3202
+ "max-depth",
3203
+ "symlink",
3204
+ "special-file",
3205
+ "error",
3206
+ "unknown"
3207
+ ];
3208
+ /**
3209
+ * Runs one scan and reports everything it left out, grouped by the rule or
3210
+ * limit that decided: default excludes, each `exclude` pattern, each
3211
+ * `.gitignore` line, size and date filters, `maxDepth`, and symbolic links
3212
+ * that were not followed. Counts are complete; each group lists at most
3213
+ * `limit` entries, the first in path order.
3214
+ *
3215
+ * Totals equal the `summary` counters of {@link analyze} with the same
3216
+ * settings. Sizes inside excluded directories are never measured.
3217
+ */
3218
+ async function explainSkips(root, options = {}) {
3219
+ const limit = options.limit ?? 20;
3220
+ if (!Number.isInteger(limit) || limit < 0 || limit > 1e3) throw new DatError(`limit must be a whole number from 0 to ${MAX_EXPLAIN_LIMIT} (got ${limit}).`);
3221
+ const { options: scanOptions, settings } = await resolveScan(root, options, Date.now());
3222
+ const absRoot = scanOptions.root;
3223
+ const excluder = scanOptions.excluder;
3224
+ const book = new RuleBook(excluder, absRoot, settings.exclude);
3225
+ const groups = /* @__PURE__ */ new Map();
3226
+ const notes = /* @__PURE__ */ new Map();
3227
+ let depthSkipped = 0;
3228
+ const addNote = (note) => {
3229
+ const key = `${note.code}\0${note.file ?? ""}\0${note.line ?? ""}\0${note.rule ?? ""}\0${note.index ?? ""}`;
3230
+ if (!notes.has(key)) notes.set(key, note);
3231
+ };
3232
+ const groupFor = (key, make) => {
3233
+ let state = groups.get(key);
3234
+ if (state === void 0) {
3235
+ state = {
3236
+ group: make(),
3237
+ sample: new Sample(limit)
3238
+ };
3239
+ groups.set(key, state);
3240
+ }
3241
+ return state.sample;
3242
+ };
3243
+ const base = (source) => ({
3244
+ source,
3245
+ file: null,
3246
+ line: null,
3247
+ rule: null,
3248
+ index: null,
3249
+ limit: null
3250
+ });
3251
+ let scanner = null;
3252
+ const onSkip = (event) => {
3253
+ const rel = scanner.relativePath(event.dir, event.name);
3254
+ switch (event.kind) {
3255
+ case "excluded": {
3256
+ const matched = book.match(rel, event.name, event.isDirectory, event.chain);
3257
+ for (const note of verdictNotes(book, matched, rel, event.isDirectory)) addNote(note);
3258
+ const verdict = matched.verdict;
3259
+ let sample;
3260
+ if (verdict === null) {
3261
+ addNote({
3262
+ code: "explanation-unavailable",
3263
+ message: "Some exclusions could not be traced to a single rule; they are grouped as \"unknown\"."
3264
+ });
3265
+ sample = groupFor("unknown", () => base("unknown"));
3266
+ } else if (verdict.source === "default") sample = groupFor(`default\0${verdict.name}`, () => ({
3267
+ ...base("default"),
3268
+ rule: verdict.name
3269
+ }));
3270
+ else if (verdict.source === "pattern") sample = groupFor(`pattern\0${verdict.index}`, () => ({
3271
+ ...base("pattern"),
3272
+ rule: verdict.match.rule.text,
3273
+ index: verdict.index
3274
+ }));
3275
+ else {
3276
+ const { scope, rule } = verdict.match;
3277
+ sample = groupFor(`${verdict.source}\0${scope.source.file}\0${rule.line}`, () => ({
3278
+ ...base(verdict.source),
3279
+ file: book.fileName(scope.source),
3280
+ line: rule.line,
3281
+ rule: rule.text
3282
+ }));
3283
+ }
3284
+ sample.add(rel);
3285
+ return;
3286
+ }
3287
+ case "filtered": {
3288
+ const reason = filterReason(scanOptions, event.stats, rel, false);
3289
+ groupFor(`${reason.source}\0${reason.rule}`, () => ({
3290
+ ...base(reason.source),
3291
+ rule: reason.rule,
3292
+ limit: reason.limit
3293
+ })).add(rel);
3294
+ return;
3295
+ }
3296
+ case "depth":
3297
+ depthSkipped++;
3298
+ groupFor("max-depth", () => ({
3299
+ ...base("max-depth"),
3300
+ rule: "maxDepth",
3301
+ limit: scanOptions.maxDepth
3302
+ })).add(rel);
3303
+ return;
3304
+ case "symlink":
3305
+ groupFor("symlink", () => base("symlink")).add(rel);
3306
+ return;
3307
+ }
3308
+ };
3309
+ scanner = new Scanner({
3310
+ ...scanOptions,
3311
+ onSkip
3312
+ }, { file() {} });
3313
+ await scanner.run();
3314
+ const rootNotes = [];
3315
+ if (excluder.gitignore) {
3316
+ const { chain, repoRoot } = await excluder.loadAncestors(absRoot);
3317
+ if (repoRoot !== null) {
3318
+ rootNotes.push(globalExcludesNote());
3319
+ if (repoRoot !== absRoot) {
3320
+ const note = rootIgnoredNote(book, absRoot, repoRoot, chain);
3321
+ if (note) rootNotes.push(note);
3322
+ }
3323
+ }
3324
+ }
3325
+ const counters = scanner.counters;
3326
+ if (counters.hardlinks > 0) rootNotes.push(hardlinkNote());
3327
+ if (scanOptions.followSymlinks && counters.symlinks > 0) rootNotes.push(symlinkOrderNote());
3328
+ const sorted = [...groups.values()].map(({ group, sample }) => ({
3329
+ ...group,
3330
+ count: sample.count,
3331
+ entries: sample.items,
3332
+ truncated: sample.count > sample.items.length
3333
+ })).toSorted((a, b) => b.count - a.count || SOURCE_ORDER.indexOf(a.source) - SOURCE_ORDER.indexOf(b.source) || comparePaths(a.file ?? "", b.file ?? "") || (a.line ?? 0) - (b.line ?? 0) || (a.index ?? 0) - (b.index ?? 0) || comparePaths(a.rule ?? "", b.rule ?? ""));
3334
+ return {
3335
+ explainVersion: 1,
3336
+ root: absRoot,
3337
+ totals: {
3338
+ excluded: counters.excluded,
3339
+ filtered: counters.filtered,
3340
+ depthSkipped,
3341
+ symlinks: counters.symlinks,
3342
+ hardlinks: counters.hardlinks,
3343
+ errors: counters.errors
3344
+ },
3345
+ groups: sorted,
3346
+ errors: scanner.errors.slice(0, limit),
3347
+ notes: [...rootNotes, ...notes.values()],
3348
+ limit,
3349
+ ignoreCase: excluder.ignoreCase,
3350
+ settings
3351
+ };
3352
+ }
3353
+ // src/config/schema.ts
2663
3354
  const SIZE_HINT = "Bytes, or a size such as \"512k\", \"25MiB\", or \"1GB\".";
2664
3355
  const TIME_HINT = "An age such as \"30d\", \"6mo\", or \"1y\", or a date (YYYY-MM-DD).";
2665
3356
  /** Single source of truth for config validation, docs, and `schema.json`. */
@@ -2939,8 +3630,7 @@ function jsonType(type) {
2939
3630
  case "enum": return { enum: [...type.values] };
2940
3631
  }
2941
3632
  }
2942
- //#endregion
2943
- //#region src/config/load.ts
3633
+ // src/config/load.ts
2944
3634
  /** File names recognized during discovery, in priority order. */
2945
3635
  const CONFIG_FILE_NAMES = [".dir-analyzer.json", "dir-analyzer.config.json"];
2946
3636
  /** Finds the nearest config file at or above `startDir`. */
@@ -2987,8 +3677,7 @@ async function loadConfig(options) {
2987
3677
  warnings: warnings.map((w) => `${path}: ${w}`)
2988
3678
  };
2989
3679
  }
2990
- //#endregion
2991
- //#region src/format/style.ts
3680
+ // src/format/style.ts
2992
3681
  function supportsColor(stream, env = process.env) {
2993
3682
  const force = env["FORCE_COLOR"];
2994
3683
  if (force !== void 0) return force !== "0" && force !== "false";
@@ -3017,8 +3706,7 @@ const ANSI_PATTERN = /\u001B\[[0-9;]*m/g;
3017
3706
  function stripAnsi(text) {
3018
3707
  return text.replace(ANSI_PATTERN, "");
3019
3708
  }
3020
- //#endregion
3021
- //#region src/format/text.ts
3709
+ // src/format/text.ts
3022
3710
  /** Visible width of a string, ignoring ANSI escapes. */
3023
3711
  function visibleWidth(text) {
3024
3712
  return stripAnsi(text).length;
@@ -3116,8 +3804,7 @@ function formatPercent(part, total) {
3116
3804
  function plural(count, singular, pluralForm = `${singular}s`) {
3117
3805
  return `${formatCount(count)} ${count === 1 ? singular : pluralForm}`;
3118
3806
  }
3119
- //#endregion
3120
- //#region src/reporters/pretty.ts
3807
+ // src/reporters/pretty.ts
3121
3808
  const CATEGORY_LABELS = {
3122
3809
  code: "Code",
3123
3810
  documents: "Documents",
@@ -3364,8 +4051,7 @@ function renderComparison(result, options = {}) {
3364
4051
  r.line("");
3365
4052
  return r.lines.join("\n");
3366
4053
  }
3367
- //#endregion
3368
- //#region src/reporters/markdown.ts
4054
+ // src/reporters/markdown.ts
3369
4055
  /**
3370
4056
  * Inline code that is safe inside a GitHub table cell. The fence is longer than
3371
4057
  * any run of backticks in the text, so a file name cannot close it early and
@@ -3591,8 +4277,7 @@ function renderComparisonMarkdown(result, options = {}) {
3591
4277
  out.push("", `<sub>${plural(result.unchanged, "file")} unchanged, compared by ${result.mode === "content" ? "size and content" : "size"}. Generated by [dir-analysis-tool](https://github.com/KhaledSaeed18/dir-analysis-tool) v${result.tool.version}</sub>`, "");
3592
4278
  return out.join("\n");
3593
4279
  }
3594
- //#endregion
3595
- //#region src/reporters/csv.ts
4280
+ // src/reporters/csv.ts
3596
4281
  /**
3597
4282
  * Quotes a CSV cell when needed (RFC 4180) and neutralizes spreadsheet
3598
4283
  * formula injection: text starting with `=`, `+`, `-`, `@`, tab, or carriage
@@ -3748,8 +4433,7 @@ function renderComparisonCsv(result) {
3748
4433
  "delta"
3749
4434
  ], rows);
3750
4435
  }
3751
- //#endregion
3752
- //#region src/reporters/html.ts
4436
+ // src/reporters/html.ts
3753
4437
  /** Duplicate groups listed in the HTML report; the full list is in JSON and CSV. */
3754
4438
  const DUPLICATE_GROUPS_SHOWN = 100;
3755
4439
  const CATEGORY_COLORS = {
@@ -3963,5 +4647,142 @@ document.getElementById('filter').addEventListener('input', function (event) {
3963
4647
  });
3964
4648
  });
3965
4649
  `;
3966
- //#endregion
3967
- export { BUDGET_METRICS as A, AbortError as B, DEFAULT_CONCURRENCY as C, Excluder as D, DEFAULT_EXCLUDES as E, parseSize as F, errorCode as H, CATEGORIES as I, VERSION as L, formatBudgetActual as M, parseBudget as N, classify as O, formatBytes as P, parseDuration as R, analyze as S, joinRelative as T, errorMessage as U, DatError as V, buildJsonSchema as _, renderComparisonMarkdown as a, DEFAULT_LARGE_FILE_THRESHOLD as b, escapeControl as c, stringifyJson as d, createStyle as f, loadConfig as g, findConfigFile as h, renderAnalysisMarkdown as i, evaluateBudgets as j, extensionOf as k, escapeControlInLines as l, CONFIG_FILE_NAMES as m, renderAnalysisCsv as n, renderAnalysis as o, supportsColor as p, renderComparisonCsv as r, renderComparison as s, renderAnalysisHtml as t, formatCount as u, validateConfig as v, listDirectories as w, DEFAULT_STALE_AGE as x, compare as y, parsePointInTime as z };
4650
+ // src/reporters/explain.ts
4651
+ const SETTING_FLAGS = {
4652
+ minSize: "--min-size",
4653
+ maxSize: "--max-size",
4654
+ modifiedAfter: "--newer-than",
4655
+ modifiedBefore: "--older-than",
4656
+ maxDepth: "--max-depth"
4657
+ };
4658
+ function flagOf(rule) {
4659
+ return (rule && SETTING_FLAGS[rule]) ?? rule ?? "";
4660
+ }
4661
+ function sizeOf(value, units) {
4662
+ return typeof value === "number" ? formatBytes(value, units) : String(value);
4663
+ }
4664
+ /** One-line description of a rule, as shown in both forms. */
4665
+ function ruleLabel(group, units) {
4666
+ const rule = escapeControl(group.rule ?? "");
4667
+ switch (group.source) {
4668
+ case "default": return `default exclude ${rule}`;
4669
+ case "pattern": return `exclude pattern ${(group.index ?? 0) + 1} ${rule}`;
4670
+ case "gitignore":
4671
+ case "info-exclude": return `${escapeControl(group.file ?? "")}:${group.line} ${rule}`;
4672
+ case "size": return `${flagOf(group.rule)} ${sizeOf(group.limit, units)}`;
4673
+ case "date": return `${flagOf(group.rule)} ${String(group.limit)}`;
4674
+ case "max-depth": return `--max-depth ${String(group.limit)}`;
4675
+ case "symlink": return "symbolic links (not followed)";
4676
+ case "special-file": return "special files";
4677
+ case "error": return "unreadable";
4678
+ case "unknown": return "no single rule identified";
4679
+ }
4680
+ }
4681
+ function reasonLines(reason, units, s) {
4682
+ const rows = [];
4683
+ const at = escapeControl(reason.at || ".");
4684
+ if (reason.ancestor) rows.push(["Decided at", `${at} ${s.dim("(parent directory)")}`]);
4685
+ switch (reason.source) {
4686
+ case "default":
4687
+ rows.push(["Rule", `default exclude ${escapeControl(reason.rule ?? "")}`]);
4688
+ rows.push(["Change it", "use --all to include default excludes"]);
4689
+ break;
4690
+ case "pattern":
4691
+ rows.push(["Rule", `exclude pattern ${(reason.index ?? 0) + 1} ${escapeControl(reason.rule ?? "")}`]);
4692
+ break;
4693
+ case "gitignore":
4694
+ case "info-exclude":
4695
+ rows.push(["Rule", `${escapeControl(reason.file ?? "")}:${reason.line} ${escapeControl(reason.rule ?? "")}`]);
4696
+ break;
4697
+ case "size":
4698
+ rows.push(["Rule", `${flagOf(reason.rule)} ${sizeOf(reason.limit, units)}; the file is ${sizeOf(reason.actual, units)} (${formatCount(Number(reason.actual))} bytes)`]);
4699
+ break;
4700
+ case "date":
4701
+ rows.push(["Rule", `${flagOf(reason.rule)} ${String(reason.limit)}; modified ${String(reason.actual)}`]);
4702
+ break;
4703
+ case "max-depth":
4704
+ rows.push(["Rule", `--max-depth ${String(reason.limit)}; ${at} is at depth ${String(reason.actual)}`]);
4705
+ break;
4706
+ case "symlink":
4707
+ rows.push(["Rule", reason.code ? `symbolic link to nothing (${reason.code}); counted, not followed` : "symbolic link; counted, not followed (use -L to follow)"]);
4708
+ break;
4709
+ case "special-file":
4710
+ rows.push(["Rule", "special file (socket, FIFO, or device); never counted"]);
4711
+ break;
4712
+ case "error":
4713
+ rows.push(["Error", `${reason.code ?? "UNKNOWN"}: could not read ${at}`]);
4714
+ break;
4715
+ case "unknown": rows.push(["Rule", "no single rule identified"]);
4716
+ }
4717
+ return rows;
4718
+ }
4719
+ function noteText(note) {
4720
+ return escapeControl(note.message);
4721
+ }
4722
+ const HEADLINE = {
4723
+ included: "included",
4724
+ excluded: "excluded",
4725
+ filtered: "filtered",
4726
+ skipped: "skipped",
4727
+ "not-found": "not found"
4728
+ };
4729
+ /** Human-readable explanation of one path. */
4730
+ function renderPathExplanation(result, options = {}) {
4731
+ const s = options.style ?? createStyle(false);
4732
+ const units = options.units ?? "iec";
4733
+ const paint = (text) => result.decision === "included" ? s.green(text) : result.decision === "not-found" ? s.yellow(text) : s.red(text);
4734
+ const shown = escapeControl(result.path || ".");
4735
+ const lines = [`${s.bold(shown)}: ${paint(HEADLINE[result.decision])}`, ""];
4736
+ const rows = [];
4737
+ if (result.reason) {
4738
+ rows.push(...reasonLines(result.reason, units, s));
4739
+ if ((result.reason.ancestor || result.type === "directory" && (result.decision === "excluded" || result.decision === "skipped")) && result.reason.source !== "symlink") rows.push(["Inside it", "not measured; dat never enters a directory it skips"]);
4740
+ } else if (result.decision === "included") rows.push(["Counted", "yes, by a scan with these settings"]);
4741
+ else rows.push(["Path", `nothing at ${shown} under ${escapeControl(result.root)}`]);
4742
+ for (const note of result.notes) rows.push(["Note", noteText(note)]);
4743
+ const width = Math.max(...rows.map(([label]) => label.length));
4744
+ for (const [label, value] of rows) lines.push(` ${s.dim(label.padEnd(width))} ${value}`);
4745
+ return `${lines.join("\n")}\n`;
4746
+ }
4747
+ /** Human-readable summary of everything a scan left out. */
4748
+ function renderSkipsExplanation(result, options = {}) {
4749
+ const s = options.style ?? createStyle(false);
4750
+ const units = options.units ?? "iec";
4751
+ const width = options.width ?? 100;
4752
+ const { totals } = result;
4753
+ const parts = [];
4754
+ if (totals.excluded > 0) parts.push(`${plural(totals.excluded, "entry", "entries")} excluded`);
4755
+ if (totals.filtered > 0) parts.push(`${plural(totals.filtered, "file")} filtered`);
4756
+ if (totals.depthSkipped > 0) parts.push(`${plural(totals.depthSkipped, "directory", "directories")} beyond --max-depth`);
4757
+ const unfollowed = result.groups.find((g) => g.source === "symlink")?.count ?? 0;
4758
+ if (unfollowed > 0) parts.push(`${plural(unfollowed, "symbolic link")} not followed`);
4759
+ if (totals.errors > 0) parts.push(`${plural(totals.errors, "entry", "entries")} unreadable`);
4760
+ const lines = [];
4761
+ lines.push(parts.length > 0 ? s.bold(`Skipped: ${parts.join(", ")}`) : s.bold("Nothing was skipped: every entry is counted."));
4762
+ if (result.groups.length > 0) {
4763
+ lines.push("");
4764
+ const labels = result.groups.map((g) => ruleLabel(g, units));
4765
+ const labelWidth = Math.min(48, Math.max(...labels.map((l) => l.length)));
4766
+ const countWidth = Math.max(...result.groups.map((g) => formatCount(g.count).length));
4767
+ result.groups.forEach((group, i) => {
4768
+ lines.push(` ${padEndVisible(labels[i], labelWidth)} ${s.bold(formatCount(group.count).padStart(countWidth))}`);
4769
+ for (const entry of group.entries) lines.push(` ${fitPath(entry, width - 6)}`);
4770
+ if (group.truncated) {
4771
+ const rest = group.count - group.entries.length;
4772
+ lines.push(s.dim(` … and ${formatCount(rest)} more (raise --limit, up to 1000, to list more)`));
4773
+ }
4774
+ });
4775
+ }
4776
+ if (result.errors.length > 0) {
4777
+ lines.push("", ` ${s.yellow("Unreadable")}`);
4778
+ for (const error of result.errors) lines.push(` ${fitPath(error.path, width - 20)} ${s.dim(error.code)}`);
4779
+ }
4780
+ const notes = result.notes.map(noteText);
4781
+ if (result.groups.some((g) => g.source !== "size" && g.source !== "date")) notes.push("Sizes inside skipped directories are unknown. Measure one with: dat <dir> --all");
4782
+ if (notes.length > 0) {
4783
+ lines.push("");
4784
+ for (const note of notes) lines.push(s.dim(note));
4785
+ }
4786
+ return `${lines.join("\n")}\n`;
4787
+ }
4788
+ export { DEFAULT_CONCURRENCY as A, parseBudget as B, MAX_EXPLAIN_LIMIT as C, DEFAULT_LARGE_FILE_THRESHOLD as D, compare as E, classify as F, parseDuration as G, parseSize as H, extensionOf as I, DatError as J, parsePointInTime as K, BUDGET_METRICS as L, joinRelative as M, DEFAULT_EXCLUDES as N, DEFAULT_STALE_AGE as O, Excluder as P, evaluateBudgets as R, EXPLAIN_VERSION as S, explainSkips as T, CATEGORIES as U, formatBytes as V, VERSION as W, errorMessage as X, errorCode as Y, 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, listDirectories as j, analyze as k, renderComparison as l, createStyle as m, renderSkipsExplanation as n, renderAnalysisMarkdown as o, stringifyJson as p, AbortError 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, formatBudgetActual as z };