dir-analysis-tool 3.1.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -52,6 +52,7 @@ npx dir-analysis-tool
52
52
  - [Output formats](#output-formats)
53
53
  - [Configuration](#configuration)
54
54
  - [Library API](#library-api)
55
+ - [Agent skill](#agent-skill)
55
56
  - [How it works](#how-it-works)
56
57
  - [Exit codes](#exit-codes)
57
58
  - [Migrating from v2](#migrating-from-v2)
@@ -425,10 +426,20 @@ await writeFile('report.md', renderAnalysisMarkdown(result));
425
426
 
426
427
  Sizes and times accept the same strings as the CLI (`minSize: '10MB'`, `modifiedAfter: '30d'`), as well as numbers and `Date`s.
427
428
 
429
+ ## Agent skill
430
+
431
+ An official [Agent Skill](https://agentskills.io) lets coding agents such as Claude Code, Codex, Gemini CLI, and OpenCode use `dat` to explain what takes up space in a repository, find duplicate assets, and check size budgets. The agents run the CLI and read its JSON output instead of guessing.
432
+
433
+ ```bash
434
+ npx skills add KhaledSaeed18/dir-analysis-tool --skill dir-analysis-tool
435
+ ```
436
+
437
+ Then ask in your own words, for example "why is this repo so big?" or "fail CI if `dist` goes over 2 MB". See [skills/README.md](skills/README.md) for other ways to install it, tested agents, and the evals.
438
+
428
439
  ## How it works
429
440
 
430
441
  - **Scanning.** Directories are read with `readdir({ withFileTypes })`, so they never need a `stat`, and each regular file is `lstat`ed once. All filesystem calls go through one concurrency limiter (32 operations in flight by default), so no tree, however wide, can exhaust file handles. Work is scheduled depth-first to keep the queue small.
431
- - **Patterns.** Exclude patterns and `.gitignore` files are compiled by a built-in matcher: consecutive rules become a few regular expressions, and plain names and `*.ext` rules are resolved with hash lookups, reducing pattern-matching overhead without caching results per path.
442
+ - **Patterns.** Exclude patterns and `.gitignore` files are compiled by a built-in matcher: consecutive rules become a few regular expressions, and plain names and `*.ext` rules are resolved with hash lookups, reducing pattern-matching overhead without caching results per path. Rules with several wildcards use a matcher whose time grows linearly with the path length, so an unusual `.gitignore` cannot stall a scan.
432
443
  - **Memory.** Totals, type and extension statistics, folder sizes, and the top-N lists are computed while scanning; the lists use bounded heaps. Reports you opt into keep only what they match. Duplicate detection keeps one small record per file that shares its size with another.
433
444
  - **Largest folders.** Folders are ranked by the total size below them. A folder whose size comes almost entirely (95% or more) from one subfolder is folded into that subfolder, so the list points to where the data actually lives instead of repeating every parent.
434
445
  - **Duplicates,** in stages so most files are never read in full:
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { A as parseBudget, B as errorMessage, I as parsePointInTime, L as AbortError, M as parseSize, P as VERSION, R as DatError, S as joinRelative, a as renderComparisonMarkdown, c as formatCount, g as compare, i as renderAnalysisMarkdown, j as formatBytes, k as formatBudgetActual, l as createStyle, n as renderAnalysisCsv, o as renderAnalysis, p as loadConfig, r as renderComparisonCsv, s as renderComparison, t as renderAnalysisHtml, u as supportsColor, w as Excluder, x as listDirectories, y as analyze, z as errorCode } from "./shared-htkguqJG.js";
2
+ import { B as AbortError, D as Excluder, F as parseSize, H as errorCode, L as VERSION, M as formatBudgetActual, N as parseBudget, P as formatBytes, S as analyze, T as joinRelative, U as errorMessage, V as DatError, a as renderComparisonMarkdown, c as escapeControl, d as stringifyJson, f as createStyle, g as loadConfig, i as renderAnalysisMarkdown, l as escapeControlInLines, n as renderAnalysisCsv, o as renderAnalysis, p as supportsColor, r as renderComparisonCsv, s as renderComparison, t as renderAnalysisHtml, u as formatCount, w as listDirectories, y as compare, z as parsePointInTime } from "./shared-30qR-AM1.js";
3
3
  import { existsSync, watch } from "node:fs";
4
4
  import { mkdir, writeFile } from "node:fs/promises";
5
5
  import { dirname, join, relative, resolve, sep } from "node:path";
@@ -658,7 +658,7 @@ const FORMATS = [
658
658
  function renderAnalysisAs(format, result, options) {
659
659
  switch (format) {
660
660
  case "pretty": return renderAnalysis(result, options);
661
- case "json": return `${JSON.stringify(result, null, 2)}\n`;
661
+ case "json": return `${stringifyJson(result, 2)}\n`;
662
662
  case "markdown": return renderAnalysisMarkdown(result, options);
663
663
  case "csv": return renderAnalysisCsv(result);
664
664
  case "html": return renderAnalysisHtml(result, { units: options.units });
@@ -667,7 +667,7 @@ function renderAnalysisAs(format, result, options) {
667
667
  function renderComparisonAs(format, result, options) {
668
668
  switch (format) {
669
669
  case "pretty": return renderComparison(result, options);
670
- case "json": return `${JSON.stringify(result, null, 2)}\n`;
670
+ case "json": return `${stringifyJson(result, 2)}\n`;
671
671
  case "markdown": return renderComparisonMarkdown(result, options);
672
672
  case "csv": return renderComparisonCsv(result);
673
673
  case "html": throw new RangeError("HTML output is not available for compare; use pretty, json, markdown, or csv.");
@@ -940,7 +940,7 @@ function reportBudgets(ctx, result, display) {
940
940
  }
941
941
  function displayPath(ctx, file) {
942
942
  const rel = relative(ctx.io.cwd, file);
943
- return rel && !rel.startsWith("..") ? rel : file;
943
+ return escapeControl(rel && !rel.startsWith("..") ? rel : file);
944
944
  }
945
945
  /** Items printed per list: the --top value, or 10 when the top lists are turned off. */
946
946
  function listLimit(top) {
@@ -994,7 +994,7 @@ function registerCompare(program, ctx) {
994
994
  });
995
995
  if (display.output) {
996
996
  const file = await ctx.writeFile(display.output, text);
997
- ctx.info(`${ctx.err.green("✔")} Comparison written to ${file}`, display.quiet);
997
+ ctx.info(`${ctx.err.green("✔")} Comparison written to ${escapeControl(file)}`, display.quiet);
998
998
  } else await ctx.stdout(text.endsWith("\n") ? text : `${text}\n`);
999
999
  });
1000
1000
  }
@@ -1151,7 +1151,7 @@ function registerInit(program, ctx) {
1151
1151
  $schema: SCHEMA_URL,
1152
1152
  ...config
1153
1153
  }, null, 4)}\n`);
1154
- ctx.info(`${ctx.err.green("✔")} Wrote ${file}`, false);
1154
+ ctx.info(`${ctx.err.green("✔")} Wrote ${escapeControl(file)}`, false);
1155
1155
  });
1156
1156
  }
1157
1157
  /** Interactive questions, asked on the CLI's own stdin/stdout. */
@@ -1348,7 +1348,7 @@ function registerWatch(program, ctx) {
1348
1348
  });
1349
1349
  const render = async (result) => {
1350
1350
  if (display.format === "json") {
1351
- await ctx.stdout(`${JSON.stringify(result)}\n`);
1351
+ await ctx.stdout(`${stringifyJson(result)}\n`);
1352
1352
  return;
1353
1353
  }
1354
1354
  if (clear) await ctx.stdout(CLEAR_SCREEN);
@@ -1358,7 +1358,7 @@ function registerWatch(program, ctx) {
1358
1358
  csv: void 0
1359
1359
  }, listLimit(options.top));
1360
1360
  const status = previous ? describeChange(previous, result, display.units) : "initial scan";
1361
- ctx.info(ctx.err.dim(`watching ${target} · ${status} · ${(/* @__PURE__ */ new Date()).toLocaleTimeString()} · Ctrl+C to stop`), display.quiet);
1361
+ ctx.info(ctx.err.dim(`watching ${escapeControl(target)} · ${status} · ${(/* @__PURE__ */ new Date()).toLocaleTimeString()} · Ctrl+C to stop`), display.quiet);
1362
1362
  };
1363
1363
  let watcher = null;
1364
1364
  const run = async () => {
@@ -1382,7 +1382,7 @@ function registerWatch(program, ctx) {
1382
1382
  }
1383
1383
  } catch (error) {
1384
1384
  if (error instanceof AbortError) return;
1385
- ctx.io.stderr.write(`${ctx.err.red("error")} ${errorMessage(error)}\n`);
1385
+ ctx.io.stderr.write(`${ctx.err.red("error")} ${escapeControlInLines(errorMessage(error))}\n`);
1386
1386
  } finally {
1387
1387
  running = false;
1388
1388
  }
@@ -1406,7 +1406,7 @@ function registerWatch(program, ctx) {
1406
1406
  isIgnored: (rel) => excluder.isPathExcluded(rel),
1407
1407
  onChange: schedule,
1408
1408
  onError: (error) => {
1409
- ctx.warn(`file watching failed (${error.message}); falling back to polling every 5 seconds`);
1409
+ ctx.warn(`file watching failed (${escapeControl(error.message)}); falling back to polling every 5 seconds`);
1410
1410
  watcher?.close();
1411
1411
  watcher = null;
1412
1412
  if (!poller) startPolling(5);
@@ -1461,7 +1461,7 @@ var Context = class {
1461
1461
  if (!quiet) this.io.stderr.write(`${message}\n`);
1462
1462
  }
1463
1463
  warn(message) {
1464
- this.io.stderr.write(`${this.err.yellow("warning")} ${message}\n`);
1464
+ this.io.stderr.write(`${this.err.yellow("warning")} ${escapeControlInLines(message)}\n`);
1465
1465
  }
1466
1466
  async loadConfig(cli, searchFrom) {
1467
1467
  if (cli["config"] === false) return {
@@ -1494,7 +1494,7 @@ function createProgram(ctx) {
1494
1494
  const program = new Command("dat").description("Fast, zero-dependency directory analysis for your terminal and CI.").version(VERSION, "-v, --version", "print the version").helpOption("-h, --help", "show help").helpCommand("help [command]", "show help for a command").configureOutput({
1495
1495
  writeOut: (text) => io.stdout.write(text),
1496
1496
  writeErr: (text) => io.stderr.write(text),
1497
- outputError: (text, write) => write(ctx.err.red(text))
1497
+ outputError: (text, write) => write(ctx.err.red(escapeControlInLines(text)))
1498
1498
  }).showHelpAfterError("(run \"dat --help\" to see all options)").showSuggestionAfterError(true).exitOverride();
1499
1499
  registerAnalyze(program, ctx);
1500
1500
  registerCompare(program, ctx);
@@ -1528,13 +1528,13 @@ function handleError(error, ctx) {
1528
1528
  return ExitCode.Interrupted;
1529
1529
  }
1530
1530
  if (error instanceof DatError) {
1531
- io.stderr.write(`${err.red("error")} ${error.message}\n`);
1532
- if (error.hint) io.stderr.write(`${err.dim(error.hint)}\n`);
1531
+ io.stderr.write(`${err.red("error")} ${escapeControlInLines(error.message)}\n`);
1532
+ if (error.hint) io.stderr.write(`${err.dim(escapeControlInLines(error.hint))}\n`);
1533
1533
  return ExitCode.Error;
1534
1534
  }
1535
- const message = errorMessage(error);
1535
+ const message = escapeControlInLines(errorMessage(error));
1536
1536
  io.stderr.write(`${err.red("error")} ${message}\n`);
1537
- if (io.env["DAT_DEBUG"] && error instanceof Error && error.stack) io.stderr.write(`${err.dim(error.stack)}\n`);
1537
+ if (io.env["DAT_DEBUG"] && error instanceof Error && error.stack) io.stderr.write(`${err.dim(escapeControlInLines(error.stack))}\n`);
1538
1538
  else io.stderr.write(`${err.dim("Set DAT_DEBUG=1 for a stack trace. Please report unexpected errors: https://github.com/KhaledSaeed18/dir-analysis-tool/issues")}\n`);
1539
1539
  return ExitCode.Error;
1540
1540
  }
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export { L as AbortError, D as BUDGET_METRICS, N as CATEGORIES, d as CONFIG_FILE_NAMES, b as DEFAULT_CONCURRENCY, C as DEFAULT_EXCLUDES, _ as DEFAULT_LARGE_FILE_THRESHOLD, v as DEFAULT_STALE_AGE, R as DatError, P as VERSION, y as analyze, m as buildJsonSchema, T as classify, g as compare, l as createStyle, O as evaluateBudgets, E as extensionOf, f as findConfigFile, j as formatBytes, x as listDirectories, p as loadConfig, A as parseBudget, F as parseDuration, I as parsePointInTime, M as parseSize, o as renderAnalysis, n as renderAnalysisCsv, t as renderAnalysisHtml, i as renderAnalysisMarkdown, s as renderComparison, r as renderComparisonCsv, a as renderComparisonMarkdown, h as validateConfig } from "./shared-htkguqJG.js";
1
+ export { B as AbortError, A as BUDGET_METRICS, I as CATEGORIES, m as CONFIG_FILE_NAMES, C as DEFAULT_CONCURRENCY, E as DEFAULT_EXCLUDES, b as DEFAULT_LARGE_FILE_THRESHOLD, x as DEFAULT_STALE_AGE, V as DatError, L as VERSION, S as analyze, _ as buildJsonSchema, O as classify, y as compare, f as createStyle, j as evaluateBudgets, k as extensionOf, h as findConfigFile, P as formatBytes, w as listDirectories, g as loadConfig, N as parseBudget, R as parseDuration, z as parsePointInTime, F as parseSize, o as renderAnalysis, n as renderAnalysisCsv, t as renderAnalysisHtml, i as renderAnalysisMarkdown, s as renderComparison, r as renderComparisonCsv, a as renderComparisonMarkdown, v as validateConfig } from "./shared-30qR-AM1.js";
@@ -928,6 +928,7 @@ var GitignoreMatcher = class GitignoreMatcher {
928
928
  const runs = this.#runs;
929
929
  let name;
930
930
  let folded;
931
+ let foldedPath;
931
932
  for (let i = runs.length - 1; i >= 0; i--) {
932
933
  const run = runs[i];
933
934
  const fast = isDirectory && run.dirFast !== null ? true : run.anyFast !== null;
@@ -941,11 +942,21 @@ var GitignoreMatcher = class GitignoreMatcher {
941
942
  if (run.anyName?.test(name) || isDirectory && run.dirName?.test(name)) return !run.negated;
942
943
  }
943
944
  if (run.anyPath?.test(path) || isDirectory && run.dirPath?.test(path)) return !run.negated;
945
+ if (run.globs !== null) {
946
+ name ??= path.slice(path.lastIndexOf("/") + 1);
947
+ for (const glob of run.globs) {
948
+ if (glob.dirOnly && !isDirectory) continue;
949
+ if (this.#ignoreCase) {
950
+ if (!(glob.nameOnly ? folded ??= name.toLowerCase() : foldedPath ??= path.toLowerCase()).includes(glob.required)) continue;
951
+ } else if (!(glob.nameOnly ? name : path).includes(glob.required)) continue;
952
+ if (glob.matches(glob.nameOnly ? name : path)) return !run.negated;
953
+ }
954
+ }
944
955
  }
945
956
  }
946
957
  /** Compiles the contents of an ignore file (or a list of patterns). */
947
958
  static compile(source, options = {}) {
948
- const lines = typeof source === "string" ? source.split(/\r?\n/) : source;
959
+ const lines = typeof source === "string" ? source.replace(/^\uFEFF/, "").split(EOL) : source;
949
960
  const ignoreCase = options.ignoreCase === true;
950
961
  const flags = ignoreCase ? "i" : "";
951
962
  const runs = [];
@@ -960,9 +971,10 @@ var GitignoreMatcher = class GitignoreMatcher {
960
971
  anyName: regex(parts.anyName),
961
972
  dirName: regex(parts.dirName),
962
973
  anyPath: regex(parts.anyPath),
963
- dirPath: regex(parts.dirPath)
974
+ dirPath: regex(parts.dirPath),
975
+ globs: parts.globs.length > 0 ? parts.globs : null
964
976
  };
965
- if (run.anyFast || run.dirFast || run.anyName || run.dirName || run.anyPath || run.dirPath) runs.push(run);
977
+ if (run.anyFast || run.dirFast || run.anyName || run.dirName || run.anyPath || run.dirPath || run.globs) runs.push(run);
966
978
  parts = new RunParts();
967
979
  };
968
980
  for (const line of lines) {
@@ -977,7 +989,8 @@ var GitignoreMatcher = class GitignoreMatcher {
977
989
  const value = ignoreCase ? rule.fast.value.toLowerCase() : rule.fast.value;
978
990
  if (rule.fast.kind === "literal") target.literals.add(value);
979
991
  else target.addSuffix(value);
980
- } else if (rule.nameOnly) (rule.dirOnly ? parts.dirName : parts.anyName).push(rule.source);
992
+ } else if (rule.wildcards >= LINEAR_GLOB_WILDCARDS) parts.globs.push(new LinearGlob(rule, ignoreCase));
993
+ else if (rule.nameOnly) (rule.dirOnly ? parts.dirName : parts.anyName).push(rule.source);
981
994
  else (rule.dirOnly ? parts.dirPath : parts.anyPath).push(rule.source);
982
995
  }
983
996
  flush();
@@ -1014,12 +1027,184 @@ var RunParts = class {
1014
1027
  dirName = [];
1015
1028
  anyPath = [];
1016
1029
  dirPath = [];
1030
+ globs = [];
1031
+ };
1032
+ const STAR = { kind: "star" };
1033
+ const ALL = { kind: "all" };
1034
+ const DIRS = { kind: "dirs" };
1035
+ const ANY = { kind: "any" };
1036
+ /** Rules with at least this many wildcards use {@link LinearGlob}. */
1037
+ const LINEAR_GLOB_WILDCARDS = 2;
1038
+ function isWildcard(token) {
1039
+ return token.kind === "star" || token.kind === "all" || token.kind === "dirs";
1040
+ }
1041
+ /** JavaScript's `.` skips line breaks, so these use `[^]`, which matches any character. */
1042
+ function tokenSource(token) {
1043
+ switch (token.kind) {
1044
+ case "char": return escapeRegex(token.char);
1045
+ case "class": return token.source;
1046
+ case "any": return "[^/]";
1047
+ case "star": return "[^/]*";
1048
+ case "all": return "[^]*";
1049
+ case "dirs": return "(?:[^]*/)?";
1050
+ }
1051
+ }
1052
+ const CHAR = 0;
1053
+ const CLASS = 1;
1054
+ const ANY_CHAR = 2;
1055
+ const ANY_RUN = 3;
1056
+ const ALL_RUN = 4;
1057
+ const OPCODES = {
1058
+ char: CHAR,
1059
+ class: CLASS,
1060
+ any: ANY_CHAR,
1061
+ star: ANY_RUN,
1062
+ all: ALL_RUN,
1063
+ dirs: 5
1064
+ };
1065
+ /** The same case folding as a regular expression with the `i` flag. */
1066
+ function foldCase(c) {
1067
+ const upper = c.toUpperCase();
1068
+ if (upper.length !== 1) return c;
1069
+ return c.charCodeAt(0) >= 128 && upper.charCodeAt(0) < 128 ? c : upper;
1070
+ }
1071
+ /** The longest stretch of plain ASCII characters that a glob must match literally. */
1072
+ function longestAsciiRun(tokens) {
1073
+ let longest = "";
1074
+ let run = "";
1075
+ for (const token of tokens) if (token.kind === "char" && token.char.charCodeAt(0) < 128) {
1076
+ run += token.char;
1077
+ if (run.length > longest.length) longest = run;
1078
+ } else run = "";
1079
+ return longest;
1080
+ }
1081
+ /**
1082
+ * Matches a parsed glob by tracking every position it could be at, one input
1083
+ * character at a time. Nothing is ever retried, so the time is bounded by the
1084
+ * length of the path times the length of the pattern, whatever the pattern is.
1085
+ */
1086
+ var LinearGlob = class {
1087
+ dirOnly;
1088
+ nameOnly;
1089
+ /**
1090
+ * Text every match must contain, in lower case when ignoring case. Only ASCII
1091
+ * is used: a regular expression's `i` flag never folds other characters into
1092
+ * ASCII, so lower-casing a path cannot hide or invent an occurrence of it.
1093
+ */
1094
+ required;
1095
+ #ops;
1096
+ #chars;
1097
+ #classes;
1098
+ #accept;
1099
+ #ignoreCase;
1100
+ #current;
1101
+ #next;
1102
+ #nextCount = 0;
1103
+ /** The step at which each position was last added, so it is added only once per step. */
1104
+ #added;
1105
+ /** The same for following a wildcard to the position after it. */
1106
+ #skipped;
1107
+ #step = 0;
1108
+ constructor(rule, ignoreCase) {
1109
+ const { tokens } = rule;
1110
+ this.dirOnly = rule.dirOnly;
1111
+ this.nameOnly = rule.nameOnly;
1112
+ this.#ignoreCase = ignoreCase;
1113
+ const required = longestAsciiRun(tokens);
1114
+ this.required = ignoreCase ? required.toLowerCase() : required;
1115
+ const size = tokens.length + 1;
1116
+ this.#accept = tokens.length;
1117
+ this.#ops = Uint8Array.from(tokens, (token) => OPCODES[token.kind]);
1118
+ this.#chars = tokens.map((token) => {
1119
+ if (token.kind !== "char") return "";
1120
+ return ignoreCase ? foldCase(token.char) : token.char;
1121
+ });
1122
+ this.#classes = tokens.map((token) => token.kind === "class" ? new RegExp(`^${token.source}$`, ignoreCase ? "i" : "") : null);
1123
+ this.#current = new Int32Array(size);
1124
+ this.#next = new Int32Array(size);
1125
+ this.#added = new Float64Array(size);
1126
+ this.#skipped = new Float64Array(size);
1127
+ }
1128
+ matches(text) {
1129
+ const ops = this.#ops;
1130
+ const chars = this.#chars;
1131
+ const accept = this.#accept;
1132
+ this.#nextCount = 0;
1133
+ this.#step++;
1134
+ this.#add(0, true);
1135
+ for (let i = 0; i < text.length; i++) {
1136
+ const count = this.#nextCount;
1137
+ if (count === 0) return false;
1138
+ const current = this.#next;
1139
+ this.#next = this.#current;
1140
+ this.#current = current;
1141
+ this.#nextCount = 0;
1142
+ this.#step++;
1143
+ const c = text[i];
1144
+ const folded = this.#ignoreCase ? foldCase(c) : c;
1145
+ for (let k = 0; k < count; k++) {
1146
+ const position = current[k];
1147
+ if (position === accept) continue;
1148
+ switch (ops[position]) {
1149
+ case CHAR:
1150
+ if (folded === chars[position]) this.#add(position + 1, true);
1151
+ break;
1152
+ case CLASS:
1153
+ if (this.#classes[position].test(c)) this.#add(position + 1, true);
1154
+ break;
1155
+ case ANY_CHAR:
1156
+ if (c !== "/") this.#add(position + 1, true);
1157
+ break;
1158
+ case ANY_RUN:
1159
+ if (c !== "/") this.#add(position, true);
1160
+ break;
1161
+ case ALL_RUN:
1162
+ this.#add(position, true);
1163
+ break;
1164
+ default:
1165
+ this.#add(position, false);
1166
+ if (c === "/") this.#add(position + 1, true);
1167
+ }
1168
+ }
1169
+ }
1170
+ return this.#added[accept] === this.#step;
1171
+ }
1172
+ #add(position, arriving) {
1173
+ const step = this.#step;
1174
+ for (let at = position;; at++) {
1175
+ if (this.#added[at] !== step) {
1176
+ this.#added[at] = step;
1177
+ this.#next[this.#nextCount++] = at;
1178
+ }
1179
+ if (!arriving || at === this.#accept || this.#ops[at] < ANY_RUN) return;
1180
+ if (this.#skipped[at] === step) return;
1181
+ this.#skipped[at] = step;
1182
+ }
1183
+ }
1017
1184
  };
1018
1185
  /** No wildcards, classes, or escapes: the pattern is a literal name (or suffix). */
1019
1186
  const LITERAL = /^[^*?[\\]+$/;
1020
- /** Turns one gitignore line into a regex fragment; `null` for blanks and comments. */
1187
+ /** A line ending; a final CR counts because Git treats the end of a file as a newline. */
1188
+ const EOL = /\r?\n|\r$/;
1189
+ /** Removes unescaped trailing spaces. Tabs are significant, as they are in Git. */
1190
+ function trimTrailingSpaces(line) {
1191
+ let end = line.length;
1192
+ let spaces = -1;
1193
+ for (let i = 0; i < line.length; i++) if (line[i] === " ") {
1194
+ if (spaces === -1) spaces = i;
1195
+ } else {
1196
+ if (line[i] === "\\") i++;
1197
+ spaces = -1;
1198
+ }
1199
+ if (spaces !== -1) end = spaces;
1200
+ return line.slice(0, end);
1201
+ }
1202
+ /**
1203
+ * Turns one gitignore line into a regex fragment. Returns `null` for blanks,
1204
+ * comments, and malformed patterns, which Git treats as never matching.
1205
+ */
1021
1206
  function parseRule(line) {
1022
- let pattern = line.replace(/(?<!\\)\s+$/, "");
1207
+ let pattern = trimTrailingSpaces(line);
1023
1208
  if (pattern === "" || pattern.startsWith("#")) return null;
1024
1209
  let negated = false;
1025
1210
  if (pattern.startsWith("!")) {
@@ -1028,25 +1213,27 @@ function parseRule(line) {
1028
1213
  } else if (pattern.startsWith("\\!") || pattern.startsWith("\\#")) pattern = pattern.slice(1);
1029
1214
  if (pattern === "") return null;
1030
1215
  let dirOnly = false;
1031
- if (pattern.endsWith("/") && !pattern.endsWith("\\/")) {
1216
+ if (pattern.endsWith("/")) {
1032
1217
  dirOnly = true;
1033
- pattern = pattern.replace(/\/+$/, "");
1218
+ pattern = pattern.slice(0, -1);
1034
1219
  if (pattern === "") return null;
1035
1220
  }
1036
1221
  let anchored = false;
1037
1222
  if (pattern.startsWith("/")) {
1038
1223
  anchored = true;
1039
- pattern = pattern.replace(/^\/+/, "");
1224
+ pattern = pattern.slice(1);
1040
1225
  } else if (pattern.includes("/")) anchored = true;
1041
1226
  if (pattern.startsWith("**/")) {
1042
1227
  anchored = false;
1043
1228
  pattern = pattern.replace(/^(\*\*\/)+/, "");
1044
1229
  }
1045
1230
  if (pattern === "") return null;
1046
- const body = globToRegex(pattern);
1231
+ const body = parseGlob(pattern);
1047
1232
  if (body === null) return null;
1048
1233
  const nameOnly = !anchored && !pattern.includes("/") && !pattern.includes("**");
1049
- const source = anchored || nameOnly ? body : `(?:.*/)?${body}`;
1234
+ const tokens = anchored || nameOnly ? body : [DIRS, ...body];
1235
+ const source = tokens.map(tokenSource).join("");
1236
+ const wildcards = tokens.filter(isWildcard).length;
1050
1237
  let fast = null;
1051
1238
  if (nameOnly) {
1052
1239
  if (LITERAL.test(pattern)) fast = {
@@ -1063,77 +1250,107 @@ function parseRule(line) {
1063
1250
  dirOnly,
1064
1251
  nameOnly,
1065
1252
  fast,
1066
- source
1253
+ source,
1254
+ tokens,
1255
+ wildcards
1067
1256
  };
1068
1257
  }
1069
1258
  /**
1070
- * Translates a gitignore glob (already stripped of anchors and trailing
1071
- * slashes) into regex source. Returns `null` for an unusable pattern.
1259
+ * Parses a gitignore glob (already stripped of anchors and trailing slashes).
1260
+ * Returns `null` for a malformed pattern.
1072
1261
  */
1073
- function globToRegex(glob) {
1074
- let out = "";
1262
+ function parseGlob(glob) {
1263
+ const out = [];
1075
1264
  const n = glob.length;
1076
1265
  for (let i = 0; i < n; i++) {
1077
1266
  const c = glob[i];
1078
1267
  if (c === "\\") {
1079
- if (i + 1 < n) out += escapeRegex(glob[++i]);
1080
- else out += "\\\\";
1268
+ if (i + 1 >= n) return null;
1269
+ out.push({
1270
+ kind: "char",
1271
+ char: glob[++i]
1272
+ });
1081
1273
  } else if (c === "*") {
1082
1274
  if (glob[i + 1] === "*") {
1083
1275
  let j = i + 1;
1084
1276
  while (glob[j] === "*") j++;
1085
1277
  const atStart = i === 0 || glob[i - 1] === "/";
1086
- if (atStart && j === n) out += ".*";
1278
+ if (atStart && j === n) out.push(ALL);
1087
1279
  else if (atStart && glob[j] === "/") {
1088
- out += "(?:.*/)?";
1280
+ out.push(DIRS);
1089
1281
  j++;
1090
- } else out += "[^/]*";
1282
+ } else out.push(STAR);
1091
1283
  i = j - 1;
1092
- } else out += "[^/]*";
1093
- } else if (c === "?") out += "[^/]";
1284
+ } else out.push(STAR);
1285
+ } else if (c === "?") out.push(ANY);
1094
1286
  else if (c === "[") {
1095
1287
  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);
1288
+ if (cls === null) return null;
1289
+ out.push({
1290
+ kind: "class",
1291
+ source: cls.source
1292
+ });
1293
+ i = cls.end;
1294
+ } else out.push({
1295
+ kind: "char",
1296
+ char: c
1297
+ });
1103
1298
  }
1104
1299
  return out;
1105
1300
  }
1106
- /** Parses a bracket expression starting at `start`; `null` when it is not closed. */
1301
+ /**
1302
+ * Parses a bracket expression starting at `start`, following Git's wildmatch.
1303
+ * Returns `null` when it is malformed (not closed, or an unknown POSIX class).
1304
+ */
1107
1305
  function parseClass(glob, start) {
1108
1306
  let i = start + 1;
1109
- let negate = false;
1110
- if (glob[i] === "!" || glob[i] === "^") {
1111
- negate = true;
1112
- i++;
1113
- }
1307
+ const negate = glob[i] === "!" || glob[i] === "^";
1308
+ if (negate) i++;
1114
1309
  let body = "";
1115
- let first = true;
1116
- for (; i < glob.length; i++) {
1310
+ let rangeStart;
1311
+ for (let first = true;; i++, first = false) {
1117
1312
  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);
1313
+ if (c === void 0) return null;
1314
+ if (c === "]" && !first) break;
1315
+ if (c === "\\") {
1316
+ const escaped = glob[++i];
1317
+ if (escaped === void 0) return null;
1318
+ body += escapeInClass(escaped);
1319
+ rangeStart = escaped;
1320
+ } else if (c === "-" && rangeStart !== void 0 && !isClassEnd(glob[i + 1])) {
1321
+ let end = glob[++i];
1322
+ if (end === "\\") {
1323
+ const escaped = glob[++i];
1324
+ if (escaped === void 0) return null;
1325
+ end = escaped;
1326
+ }
1327
+ if (rangeStart <= end) body += `${escapeInClass(rangeStart)}-${escapeInClass(end)}`;
1328
+ rangeStart = void 0;
1329
+ } else if (c === "[" && glob[i + 1] === ":") {
1330
+ const close = glob.indexOf("]", i + 2);
1126
1331
  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);
1332
+ if (glob[close - 1] === ":" && close - 1 >= i + 2) {
1333
+ const posix = POSIX_CLASSES[glob.slice(i + 2, close - 1)];
1334
+ if (posix === void 0) return null;
1335
+ body += posix;
1336
+ i = close;
1337
+ rangeStart = void 0;
1338
+ } else {
1339
+ body += escapeInClass(c);
1340
+ rangeStart = c;
1341
+ }
1342
+ } else {
1343
+ body += escapeInClass(c);
1344
+ rangeStart = c;
1345
+ }
1135
1346
  }
1136
- return null;
1347
+ return {
1348
+ source: `(?!/)[${negate ? "^" : ""}${body}]`,
1349
+ end: i
1350
+ };
1351
+ }
1352
+ function isClassEnd(c) {
1353
+ return c === void 0 || c === "]";
1137
1354
  }
1138
1355
  const POSIX_CLASSES = {
1139
1356
  alnum: "a-zA-Z0-9",
@@ -1153,7 +1370,7 @@ function escapeRegex(c) {
1153
1370
  return /[\\^$.*+?()[\]{}|/-]/.test(c) ? `\\${c}` : c;
1154
1371
  }
1155
1372
  function escapeInClass(c) {
1156
- return c === "\\" ? "\\\\" : c;
1373
+ return /[\\\]^[-]/.test(c) ? `\\${c}` : c;
1157
1374
  }
1158
1375
  //#endregion
1159
1376
  //#region src/core/exclude.ts
@@ -1264,7 +1481,8 @@ var Excluder = class {
1264
1481
  strip: 0
1265
1482
  });
1266
1483
  };
1267
- await add(join(repoRoot, ".git", "info", "exclude"), repoRoot);
1484
+ const infoExclude = await findInfoExclude(repoRoot);
1485
+ if (infoExclude !== null) await add(infoExclude, repoRoot);
1268
1486
  for (const dir of outermostFirst) await add(join(dir, ".gitignore"), dir);
1269
1487
  return scopes;
1270
1488
  }
@@ -1272,6 +1490,21 @@ var Excluder = class {
1272
1490
  return GitignoreMatcher.compile(source, { ignoreCase: this.#ignoreCase });
1273
1491
  }
1274
1492
  };
1493
+ /**
1494
+ * Locates `info/exclude`. In a linked worktree or a submodule `.git` is a file
1495
+ * naming the real Git directory, and a worktree shares its main repository's
1496
+ * exclude file through `commondir`.
1497
+ */
1498
+ async function findInfoExclude(repoRoot) {
1499
+ const dotGit = join(repoRoot, ".git");
1500
+ const pointer = await readFile$1(dotGit, "utf8").catch(() => null);
1501
+ if (pointer === null) return join(dotGit, "info", "exclude");
1502
+ const gitDir = /^gitdir:\s*(.+?)\s*$/m.exec(pointer)?.[1];
1503
+ if (gitDir === void 0) return null;
1504
+ const dir = resolve(repoRoot, gitDir);
1505
+ const commonDir = await readFile$1(join(dir, "commondir"), "utf8").catch(() => null);
1506
+ return join(commonDir === null ? dir : resolve(dir, commonDir.trim()), "info", "exclude");
1507
+ }
1275
1508
  function isGitIgnored(chain, relPath, isDirectory) {
1276
1509
  let ignored = false;
1277
1510
  for (const scope of chain) {
@@ -2807,6 +3040,52 @@ function truncateMiddle(text, max) {
2807
3040
  const keepStart = max - 1 - keepEnd;
2808
3041
  return `${text.slice(0, keepStart)}…${text.slice(text.length - keepEnd)}`;
2809
3042
  }
3043
+ /** C0 and C1 controls, DEL, Unicode line separators, and bidirectional overrides. */
3044
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
3045
+ /** The same, without tab, CR, and LF, which CSV can carry inside a quoted cell. */
3046
+ const CONTROL_EXCEPT_WHITESPACE = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
3047
+ /** What `JSON.stringify` leaves raw but a terminal could still act on. */
3048
+ const JSON_UNSAFE = /[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g;
3049
+ const NAMED_ESCAPES = {
3050
+ "\n": "\\n",
3051
+ "\r": "\\r",
3052
+ " ": "\\t"
3053
+ };
3054
+ function hexEscape(c) {
3055
+ const code = c.charCodeAt(0);
3056
+ return code <= 255 ? `\\x${code.toString(16).padStart(2, "0")}` : `\\u${code.toString(16).padStart(4, "0")}`;
3057
+ }
3058
+ function controlEscape(c) {
3059
+ return NAMED_ESCAPES[c] ?? hexEscape(c);
3060
+ }
3061
+ /**
3062
+ * Makes untrusted text, such as a file name, safe to print: control characters
3063
+ * become visible escapes (`\x1b`, `\n`), so a name cannot drive the terminal,
3064
+ * forge report lines, or disguise itself. Backslashes are left alone because
3065
+ * Windows paths are full of them, so use JSON output for the exact name.
3066
+ */
3067
+ function escapeControl(text) {
3068
+ return text.replace(CONTROL, controlEscape);
3069
+ }
3070
+ /** {@link escapeControl} for cells of a format that can quote tabs and line breaks. */
3071
+ function escapeControlKeepingWhitespace(text) {
3072
+ return text.replace(CONTROL_EXCEPT_WHITESPACE, controlEscape);
3073
+ }
3074
+ /** {@link escapeControl} for a multi-line message: its own line breaks are kept. */
3075
+ function escapeControlInLines(text) {
3076
+ return text.split("\n").map(escapeControl).join("\n");
3077
+ }
3078
+ /** Fits a name into `max` columns. Escapes first, so an escape is counted and never cut raw. */
3079
+ function fitPath(text, max) {
3080
+ return truncateMiddle(escapeControl(text), max);
3081
+ }
3082
+ /**
3083
+ * `JSON.stringify` that also writes terminal-sensitive characters as `\uXXXX`.
3084
+ * Parsing the output gives back exactly the same strings.
3085
+ */
3086
+ function stringifyJson(value, indent) {
3087
+ return JSON.stringify(value, null, indent).replace(JSON_UNSAFE, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
3088
+ }
2810
3089
  const PARTIAL_BLOCKS = [
2811
3090
  "",
2812
3091
  "▏",
@@ -2889,7 +3168,7 @@ var Renderer = class {
2889
3168
  for (const item of shown) {
2890
3169
  const suffix = extra ? ` ${this.s.dim(extra(item))}` : "";
2891
3170
  const used = 15 + (extra ? extra(item).length + 2 : 0);
2892
- this.line(` ${this.size(item.bytes)} ${truncateMiddle(item.path, this.room(used))}${suffix}`);
3171
+ this.line(` ${this.size(item.bytes)} ${fitPath(item.path, this.room(used))}${suffix}`);
2893
3172
  }
2894
3173
  this.more(shown.length, total);
2895
3174
  }
@@ -2900,7 +3179,7 @@ function renderAnalysis(result, options = {}) {
2900
3179
  const { s } = r;
2901
3180
  const now = options.now ?? Date.now();
2902
3181
  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))}`);
3182
+ r.line(` ${s.bold(s.blue("dat"))} ${s.bold(fitPath(result.root, r.room(20)))} ${s.dim(formatElapsed(result.durationMs))}`);
2904
3183
  r.line("");
2905
3184
  const row = (label, value) => r.line(` ${padEndVisible(s.dim(label), 10)}${value}`);
2906
3185
  const disk = sum.diskBytes !== sum.bytes ? ` ${s.dim(`(${r.bytes(sum.diskBytes)} on disk)`)}` : "";
@@ -2923,7 +3202,7 @@ function renderAnalysis(result, options = {}) {
2923
3202
  r.heading("Largest folders");
2924
3203
  for (const dir of result.largestDirectories.slice(0, r.limit)) {
2925
3204
  const files = plural(dir.files, "file");
2926
- r.line(` ${r.size(dir.bytes)} ${truncateMiddle(`${dir.path}/`, r.room(17 + files.length))} ${s.dim(files)}`);
3205
+ r.line(` ${r.size(dir.bytes)} ${fitPath(`${dir.path}/`, r.room(17 + files.length))} ${s.dim(files)}`);
2927
3206
  }
2928
3207
  }
2929
3208
  if (result.largestFiles.length > 0) {
@@ -2938,13 +3217,13 @@ function renderAnalysis(result, options = {}) {
2938
3217
  if (result.duplicates) renderDuplicates(r, result.duplicates);
2939
3218
  if (result.emptyFiles) {
2940
3219
  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))}`);
3220
+ for (const file of result.emptyFiles.items.slice(0, r.limit)) r.line(` ${fitPath(file.path, r.room(3))}`);
2942
3221
  r.more(Math.min(r.limit, result.emptyFiles.items.length), result.emptyFiles.count);
2943
3222
  }
2944
3223
  if (result.emptyDirectories) {
2945
3224
  const ed = result.emptyDirectories;
2946
3225
  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))}`);
3226
+ for (const dir of ed.items.slice(0, r.limit)) r.line(` ${fitPath(`${dir}/`, r.room(3))}`);
2948
3227
  r.more(Math.min(r.limit, ed.items.length), ed.count);
2949
3228
  }
2950
3229
  if (result.staleFiles) {
@@ -2960,8 +3239,9 @@ function renderAnalysis(result, options = {}) {
2960
3239
  r.heading("Unreadable", plural(sum.errors, "path"));
2961
3240
  const shown = result.errors.slice(0, 5);
2962
3241
  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)}`);
3242
+ const message = escapeControl(error.message);
3243
+ const used = 13 + message.length;
3244
+ r.line(` ${s.yellow(padEndVisible(error.code, 8))}${fitPath(error.path, r.room(used))} ${s.dim(message)}`);
2965
3245
  }
2966
3246
  r.more(shown.length, sum.errors);
2967
3247
  }
@@ -2971,7 +3251,7 @@ function renderAnalysis(result, options = {}) {
2971
3251
  for (const budget of result.budgets) {
2972
3252
  const actual = formatBudgetActual(budget, r.units);
2973
3253
  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)}`);
3254
+ r.line(` ${mark} ${padEndVisible(escapeControl(budget.rule), 24)} ${s.dim("actual")} ${budget.passed ? actual : s.red(actual)}`);
2975
3255
  }
2976
3256
  }
2977
3257
  r.line("");
@@ -2992,7 +3272,7 @@ function renderExtensions(r, result) {
2992
3272
  const total = result.summary.bytes;
2993
3273
  r.heading("Extensions", plural(result.extensions.length, "distinct extension"));
2994
3274
  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"))}`);
3275
+ 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
3276
  r.more(shown.length, result.extensions.length);
2997
3277
  }
2998
3278
  function renderDuplicates(r, duplicates) {
@@ -3006,7 +3286,7 @@ function renderDuplicates(r, duplicates) {
3006
3286
  for (const group of shown) {
3007
3287
  r.line(` ${r.size(group.wastedBytes)} ${s.dim(`${group.files.length} × ${r.bytes(group.bytes)}`)}`);
3008
3288
  const files = group.files.slice(0, 5);
3009
- for (const file of files) r.line(` ${" ".repeat(SIZE_WIDTH)} ${truncateMiddle(file, r.room(15))}`);
3289
+ for (const file of files) r.line(` ${" ".repeat(SIZE_WIDTH)} ${fitPath(file, r.room(15))}`);
3010
3290
  if (group.files.length > files.length) r.line(` ${" ".repeat(SIZE_WIDTH)} ${s.dim(`… ${group.files.length - files.length} more copies`)}`);
3011
3291
  }
3012
3292
  r.more(shown.length, duplicates.count, "more groups");
@@ -3016,7 +3296,7 @@ function renderTree(r, root) {
3016
3296
  const walk = (node, prefix, isLast, isRoot) => {
3017
3297
  const connector = isRoot ? "" : isLast ? "└─ " : "├─ ";
3018
3298
  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));
3299
+ const name = fitPath(node.type === "directory" && !isRoot ? `${node.name}/` : node.name, Math.max(12, r.width - used));
3020
3300
  r.line(` ${r.size(node.bytes)} ${s.dim(prefix + connector)}${node.type === "directory" ? s.bold(name) : name}`);
3021
3301
  const childPrefix = isRoot ? "" : prefix + (isLast ? " " : "│ ");
3022
3302
  const children = node.children ?? [];
@@ -3038,8 +3318,8 @@ function renderComparison(result, options = {}) {
3038
3318
  };
3039
3319
  r.line(` ${s.bold(s.blue("dat compare"))} ${s.dim(formatElapsed(result.durationMs))}`);
3040
3320
  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))}`);
3321
+ r.line(` ${s.dim("left ")} ${fitPath(result.left.root, r.room(12))}`);
3322
+ r.line(` ${s.dim("right")} ${fitPath(result.right.root, r.room(12))}`);
3043
3323
  const col = (text) => padStartVisible(text, 12);
3044
3324
  r.heading("Overview");
3045
3325
  r.line(` ${padEndVisible("", 10)}${col(s.dim("left"))}${col(s.dim("right"))} ${s.dim("change")}`);
@@ -3061,7 +3341,7 @@ function renderComparison(result, options = {}) {
3061
3341
  const fileSection = (title, list, mark) => {
3062
3342
  if (list.count === 0) return;
3063
3343
  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))}`);
3344
+ for (const f of list.items.slice(0, r.limit)) r.line(` ${mark} ${r.size(f.bytes)} ${fitPath(f.path, r.room(17))}`);
3065
3345
  r.more(Math.min(r.limit, list.items.length), list.count);
3066
3346
  };
3067
3347
  fileSection("Added", result.added, s.green("+"));
@@ -3070,13 +3350,13 @@ function renderComparison(result, options = {}) {
3070
3350
  r.heading("Changed", `${plural(result.changed.count, "file")} · ${result.changed.delta > 0 ? "+" : ""}${formatBytes(result.changed.delta, r.units)} net`);
3071
3351
  for (const c of result.changed.items.slice(0, r.limit)) {
3072
3352
  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)}`);
3353
+ r.line(` ${s.yellow("~")} ${padStartVisible(signed(c.delta), SIZE_WIDTH)} ${fitPath(c.path, r.room(19 + detail.length))} ${s.dim(detail)}`);
3074
3354
  }
3075
3355
  r.more(Math.min(r.limit, result.changed.items.length), result.changed.count);
3076
3356
  }
3077
3357
  if (result.directories.length > 0) {
3078
3358
  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))}`);
3359
+ for (const d of result.directories.slice(0, r.limit)) r.line(` ${padStartVisible(signed(d.delta), 12)} ${fitPath(`${d.path}/`, r.room(17))}`);
3080
3360
  }
3081
3361
  r.line("");
3082
3362
  const identical = result.added.count + result.removed.count + result.changed.count === 0;
@@ -3086,10 +3366,16 @@ function renderComparison(result, options = {}) {
3086
3366
  }
3087
3367
  //#endregion
3088
3368
  //#region src/reporters/markdown.ts
3089
- /** Inline code that is safe inside a GitHub table cell. */
3369
+ /**
3370
+ * Inline code that is safe inside a GitHub table cell. The fence is longer than
3371
+ * any run of backticks in the text, so a file name cannot close it early and
3372
+ * have the rest of its name rendered as Markdown.
3373
+ */
3090
3374
  function mdCode(text) {
3091
- const fence = text.includes("`") ? "``" : "`";
3092
- return `${fence}${(fence === "``" ? ` ${text} ` : text).replaceAll("|", "\\|")}${fence}`;
3375
+ const safe = escapeControl(text).replaceAll("|", "\\|");
3376
+ const longestRun = Math.max(0, ...(safe.match(/`+/g) ?? []).map((run) => run.length));
3377
+ const fence = "`".repeat(longestRun + 1);
3378
+ return longestRun > 0 ? `${fence} ${safe} ${fence}` : `${fence}${safe}${fence}`;
3093
3379
  }
3094
3380
  function table(header, rows, align) {
3095
3381
  const sep = header.map((_, i) => align?.[i] === "r" ? "---:" : "---");
@@ -3310,12 +3596,13 @@ function renderComparisonMarkdown(result, options = {}) {
3310
3596
  /**
3311
3597
  * Quotes a CSV cell when needed (RFC 4180) and neutralizes spreadsheet
3312
3598
  * formula injection: text starting with `=`, `+`, `-`, `@`, tab, or carriage
3313
- * return is prefixed with an apostrophe so it is never evaluated.
3599
+ * return is prefixed with an apostrophe so it is never evaluated. Other control
3600
+ * characters are escaped because CSV is often printed; JSON keeps exact names.
3314
3601
  */
3315
3602
  function csvCell(value) {
3316
3603
  if (value === null || value === void 0) return "";
3317
3604
  if (typeof value === "number") return String(value);
3318
- let text = value;
3605
+ let text = escapeControlKeepingWhitespace(value);
3319
3606
  if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`;
3320
3607
  return /[",\r\n]/.test(text) ? `"${text.replaceAll("\"", "\"\"")}"` : text;
3321
3608
  }
@@ -3677,4 +3964,4 @@ document.getElementById('filter').addEventListener('input', function (event) {
3677
3964
  });
3678
3965
  `;
3679
3966
  //#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 };
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 };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dir-analysis-tool",
3
- "version": "3.1.0",
3
+ "version": "3.2.1",
4
4
  "description": "Fast, zero-dependency directory analysis for your terminal and CI: largest folders and files, type and extension breakdowns, staged duplicate detection, size budgets, directory diffs, and self-contained HTML, Markdown, JSON, and CSV reports.",
5
5
  "type": "module",
6
6
  "exports": {