dir-analysis-tool 3.2.0 → 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
  *
@@ -928,6 +920,7 @@ var GitignoreMatcher = class GitignoreMatcher {
928
920
  const runs = this.#runs;
929
921
  let name;
930
922
  let folded;
923
+ let foldedPath;
931
924
  for (let i = runs.length - 1; i >= 0; i--) {
932
925
  const run = runs[i];
933
926
  const fast = isDirectory && run.dirFast !== null ? true : run.anyFast !== null;
@@ -941,11 +934,21 @@ var GitignoreMatcher = class GitignoreMatcher {
941
934
  if (run.anyName?.test(name) || isDirectory && run.dirName?.test(name)) return !run.negated;
942
935
  }
943
936
  if (run.anyPath?.test(path) || isDirectory && run.dirPath?.test(path)) return !run.negated;
937
+ if (run.globs !== null) {
938
+ name ??= path.slice(path.lastIndexOf("/") + 1);
939
+ for (const glob of run.globs) {
940
+ if (glob.dirOnly && !isDirectory) continue;
941
+ if (this.#ignoreCase) {
942
+ if (!(glob.nameOnly ? folded ??= name.toLowerCase() : foldedPath ??= path.toLowerCase()).includes(glob.required)) continue;
943
+ } else if (!(glob.nameOnly ? name : path).includes(glob.required)) continue;
944
+ if (glob.matches(glob.nameOnly ? name : path)) return !run.negated;
945
+ }
946
+ }
944
947
  }
945
948
  }
946
949
  /** Compiles the contents of an ignore file (or a list of patterns). */
947
950
  static compile(source, options = {}) {
948
- const lines = typeof source === "string" ? source.split(/\r?\n/) : source;
951
+ const lines = typeof source === "string" ? splitRuleLines(source) : source;
949
952
  const ignoreCase = options.ignoreCase === true;
950
953
  const flags = ignoreCase ? "i" : "";
951
954
  const runs = [];
@@ -960,9 +963,10 @@ var GitignoreMatcher = class GitignoreMatcher {
960
963
  anyName: regex(parts.anyName),
961
964
  dirName: regex(parts.dirName),
962
965
  anyPath: regex(parts.anyPath),
963
- dirPath: regex(parts.dirPath)
966
+ dirPath: regex(parts.dirPath),
967
+ globs: parts.globs.length > 0 ? parts.globs : null
964
968
  };
965
- if (run.anyFast || run.dirFast || run.anyName || run.dirName || run.anyPath || run.dirPath) runs.push(run);
969
+ if (run.anyFast || run.dirFast || run.anyName || run.dirName || run.anyPath || run.dirPath || run.globs) runs.push(run);
966
970
  parts = new RunParts();
967
971
  };
968
972
  for (const line of lines) {
@@ -977,7 +981,8 @@ var GitignoreMatcher = class GitignoreMatcher {
977
981
  const value = ignoreCase ? rule.fast.value.toLowerCase() : rule.fast.value;
978
982
  if (rule.fast.kind === "literal") target.literals.add(value);
979
983
  else target.addSuffix(value);
980
- } else if (rule.nameOnly) (rule.dirOnly ? parts.dirName : parts.anyName).push(rule.source);
984
+ } else if (rule.wildcards >= LINEAR_GLOB_WILDCARDS) parts.globs.push(new LinearGlob(rule, ignoreCase));
985
+ else if (rule.nameOnly) (rule.dirOnly ? parts.dirName : parts.anyName).push(rule.source);
981
986
  else (rule.dirOnly ? parts.dirPath : parts.anyPath).push(rule.source);
982
987
  }
983
988
  flush();
@@ -1014,12 +1019,191 @@ var RunParts = class {
1014
1019
  dirName = [];
1015
1020
  anyPath = [];
1016
1021
  dirPath = [];
1022
+ globs = [];
1023
+ };
1024
+ const STAR = { kind: "star" };
1025
+ const ALL = { kind: "all" };
1026
+ const DIRS = { kind: "dirs" };
1027
+ const ANY = { kind: "any" };
1028
+ /** Rules with at least this many wildcards use {@link LinearGlob}. */
1029
+ const LINEAR_GLOB_WILDCARDS = 2;
1030
+ function isWildcard(token) {
1031
+ return token.kind === "star" || token.kind === "all" || token.kind === "dirs";
1032
+ }
1033
+ /** JavaScript's `.` skips line breaks, so these use `[^]`, which matches any character. */
1034
+ function tokenSource(token) {
1035
+ switch (token.kind) {
1036
+ case "char": return escapeRegex(token.char);
1037
+ case "class": return token.source;
1038
+ case "any": return "[^/]";
1039
+ case "star": return "[^/]*";
1040
+ case "all": return "[^]*";
1041
+ case "dirs": return "(?:[^]*/)?";
1042
+ }
1043
+ }
1044
+ const CHAR = 0;
1045
+ const CLASS = 1;
1046
+ const ANY_CHAR = 2;
1047
+ const ANY_RUN = 3;
1048
+ const ALL_RUN = 4;
1049
+ const OPCODES = {
1050
+ char: CHAR,
1051
+ class: CLASS,
1052
+ any: ANY_CHAR,
1053
+ star: ANY_RUN,
1054
+ all: ALL_RUN,
1055
+ dirs: 5
1056
+ };
1057
+ /** The same case folding as a regular expression with the `i` flag. */
1058
+ function foldCase(c) {
1059
+ const upper = c.toUpperCase();
1060
+ if (upper.length !== 1) return c;
1061
+ return c.charCodeAt(0) >= 128 && upper.charCodeAt(0) < 128 ? c : upper;
1062
+ }
1063
+ /** The longest stretch of plain ASCII characters that a glob must match literally. */
1064
+ function longestAsciiRun(tokens) {
1065
+ let longest = "";
1066
+ let run = "";
1067
+ for (const token of tokens) if (token.kind === "char" && token.char.charCodeAt(0) < 128) {
1068
+ run += token.char;
1069
+ if (run.length > longest.length) longest = run;
1070
+ } else run = "";
1071
+ return longest;
1072
+ }
1073
+ /**
1074
+ * Matches a parsed glob by tracking every position it could be at, one input
1075
+ * character at a time. Nothing is ever retried, so the time is bounded by the
1076
+ * length of the path times the length of the pattern, whatever the pattern is.
1077
+ */
1078
+ var LinearGlob = class {
1079
+ dirOnly;
1080
+ nameOnly;
1081
+ /**
1082
+ * Text every match must contain, in lower case when ignoring case. Only ASCII
1083
+ * is used: a regular expression's `i` flag never folds other characters into
1084
+ * ASCII, so lower-casing a path cannot hide or invent an occurrence of it.
1085
+ */
1086
+ required;
1087
+ #ops;
1088
+ #chars;
1089
+ #classes;
1090
+ #accept;
1091
+ #ignoreCase;
1092
+ #current;
1093
+ #next;
1094
+ #nextCount = 0;
1095
+ /** The step at which each position was last added, so it is added only once per step. */
1096
+ #added;
1097
+ /** The same for following a wildcard to the position after it. */
1098
+ #skipped;
1099
+ #step = 0;
1100
+ constructor(rule, ignoreCase) {
1101
+ const { tokens } = rule;
1102
+ this.dirOnly = rule.dirOnly;
1103
+ this.nameOnly = rule.nameOnly;
1104
+ this.#ignoreCase = ignoreCase;
1105
+ const required = longestAsciiRun(tokens);
1106
+ this.required = ignoreCase ? required.toLowerCase() : required;
1107
+ const size = tokens.length + 1;
1108
+ this.#accept = tokens.length;
1109
+ this.#ops = Uint8Array.from(tokens, (token) => OPCODES[token.kind]);
1110
+ this.#chars = tokens.map((token) => {
1111
+ if (token.kind !== "char") return "";
1112
+ return ignoreCase ? foldCase(token.char) : token.char;
1113
+ });
1114
+ this.#classes = tokens.map((token) => token.kind === "class" ? new RegExp(`^${token.source}$`, ignoreCase ? "i" : "") : null);
1115
+ this.#current = new Int32Array(size);
1116
+ this.#next = new Int32Array(size);
1117
+ this.#added = new Float64Array(size);
1118
+ this.#skipped = new Float64Array(size);
1119
+ }
1120
+ matches(text) {
1121
+ const ops = this.#ops;
1122
+ const chars = this.#chars;
1123
+ const accept = this.#accept;
1124
+ this.#nextCount = 0;
1125
+ this.#step++;
1126
+ this.#add(0, true);
1127
+ for (let i = 0; i < text.length; i++) {
1128
+ const count = this.#nextCount;
1129
+ if (count === 0) return false;
1130
+ const current = this.#next;
1131
+ this.#next = this.#current;
1132
+ this.#current = current;
1133
+ this.#nextCount = 0;
1134
+ this.#step++;
1135
+ const c = text[i];
1136
+ const folded = this.#ignoreCase ? foldCase(c) : c;
1137
+ for (let k = 0; k < count; k++) {
1138
+ const position = current[k];
1139
+ if (position === accept) continue;
1140
+ switch (ops[position]) {
1141
+ case CHAR:
1142
+ if (folded === chars[position]) this.#add(position + 1, true);
1143
+ break;
1144
+ case CLASS:
1145
+ if (this.#classes[position].test(c)) this.#add(position + 1, true);
1146
+ break;
1147
+ case ANY_CHAR:
1148
+ if (c !== "/") this.#add(position + 1, true);
1149
+ break;
1150
+ case ANY_RUN:
1151
+ if (c !== "/") this.#add(position, true);
1152
+ break;
1153
+ case ALL_RUN:
1154
+ this.#add(position, true);
1155
+ break;
1156
+ default:
1157
+ this.#add(position, false);
1158
+ if (c === "/") this.#add(position + 1, true);
1159
+ }
1160
+ }
1161
+ }
1162
+ return this.#added[accept] === this.#step;
1163
+ }
1164
+ #add(position, arriving) {
1165
+ const step = this.#step;
1166
+ for (let at = position;; at++) {
1167
+ if (this.#added[at] !== step) {
1168
+ this.#added[at] = step;
1169
+ this.#next[this.#nextCount++] = at;
1170
+ }
1171
+ if (!arriving || at === this.#accept || this.#ops[at] < ANY_RUN) return;
1172
+ if (this.#skipped[at] === step) return;
1173
+ this.#skipped[at] = step;
1174
+ }
1175
+ }
1017
1176
  };
1018
1177
  /** No wildcards, classes, or escapes: the pattern is a literal name (or suffix). */
1019
1178
  const LITERAL = /^[^*?[\\]+$/;
1020
- /** Turns one gitignore line into a regex fragment; `null` for blanks and comments. */
1179
+ /** A line ending; a final CR counts because Git treats the end of a file as a newline. */
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
+ }
1188
+ /** Removes unescaped trailing spaces. Tabs are significant, as they are in Git. */
1189
+ function trimTrailingSpaces(line) {
1190
+ let end = line.length;
1191
+ let spaces = -1;
1192
+ for (let i = 0; i < line.length; i++) if (line[i] === " ") {
1193
+ if (spaces === -1) spaces = i;
1194
+ } else {
1195
+ if (line[i] === "\\") i++;
1196
+ spaces = -1;
1197
+ }
1198
+ if (spaces !== -1) end = spaces;
1199
+ return line.slice(0, end);
1200
+ }
1201
+ /**
1202
+ * Turns one gitignore line into a regex fragment. Returns `null` for blanks,
1203
+ * comments, and malformed patterns, which Git treats as never matching.
1204
+ */
1021
1205
  function parseRule(line) {
1022
- let pattern = line.replace(/(?<!\\)\s+$/, "");
1206
+ let pattern = trimTrailingSpaces(line);
1023
1207
  if (pattern === "" || pattern.startsWith("#")) return null;
1024
1208
  let negated = false;
1025
1209
  if (pattern.startsWith("!")) {
@@ -1028,25 +1212,27 @@ function parseRule(line) {
1028
1212
  } else if (pattern.startsWith("\\!") || pattern.startsWith("\\#")) pattern = pattern.slice(1);
1029
1213
  if (pattern === "") return null;
1030
1214
  let dirOnly = false;
1031
- if (pattern.endsWith("/") && !pattern.endsWith("\\/")) {
1215
+ if (pattern.endsWith("/")) {
1032
1216
  dirOnly = true;
1033
- pattern = pattern.replace(/\/+$/, "");
1217
+ pattern = pattern.slice(0, -1);
1034
1218
  if (pattern === "") return null;
1035
1219
  }
1036
1220
  let anchored = false;
1037
1221
  if (pattern.startsWith("/")) {
1038
1222
  anchored = true;
1039
- pattern = pattern.replace(/^\/+/, "");
1223
+ pattern = pattern.slice(1);
1040
1224
  } else if (pattern.includes("/")) anchored = true;
1041
1225
  if (pattern.startsWith("**/")) {
1042
1226
  anchored = false;
1043
1227
  pattern = pattern.replace(/^(\*\*\/)+/, "");
1044
1228
  }
1045
1229
  if (pattern === "") return null;
1046
- const body = globToRegex(pattern);
1230
+ const body = parseGlob(pattern);
1047
1231
  if (body === null) return null;
1048
1232
  const nameOnly = !anchored && !pattern.includes("/") && !pattern.includes("**");
1049
- const source = anchored || nameOnly ? body : `(?:.*/)?${body}`;
1233
+ const tokens = anchored || nameOnly ? body : [DIRS, ...body];
1234
+ const source = tokens.map(tokenSource).join("");
1235
+ const wildcards = tokens.filter(isWildcard).length;
1050
1236
  let fast = null;
1051
1237
  if (nameOnly) {
1052
1238
  if (LITERAL.test(pattern)) fast = {
@@ -1063,77 +1249,107 @@ function parseRule(line) {
1063
1249
  dirOnly,
1064
1250
  nameOnly,
1065
1251
  fast,
1066
- source
1252
+ source,
1253
+ tokens,
1254
+ wildcards
1067
1255
  };
1068
1256
  }
1069
1257
  /**
1070
- * Translates a gitignore glob (already stripped of anchors and trailing
1071
- * slashes) into regex source. Returns `null` for an unusable pattern.
1258
+ * Parses a gitignore glob (already stripped of anchors and trailing slashes).
1259
+ * Returns `null` for a malformed pattern.
1072
1260
  */
1073
- function globToRegex(glob) {
1074
- let out = "";
1261
+ function parseGlob(glob) {
1262
+ const out = [];
1075
1263
  const n = glob.length;
1076
1264
  for (let i = 0; i < n; i++) {
1077
1265
  const c = glob[i];
1078
1266
  if (c === "\\") {
1079
- if (i + 1 < n) out += escapeRegex(glob[++i]);
1080
- else out += "\\\\";
1267
+ if (i + 1 >= n) return null;
1268
+ out.push({
1269
+ kind: "char",
1270
+ char: glob[++i]
1271
+ });
1081
1272
  } else if (c === "*") {
1082
1273
  if (glob[i + 1] === "*") {
1083
1274
  let j = i + 1;
1084
1275
  while (glob[j] === "*") j++;
1085
1276
  const atStart = i === 0 || glob[i - 1] === "/";
1086
- if (atStart && j === n) out += ".*";
1277
+ if (atStart && j === n) out.push(ALL);
1087
1278
  else if (atStart && glob[j] === "/") {
1088
- out += "(?:.*/)?";
1279
+ out.push(DIRS);
1089
1280
  j++;
1090
- } else out += "[^/]*";
1281
+ } else out.push(STAR);
1091
1282
  i = j - 1;
1092
- } else out += "[^/]*";
1093
- } else if (c === "?") out += "[^/]";
1283
+ } else out.push(STAR);
1284
+ } else if (c === "?") out.push(ANY);
1094
1285
  else if (c === "[") {
1095
1286
  const cls = parseClass(glob, i);
1096
- if (cls === null) out += "\\[";
1097
- else {
1098
- out += cls.source;
1099
- i = cls.end;
1100
- }
1101
- } else if (c === "/") out += "/";
1102
- else out += escapeRegex(c);
1287
+ if (cls === null) return null;
1288
+ out.push({
1289
+ kind: "class",
1290
+ source: cls.source
1291
+ });
1292
+ i = cls.end;
1293
+ } else out.push({
1294
+ kind: "char",
1295
+ char: c
1296
+ });
1103
1297
  }
1104
1298
  return out;
1105
1299
  }
1106
- /** Parses a bracket expression starting at `start`; `null` when it is not closed. */
1300
+ /**
1301
+ * Parses a bracket expression starting at `start`, following Git's wildmatch.
1302
+ * Returns `null` when it is malformed (not closed, or an unknown POSIX class).
1303
+ */
1107
1304
  function parseClass(glob, start) {
1108
1305
  let i = start + 1;
1109
- let negate = false;
1110
- if (glob[i] === "!" || glob[i] === "^") {
1111
- negate = true;
1112
- i++;
1113
- }
1306
+ const negate = glob[i] === "!" || glob[i] === "^";
1307
+ if (negate) i++;
1114
1308
  let body = "";
1115
- let first = true;
1116
- for (; i < glob.length; i++) {
1309
+ let rangeStart;
1310
+ for (let first = true;; i++, first = false) {
1117
1311
  const c = glob[i];
1118
- if (c === "]" && !first) return {
1119
- source: negate ? `(?!/)[^${body}]` : `[${body}]`,
1120
- end: i
1121
- };
1122
- first = false;
1123
- if (c === "\\" && i + 1 < glob.length) body += `\\${glob[++i]}`;
1124
- else if (c === "[" && glob[i + 1] === ":") {
1125
- const close = glob.indexOf(":]", i + 2);
1312
+ if (c === void 0) return null;
1313
+ if (c === "]" && !first) break;
1314
+ if (c === "\\") {
1315
+ const escaped = glob[++i];
1316
+ if (escaped === void 0) return null;
1317
+ body += escapeInClass(escaped);
1318
+ rangeStart = escaped;
1319
+ } else if (c === "-" && rangeStart !== void 0 && !isClassEnd(glob[i + 1])) {
1320
+ let end = glob[++i];
1321
+ if (end === "\\") {
1322
+ const escaped = glob[++i];
1323
+ if (escaped === void 0) return null;
1324
+ end = escaped;
1325
+ }
1326
+ if (rangeStart <= end) body += `${escapeInClass(rangeStart)}-${escapeInClass(end)}`;
1327
+ rangeStart = void 0;
1328
+ } else if (c === "[" && glob[i + 1] === ":") {
1329
+ const close = glob.indexOf("]", i + 2);
1126
1330
  if (close === -1) return null;
1127
- const name = glob.slice(i + 2, close);
1128
- const posix = POSIX_CLASSES[name];
1129
- if (posix === void 0) return null;
1130
- body += posix;
1131
- i = close + 1;
1132
- } else if (c === "/") return null;
1133
- else if (c === "-" || c === "]" || c === "^") body += c === "]" ? "\\]" : c === "^" ? "\\^" : "-";
1134
- else body += escapeInClass(c);
1331
+ if (glob[close - 1] === ":" && close - 1 >= i + 2) {
1332
+ const posix = POSIX_CLASSES[glob.slice(i + 2, close - 1)];
1333
+ if (posix === void 0) return null;
1334
+ body += posix;
1335
+ i = close;
1336
+ rangeStart = void 0;
1337
+ } else {
1338
+ body += escapeInClass(c);
1339
+ rangeStart = c;
1340
+ }
1341
+ } else {
1342
+ body += escapeInClass(c);
1343
+ rangeStart = c;
1344
+ }
1135
1345
  }
1136
- return null;
1346
+ return {
1347
+ source: `(?!/)[${negate ? "^" : ""}${body}]`,
1348
+ end: i
1349
+ };
1350
+ }
1351
+ function isClassEnd(c) {
1352
+ return c === void 0 || c === "]";
1137
1353
  }
1138
1354
  const POSIX_CLASSES = {
1139
1355
  alnum: "a-zA-Z0-9",
@@ -1153,10 +1369,9 @@ function escapeRegex(c) {
1153
1369
  return /[\\^$.*+?()[\]{}|/-]/.test(c) ? `\\${c}` : c;
1154
1370
  }
1155
1371
  function escapeInClass(c) {
1156
- return c === "\\" ? "\\\\" : c;
1372
+ return /[\\\]^[-]/.test(c) ? `\\${c}` : c;
1157
1373
  }
1158
- //#endregion
1159
- //#region src/core/exclude.ts
1374
+ // src/core/exclude.ts
1160
1375
  /** Directories skipped unless default excludes are turned off. */
1161
1376
  const DEFAULT_EXCLUDES = [
1162
1377
  ".git",
@@ -1176,14 +1391,25 @@ var Excluder = class {
1176
1391
  #defaults;
1177
1392
  #user;
1178
1393
  #ignoreCase;
1394
+ /** Trimmed, non-empty user patterns, as they were compiled. */
1395
+ patterns;
1179
1396
  constructor(options = {}) {
1180
1397
  this.gitignore = options.gitignore ?? false;
1181
1398
  this.#ignoreCase = options.ignoreCase ?? process.platform !== "linux";
1182
1399
  this.#defaults = options.defaultExcludes ?? true ? new Set(DEFAULT_EXCLUDES) : null;
1183
1400
  const patterns = (options.patterns ?? []).map((p) => p.trim()).filter(Boolean);
1401
+ this.patterns = patterns;
1184
1402
  const user = patterns.length > 0 ? this.#compile(patterns) : null;
1185
1403
  this.#user = user?.hasRules ? user : null;
1186
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
+ }
1187
1413
  /** True when at least one rule could exclude something. */
1188
1414
  get active() {
1189
1415
  return this.#defaults !== null || this.#user !== null || this.gitignore;
@@ -1226,7 +1452,12 @@ var Excluder = class {
1226
1452
  return {
1227
1453
  matcher,
1228
1454
  prefix: "",
1229
- strip: rootRelativeDir ? rootRelativeDir.length + 1 : 0
1455
+ strip: rootRelativeDir ? rootRelativeDir.length + 1 : 0,
1456
+ source: {
1457
+ kind: "gitignore",
1458
+ file: filePath,
1459
+ content
1460
+ }
1230
1461
  };
1231
1462
  }
1232
1463
  /**
@@ -1235,7 +1466,14 @@ var Excluder = class {
1235
1466
  * `.git/info/exclude`, so a sub-directory scan matches Git's view.
1236
1467
  */
1237
1468
  async loadAncestorChain(root) {
1238
- 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
+ };
1239
1477
  const ancestors = [];
1240
1478
  let repoRoot = null;
1241
1479
  let current = root;
@@ -1249,10 +1487,13 @@ var Excluder = class {
1249
1487
  ancestors.push(parent);
1250
1488
  current = parent;
1251
1489
  }
1252
- if (repoRoot === null) return EMPTY_CHAIN;
1490
+ if (repoRoot === null) return {
1491
+ chain: EMPTY_CHAIN,
1492
+ repoRoot: null
1493
+ };
1253
1494
  const scopes = [];
1254
1495
  const outermostFirst = repoRoot === root ? [] : ancestors.reverse();
1255
- const add = async (file, base) => {
1496
+ const add = async (file, base, kind) => {
1256
1497
  const content = await readFile$1(file, "utf8").catch(() => null);
1257
1498
  if (content === null) return;
1258
1499
  const matcher = this.#compile(content);
@@ -1261,17 +1502,41 @@ var Excluder = class {
1261
1502
  scopes.push({
1262
1503
  matcher,
1263
1504
  prefix: prefix ? `${prefix}/` : "",
1264
- strip: 0
1505
+ strip: 0,
1506
+ source: {
1507
+ kind,
1508
+ file,
1509
+ content
1510
+ }
1265
1511
  });
1266
1512
  };
1267
- await add(join(repoRoot, ".git", "info", "exclude"), repoRoot);
1268
- for (const dir of outermostFirst) await add(join(dir, ".gitignore"), dir);
1269
- return scopes;
1513
+ const infoExclude = await findInfoExclude(repoRoot);
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
+ };
1270
1520
  }
1271
1521
  #compile(source) {
1272
1522
  return GitignoreMatcher.compile(source, { ignoreCase: this.#ignoreCase });
1273
1523
  }
1274
1524
  };
1525
+ /**
1526
+ * Locates `info/exclude`. In a linked worktree or a submodule `.git` is a file
1527
+ * naming the real Git directory, and a worktree shares its main repository's
1528
+ * exclude file through `commondir`.
1529
+ */
1530
+ async function findInfoExclude(repoRoot) {
1531
+ const dotGit = join(repoRoot, ".git");
1532
+ const pointer = await readFile$1(dotGit, "utf8").catch(() => null);
1533
+ if (pointer === null) return join(dotGit, "info", "exclude");
1534
+ const gitDir = /^gitdir:\s*(.+?)\s*$/m.exec(pointer)?.[1];
1535
+ if (gitDir === void 0) return null;
1536
+ const dir = resolve(repoRoot, gitDir);
1537
+ const commonDir = await readFile$1(join(dir, "commondir"), "utf8").catch(() => null);
1538
+ return join(commonDir === null ? dir : resolve(dir, commonDir.trim()), "info", "exclude");
1539
+ }
1275
1540
  function isGitIgnored(chain, relPath, isDirectory) {
1276
1541
  let ignored = false;
1277
1542
  for (const scope of chain) {
@@ -1282,8 +1547,7 @@ function isGitIgnored(chain, relPath, isDirectory) {
1282
1547
  }
1283
1548
  return ignored;
1284
1549
  }
1285
- //#endregion
1286
- //#region src/core/limiter.ts
1550
+ // src/core/limiter.ts
1287
1551
  /**
1288
1552
  * A tiny concurrency limiter for filesystem work.
1289
1553
  *
@@ -1349,8 +1613,7 @@ var Limiter = class {
1349
1613
  this.abort(error);
1350
1614
  };
1351
1615
  };
1352
- //#endregion
1353
- //#region src/core/paths.ts
1616
+ // src/core/paths.ts
1354
1617
  /** Ordinal comparison, so output order never depends on the locale. */
1355
1618
  function comparePaths(a, b) {
1356
1619
  return a < b ? -1 : a > b ? 1 : 0;
@@ -1475,6 +1738,13 @@ var Scanner = class {
1475
1738
  const rel = relDir ? `${relDir}/${name}` : name;
1476
1739
  if (excluder.isExcluded(rel, name, isDirectory, chain)) {
1477
1740
  this.counters.excluded++;
1741
+ this.#options.onSkip?.({
1742
+ kind: "excluded",
1743
+ dir: index,
1744
+ name,
1745
+ isDirectory,
1746
+ chain
1747
+ });
1478
1748
  continue;
1479
1749
  }
1480
1750
  }
@@ -1487,7 +1757,15 @@ var Scanner = class {
1487
1757
  }
1488
1758
  #enterDir(parent, name, fullPath, chain) {
1489
1759
  const depth = this.dirs[parent].depth + 1;
1490
- 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
+ }
1491
1769
  const child = this.#addDir(name, parent, depth);
1492
1770
  this.#limiter.run(() => this.#scanDir(child, fullPath, chain));
1493
1771
  }
@@ -1513,6 +1791,11 @@ var Scanner = class {
1513
1791
  isSymlink = true;
1514
1792
  if (!this.#options.followSymlinks) {
1515
1793
  this.counters.symlinks++;
1794
+ this.#options.onSkip?.({
1795
+ kind: "symlink",
1796
+ dir: dirIndex,
1797
+ name
1798
+ });
1516
1799
  return;
1517
1800
  }
1518
1801
  stats = await stat(fullPath);
@@ -1533,6 +1816,13 @@ var Scanner = class {
1533
1816
  const rel = this.relativePath(dirIndex, name);
1534
1817
  if (excluder.isExcluded(rel, name, true, chain)) {
1535
1818
  this.counters.excluded++;
1819
+ this.#options.onSkip?.({
1820
+ kind: "excluded",
1821
+ dir: dirIndex,
1822
+ name,
1823
+ isDirectory: true,
1824
+ chain
1825
+ });
1536
1826
  return;
1537
1827
  }
1538
1828
  }
@@ -1557,6 +1847,12 @@ var Scanner = class {
1557
1847
  const mtime = stats.mtimeMs;
1558
1848
  if (size < o.minSize || size > o.maxSize || mtime < o.modifiedAfter || mtime > o.modifiedBefore) {
1559
1849
  this.counters.filtered++;
1850
+ o.onSkip?.({
1851
+ kind: "filtered",
1852
+ dir: dirIndex,
1853
+ name,
1854
+ stats
1855
+ });
1560
1856
  return;
1561
1857
  }
1562
1858
  }
@@ -1620,8 +1916,7 @@ const ERROR_DESCRIPTIONS = {
1620
1916
  EIO: "input/output error",
1621
1917
  EBUSY: "resource busy"
1622
1918
  };
1623
- //#endregion
1624
- //#region src/core/options.ts
1919
+ // src/core/options.ts
1625
1920
  /** Default number of concurrent filesystem operations. */
1626
1921
  const DEFAULT_CONCURRENCY = 32;
1627
1922
  /** Validates the root and turns user-facing settings into scanner options. */
@@ -1717,8 +2012,7 @@ async function listDirectories(path, settings = {}) {
1717
2012
  await scanner.run();
1718
2013
  return scanner.dirs.map((_, index) => scanner.relativePath(index));
1719
2014
  }
1720
- //#endregion
1721
- //#region src/core/top.ts
2015
+ // src/core/top.ts
1722
2016
  /**
1723
2017
  * Keeps the `limit` largest items seen, in O(limit) memory and O(log limit)
1724
2018
  * time per insertion, using a binary min-heap keyed by `score`.
@@ -1789,8 +2083,7 @@ var TopK = class {
1789
2083
  }
1790
2084
  }
1791
2085
  };
1792
- //#endregion
1793
- //#region src/core/analyze.ts
2086
+ // src/core/analyze.ts
1794
2087
  /** Default size for "large file" detection: 100 MiB. */
1795
2088
  const DEFAULT_LARGE_FILE_THRESHOLD = 104857600;
1796
2089
  /** Default age for stale-file detection. */
@@ -2207,8 +2500,7 @@ function createProgressReporter(report, interval, snapshot) {
2207
2500
  }
2208
2501
  };
2209
2502
  }
2210
- //#endregion
2211
- //#region src/core/compare.ts
2503
+ // src/core/compare.ts
2212
2504
  const PASS_THROUGH_SHARE = .95;
2213
2505
  /** Records every file by its root-relative path, for diffing. */
2214
2506
  var FileIndex = class {
@@ -2425,8 +2717,640 @@ function directoryDeltas(leftScanner, leftIndex, rightScanner, rightIndex, top)
2425
2717
  deltas.sort((x, y) => Math.abs(y.delta) - Math.abs(x.delta) || comparePaths(x.path, y.path));
2426
2718
  return deltas.slice(0, top);
2427
2719
  }
2428
- //#endregion
2429
- //#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
2430
3354
  const SIZE_HINT = "Bytes, or a size such as \"512k\", \"25MiB\", or \"1GB\".";
2431
3355
  const TIME_HINT = "An age such as \"30d\", \"6mo\", or \"1y\", or a date (YYYY-MM-DD).";
2432
3356
  /** Single source of truth for config validation, docs, and `schema.json`. */
@@ -2706,8 +3630,7 @@ function jsonType(type) {
2706
3630
  case "enum": return { enum: [...type.values] };
2707
3631
  }
2708
3632
  }
2709
- //#endregion
2710
- //#region src/config/load.ts
3633
+ // src/config/load.ts
2711
3634
  /** File names recognized during discovery, in priority order. */
2712
3635
  const CONFIG_FILE_NAMES = [".dir-analyzer.json", "dir-analyzer.config.json"];
2713
3636
  /** Finds the nearest config file at or above `startDir`. */
@@ -2754,8 +3677,7 @@ async function loadConfig(options) {
2754
3677
  warnings: warnings.map((w) => `${path}: ${w}`)
2755
3678
  };
2756
3679
  }
2757
- //#endregion
2758
- //#region src/format/style.ts
3680
+ // src/format/style.ts
2759
3681
  function supportsColor(stream, env = process.env) {
2760
3682
  const force = env["FORCE_COLOR"];
2761
3683
  if (force !== void 0) return force !== "0" && force !== "false";
@@ -2784,8 +3706,7 @@ const ANSI_PATTERN = /\u001B\[[0-9;]*m/g;
2784
3706
  function stripAnsi(text) {
2785
3707
  return text.replace(ANSI_PATTERN, "");
2786
3708
  }
2787
- //#endregion
2788
- //#region src/format/text.ts
3709
+ // src/format/text.ts
2789
3710
  /** Visible width of a string, ignoring ANSI escapes. */
2790
3711
  function visibleWidth(text) {
2791
3712
  return stripAnsi(text).length;
@@ -2807,6 +3728,52 @@ function truncateMiddle(text, max) {
2807
3728
  const keepStart = max - 1 - keepEnd;
2808
3729
  return `${text.slice(0, keepStart)}…${text.slice(text.length - keepEnd)}`;
2809
3730
  }
3731
+ /** C0 and C1 controls, DEL, Unicode line separators, and bidirectional overrides. */
3732
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
3733
+ /** The same, without tab, CR, and LF, which CSV can carry inside a quoted cell. */
3734
+ const CONTROL_EXCEPT_WHITESPACE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
3735
+ /** What `JSON.stringify` leaves raw but a terminal could still act on. */
3736
+ const JSON_UNSAFE = /[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
3737
+ const NAMED_ESCAPES = {
3738
+ "\n": "\\n",
3739
+ "\r": "\\r",
3740
+ " ": "\\t"
3741
+ };
3742
+ function hexEscape(c) {
3743
+ const code = c.charCodeAt(0);
3744
+ return code <= 255 ? `\\x${code.toString(16).padStart(2, "0")}` : `\\u${code.toString(16).padStart(4, "0")}`;
3745
+ }
3746
+ function controlEscape(c) {
3747
+ return NAMED_ESCAPES[c] ?? hexEscape(c);
3748
+ }
3749
+ /**
3750
+ * Makes untrusted text, such as a file name, safe to print: control characters
3751
+ * become visible escapes (`\x1b`, `\n`), so a name cannot drive the terminal,
3752
+ * forge report lines, or disguise itself. Backslashes are left alone because
3753
+ * Windows paths are full of them, so use JSON output for the exact name.
3754
+ */
3755
+ function escapeControl(text) {
3756
+ return text.replace(CONTROL, controlEscape);
3757
+ }
3758
+ /** {@link escapeControl} for cells of a format that can quote tabs and line breaks. */
3759
+ function escapeControlKeepingWhitespace(text) {
3760
+ return text.replace(CONTROL_EXCEPT_WHITESPACE, controlEscape);
3761
+ }
3762
+ /** {@link escapeControl} for a multi-line message: its own line breaks are kept. */
3763
+ function escapeControlInLines(text) {
3764
+ return text.split("\n").map(escapeControl).join("\n");
3765
+ }
3766
+ /** Fits a name into `max` columns. Escapes first, so an escape is counted and never cut raw. */
3767
+ function fitPath(text, max) {
3768
+ return truncateMiddle(escapeControl(text), max);
3769
+ }
3770
+ /**
3771
+ * `JSON.stringify` that also writes terminal-sensitive characters as `\uXXXX`.
3772
+ * Parsing the output gives back exactly the same strings.
3773
+ */
3774
+ function stringifyJson(value, indent) {
3775
+ return JSON.stringify(value, null, indent).replace(JSON_UNSAFE, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
3776
+ }
2810
3777
  const PARTIAL_BLOCKS = [
2811
3778
  "",
2812
3779
  "▏",
@@ -2837,8 +3804,7 @@ function formatPercent(part, total) {
2837
3804
  function plural(count, singular, pluralForm = `${singular}s`) {
2838
3805
  return `${formatCount(count)} ${count === 1 ? singular : pluralForm}`;
2839
3806
  }
2840
- //#endregion
2841
- //#region src/reporters/pretty.ts
3807
+ // src/reporters/pretty.ts
2842
3808
  const CATEGORY_LABELS = {
2843
3809
  code: "Code",
2844
3810
  documents: "Documents",
@@ -2889,7 +3855,7 @@ var Renderer = class {
2889
3855
  for (const item of shown) {
2890
3856
  const suffix = extra ? ` ${this.s.dim(extra(item))}` : "";
2891
3857
  const used = 15 + (extra ? extra(item).length + 2 : 0);
2892
- this.line(` ${this.size(item.bytes)} ${truncateMiddle(item.path, this.room(used))}${suffix}`);
3858
+ this.line(` ${this.size(item.bytes)} ${fitPath(item.path, this.room(used))}${suffix}`);
2893
3859
  }
2894
3860
  this.more(shown.length, total);
2895
3861
  }
@@ -2900,7 +3866,7 @@ function renderAnalysis(result, options = {}) {
2900
3866
  const { s } = r;
2901
3867
  const now = options.now ?? Date.now();
2902
3868
  const sum = result.summary;
2903
- r.line(` ${s.bold(s.blue("dat"))} ${s.bold(truncateMiddle(result.root, r.room(20)))} ${s.dim(formatElapsed(result.durationMs))}`);
3869
+ r.line(` ${s.bold(s.blue("dat"))} ${s.bold(fitPath(result.root, r.room(20)))} ${s.dim(formatElapsed(result.durationMs))}`);
2904
3870
  r.line("");
2905
3871
  const row = (label, value) => r.line(` ${padEndVisible(s.dim(label), 10)}${value}`);
2906
3872
  const disk = sum.diskBytes !== sum.bytes ? ` ${s.dim(`(${r.bytes(sum.diskBytes)} on disk)`)}` : "";
@@ -2923,7 +3889,7 @@ function renderAnalysis(result, options = {}) {
2923
3889
  r.heading("Largest folders");
2924
3890
  for (const dir of result.largestDirectories.slice(0, r.limit)) {
2925
3891
  const files = plural(dir.files, "file");
2926
- r.line(` ${r.size(dir.bytes)} ${truncateMiddle(`${dir.path}/`, r.room(17 + files.length))} ${s.dim(files)}`);
3892
+ r.line(` ${r.size(dir.bytes)} ${fitPath(`${dir.path}/`, r.room(17 + files.length))} ${s.dim(files)}`);
2927
3893
  }
2928
3894
  }
2929
3895
  if (result.largestFiles.length > 0) {
@@ -2938,13 +3904,13 @@ function renderAnalysis(result, options = {}) {
2938
3904
  if (result.duplicates) renderDuplicates(r, result.duplicates);
2939
3905
  if (result.emptyFiles) {
2940
3906
  r.heading("Empty files", result.emptyFiles.count > 0 ? plural(result.emptyFiles.count, "file") : "none");
2941
- for (const file of result.emptyFiles.items.slice(0, r.limit)) r.line(` ${truncateMiddle(file.path, r.room(3))}`);
3907
+ for (const file of result.emptyFiles.items.slice(0, r.limit)) r.line(` ${fitPath(file.path, r.room(3))}`);
2942
3908
  r.more(Math.min(r.limit, result.emptyFiles.items.length), result.emptyFiles.count);
2943
3909
  }
2944
3910
  if (result.emptyDirectories) {
2945
3911
  const ed = result.emptyDirectories;
2946
3912
  r.heading("Empty folders", ed.count > 0 ? plural(ed.count, "folder") : "none");
2947
- for (const dir of ed.items.slice(0, r.limit)) r.line(` ${truncateMiddle(`${dir}/`, r.room(3))}`);
3913
+ for (const dir of ed.items.slice(0, r.limit)) r.line(` ${fitPath(`${dir}/`, r.room(3))}`);
2948
3914
  r.more(Math.min(r.limit, ed.items.length), ed.count);
2949
3915
  }
2950
3916
  if (result.staleFiles) {
@@ -2960,8 +3926,9 @@ function renderAnalysis(result, options = {}) {
2960
3926
  r.heading("Unreadable", plural(sum.errors, "path"));
2961
3927
  const shown = result.errors.slice(0, 5);
2962
3928
  for (const error of shown) {
2963
- const used = 13 + error.message.length;
2964
- r.line(` ${s.yellow(padEndVisible(error.code, 8))}${truncateMiddle(error.path, r.room(used))} ${s.dim(error.message)}`);
3929
+ const message = escapeControl(error.message);
3930
+ const used = 13 + message.length;
3931
+ r.line(` ${s.yellow(padEndVisible(error.code, 8))}${fitPath(error.path, r.room(used))} ${s.dim(message)}`);
2965
3932
  }
2966
3933
  r.more(shown.length, sum.errors);
2967
3934
  }
@@ -2971,7 +3938,7 @@ function renderAnalysis(result, options = {}) {
2971
3938
  for (const budget of result.budgets) {
2972
3939
  const actual = formatBudgetActual(budget, r.units);
2973
3940
  const mark = budget.passed ? s.green("✔") : s.red("✘");
2974
- r.line(` ${mark} ${padEndVisible(budget.rule, 24)} ${s.dim("actual")} ${budget.passed ? actual : s.red(actual)}`);
3941
+ r.line(` ${mark} ${padEndVisible(escapeControl(budget.rule), 24)} ${s.dim("actual")} ${budget.passed ? actual : s.red(actual)}`);
2975
3942
  }
2976
3943
  }
2977
3944
  r.line("");
@@ -2992,7 +3959,7 @@ function renderExtensions(r, result) {
2992
3959
  const total = result.summary.bytes;
2993
3960
  r.heading("Extensions", plural(result.extensions.length, "distinct extension"));
2994
3961
  const shown = result.extensions.slice(0, r.limit);
2995
- for (const ext of shown) r.line(` ${padEndVisible(ext.extension || s.dim("(none)"), 12)} ${r.size(ext.bytes)} ${padStartVisible(formatPercent(ext.bytes, total), 5)} ${s.dim(plural(ext.files, "file"))}`);
3962
+ for (const ext of shown) r.line(` ${padEndVisible(escapeControl(ext.extension) || s.dim("(none)"), 12)} ${r.size(ext.bytes)} ${padStartVisible(formatPercent(ext.bytes, total), 5)} ${s.dim(plural(ext.files, "file"))}`);
2996
3963
  r.more(shown.length, result.extensions.length);
2997
3964
  }
2998
3965
  function renderDuplicates(r, duplicates) {
@@ -3006,7 +3973,7 @@ function renderDuplicates(r, duplicates) {
3006
3973
  for (const group of shown) {
3007
3974
  r.line(` ${r.size(group.wastedBytes)} ${s.dim(`${group.files.length} × ${r.bytes(group.bytes)}`)}`);
3008
3975
  const files = group.files.slice(0, 5);
3009
- for (const file of files) r.line(` ${" ".repeat(SIZE_WIDTH)} ${truncateMiddle(file, r.room(15))}`);
3976
+ for (const file of files) r.line(` ${" ".repeat(SIZE_WIDTH)} ${fitPath(file, r.room(15))}`);
3010
3977
  if (group.files.length > files.length) r.line(` ${" ".repeat(SIZE_WIDTH)} ${s.dim(`… ${group.files.length - files.length} more copies`)}`);
3011
3978
  }
3012
3979
  r.more(shown.length, duplicates.count, "more groups");
@@ -3016,7 +3983,7 @@ function renderTree(r, root) {
3016
3983
  const walk = (node, prefix, isLast, isRoot) => {
3017
3984
  const connector = isRoot ? "" : isLast ? "└─ " : "├─ ";
3018
3985
  const used = 15 + prefix.length + connector.length;
3019
- const name = truncateMiddle(node.type === "directory" && !isRoot ? `${node.name}/` : node.name, Math.max(12, r.width - used));
3986
+ const name = fitPath(node.type === "directory" && !isRoot ? `${node.name}/` : node.name, Math.max(12, r.width - used));
3020
3987
  r.line(` ${r.size(node.bytes)} ${s.dim(prefix + connector)}${node.type === "directory" ? s.bold(name) : name}`);
3021
3988
  const childPrefix = isRoot ? "" : prefix + (isLast ? " " : "│ ");
3022
3989
  const children = node.children ?? [];
@@ -3038,8 +4005,8 @@ function renderComparison(result, options = {}) {
3038
4005
  };
3039
4006
  r.line(` ${s.bold(s.blue("dat compare"))} ${s.dim(formatElapsed(result.durationMs))}`);
3040
4007
  r.line("");
3041
- r.line(` ${s.dim("left ")} ${truncateMiddle(result.left.root, r.room(12))}`);
3042
- r.line(` ${s.dim("right")} ${truncateMiddle(result.right.root, r.room(12))}`);
4008
+ r.line(` ${s.dim("left ")} ${fitPath(result.left.root, r.room(12))}`);
4009
+ r.line(` ${s.dim("right")} ${fitPath(result.right.root, r.room(12))}`);
3043
4010
  const col = (text) => padStartVisible(text, 12);
3044
4011
  r.heading("Overview");
3045
4012
  r.line(` ${padEndVisible("", 10)}${col(s.dim("left"))}${col(s.dim("right"))} ${s.dim("change")}`);
@@ -3061,7 +4028,7 @@ function renderComparison(result, options = {}) {
3061
4028
  const fileSection = (title, list, mark) => {
3062
4029
  if (list.count === 0) return;
3063
4030
  r.heading(title, `${plural(list.count, "file")} · ${r.bytes(list.bytes)}`);
3064
- for (const f of list.items.slice(0, r.limit)) r.line(` ${mark} ${r.size(f.bytes)} ${truncateMiddle(f.path, r.room(17))}`);
4031
+ for (const f of list.items.slice(0, r.limit)) r.line(` ${mark} ${r.size(f.bytes)} ${fitPath(f.path, r.room(17))}`);
3065
4032
  r.more(Math.min(r.limit, list.items.length), list.count);
3066
4033
  };
3067
4034
  fileSection("Added", result.added, s.green("+"));
@@ -3070,13 +4037,13 @@ function renderComparison(result, options = {}) {
3070
4037
  r.heading("Changed", `${plural(result.changed.count, "file")} · ${result.changed.delta > 0 ? "+" : ""}${formatBytes(result.changed.delta, r.units)} net`);
3071
4038
  for (const c of result.changed.items.slice(0, r.limit)) {
3072
4039
  const detail = c.delta === 0 ? "content" : `${r.bytes(c.leftBytes)} → ${r.bytes(c.rightBytes)}`;
3073
- r.line(` ${s.yellow("~")} ${padStartVisible(signed(c.delta), SIZE_WIDTH)} ${truncateMiddle(c.path, r.room(19 + detail.length))} ${s.dim(detail)}`);
4040
+ r.line(` ${s.yellow("~")} ${padStartVisible(signed(c.delta), SIZE_WIDTH)} ${fitPath(c.path, r.room(19 + detail.length))} ${s.dim(detail)}`);
3074
4041
  }
3075
4042
  r.more(Math.min(r.limit, result.changed.items.length), result.changed.count);
3076
4043
  }
3077
4044
  if (result.directories.length > 0) {
3078
4045
  r.heading("Folders that changed most");
3079
- for (const d of result.directories.slice(0, r.limit)) r.line(` ${padStartVisible(signed(d.delta), 12)} ${truncateMiddle(`${d.path}/`, r.room(17))}`);
4046
+ for (const d of result.directories.slice(0, r.limit)) r.line(` ${padStartVisible(signed(d.delta), 12)} ${fitPath(`${d.path}/`, r.room(17))}`);
3080
4047
  }
3081
4048
  r.line("");
3082
4049
  const identical = result.added.count + result.removed.count + result.changed.count === 0;
@@ -3084,12 +4051,17 @@ function renderComparison(result, options = {}) {
3084
4051
  r.line("");
3085
4052
  return r.lines.join("\n");
3086
4053
  }
3087
- //#endregion
3088
- //#region src/reporters/markdown.ts
3089
- /** Inline code that is safe inside a GitHub table cell. */
4054
+ // src/reporters/markdown.ts
4055
+ /**
4056
+ * Inline code that is safe inside a GitHub table cell. The fence is longer than
4057
+ * any run of backticks in the text, so a file name cannot close it early and
4058
+ * have the rest of its name rendered as Markdown.
4059
+ */
3090
4060
  function mdCode(text) {
3091
- const fence = text.includes("`") ? "``" : "`";
3092
- return `${fence}${(fence === "``" ? ` ${text} ` : text).replaceAll("|", "\\|")}${fence}`;
4061
+ const safe = escapeControl(text).replaceAll("|", "\\|");
4062
+ const longestRun = Math.max(0, ...(safe.match(/`+/g) ?? []).map((run) => run.length));
4063
+ const fence = "`".repeat(longestRun + 1);
4064
+ return longestRun > 0 ? `${fence} ${safe} ${fence}` : `${fence}${safe}${fence}`;
3093
4065
  }
3094
4066
  function table(header, rows, align) {
3095
4067
  const sep = header.map((_, i) => align?.[i] === "r" ? "---:" : "---");
@@ -3305,17 +4277,17 @@ function renderComparisonMarkdown(result, options = {}) {
3305
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>`, "");
3306
4278
  return out.join("\n");
3307
4279
  }
3308
- //#endregion
3309
- //#region src/reporters/csv.ts
4280
+ // src/reporters/csv.ts
3310
4281
  /**
3311
4282
  * Quotes a CSV cell when needed (RFC 4180) and neutralizes spreadsheet
3312
4283
  * formula injection: text starting with `=`, `+`, `-`, `@`, tab, or carriage
3313
- * return is prefixed with an apostrophe so it is never evaluated.
4284
+ * return is prefixed with an apostrophe so it is never evaluated. Other control
4285
+ * characters are escaped because CSV is often printed; JSON keeps exact names.
3314
4286
  */
3315
4287
  function csvCell(value) {
3316
4288
  if (value === null || value === void 0) return "";
3317
4289
  if (typeof value === "number") return String(value);
3318
- let text = value;
4290
+ let text = escapeControlKeepingWhitespace(value);
3319
4291
  if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`;
3320
4292
  return /[",\r\n]/.test(text) ? `"${text.replaceAll("\"", "\"\"")}"` : text;
3321
4293
  }
@@ -3461,8 +4433,7 @@ function renderComparisonCsv(result) {
3461
4433
  "delta"
3462
4434
  ], rows);
3463
4435
  }
3464
- //#endregion
3465
- //#region src/reporters/html.ts
4436
+ // src/reporters/html.ts
3466
4437
  /** Duplicate groups listed in the HTML report; the full list is in JSON and CSV. */
3467
4438
  const DUPLICATE_GROUPS_SHOWN = 100;
3468
4439
  const CATEGORY_COLORS = {
@@ -3676,5 +4647,142 @@ document.getElementById('filter').addEventListener('input', function (event) {
3676
4647
  });
3677
4648
  });
3678
4649
  `;
3679
- //#endregion
3680
- export { parseBudget as A, errorMessage as B, DEFAULT_EXCLUDES as C, BUDGET_METRICS as D, extensionOf as E, parseDuration as F, parsePointInTime as I, AbortError as L, parseSize as M, CATEGORIES as N, evaluateBudgets as O, VERSION as P, DatError as R, joinRelative as S, classify as T, DEFAULT_LARGE_FILE_THRESHOLD as _, renderComparisonMarkdown as a, DEFAULT_CONCURRENCY as b, formatCount as c, CONFIG_FILE_NAMES as d, findConfigFile as f, compare as g, validateConfig as h, renderAnalysisMarkdown as i, formatBytes as j, formatBudgetActual as k, createStyle as l, buildJsonSchema as m, renderAnalysisCsv as n, renderAnalysis as o, loadConfig as p, renderComparisonCsv as r, renderComparison as s, renderAnalysisHtml as t, supportsColor as u, DEFAULT_STALE_AGE as v, Excluder as w, listDirectories as x, analyze as y, errorCode 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 };