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.
package/README.md CHANGED
@@ -46,7 +46,7 @@ npx dir-analysis-tool
46
46
  - [Installation](#installation)
47
47
  - [Quick start](#quick-start)
48
48
  - [What it shows](#what-it-shows)
49
- - [Commands](#commands): [`analyze`](#dat-analyze), [`compare`](#dat-compare), [`watch`](#dat-watch), [`init`](#dat-init)
49
+ - [Commands](#commands): [`analyze`](#dat-analyze), [`compare`](#dat-compare), [`explain`](#dat-explain), [`watch`](#dat-watch), [`init`](#dat-init)
50
50
  - [Sizes, ages, and patterns](#sizes-ages-and-patterns)
51
51
  - [Budgets in CI](#budgets-in-ci)
52
52
  - [Output formats](#output-formats)
@@ -88,6 +88,7 @@ dat . --stale 2y # files untouched for two years
88
88
  dat . -t --tree-depth 2 # a size tree, two levels deep
89
89
  dat . -g -x # honor .gitignore, show extensions
90
90
  dat compare dist-old dist-new # what changed between two builds
91
+ dat explain -g # what a scan skips, and which rule skipped it
91
92
  dat . -b "size<=200MB" -b "duplicates=0" # fail CI when a budget is exceeded
92
93
  dat . --html report.html # a self-contained HTML report
93
94
  dat . --json | jq '.largestFiles[0]' # machine-readable output
@@ -150,7 +151,7 @@ A size tree (`dat src -t --tree-depth 2`):
150
151
 
151
152
  `dat [directory] [options]`. `analyze` is the default command, so `dat .` and `dat analyze .` are the same.
152
153
 
153
- **Scan options** decide which files are counted. They also apply to `compare` and `watch`.
154
+ **Scan options** decide which files are counted. They also apply to `compare`, `explain`, and `watch`.
154
155
 
155
156
  | Option | Description |
156
157
  | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
@@ -232,6 +233,57 @@ A size tree (`dat src -t --tree-depth 2`):
232
233
 
233
234
  All scan options and shared output options above are accepted too; `--html`, `--csv`, and HTML format are analyze-only. Use `--format csv` to export a comparison.
234
235
 
236
+ ### `dat explain`
237
+
238
+ `dat explain [path] [options]` says why a scan counts or skips something, using the same scan options and config file as `analyze`. It never changes what `analyze` reports.
239
+
240
+ With a path, it explains that one entry without a full scan: it walks down from the root as the scanner does and names the rule or limit that decided, with its file and line.
241
+
242
+ ```text
243
+ $ dat explain build/keep/k.txt -g
244
+ build/keep/k.txt: excluded
245
+
246
+ Decided at build (parent directory)
247
+ Rule .gitignore:1 build/
248
+ Inside it not measured; dat never enters a directory it skips
249
+ Note .gitignore:2 !build/keep/ cannot re-include this: its parent directory build is excluded.
250
+ Note Git's global excludes file (core.excludesFile, usually ~/.config/git/ignore) is not read; Git may ignore more than dat does.
251
+ ```
252
+
253
+ Without a path, it runs one scan and groups everything left out by the rule that skipped it: default excludes, each exclude pattern, each `.gitignore` line, size and date filters, `--max-depth`, and symbolic links that were not followed. Counts are complete and equal `summary.excluded` and `summary.filtered` from `analyze`; each group lists its first 20 entries in path order.
254
+
255
+ ```text
256
+ $ dat explain -g
257
+ Skipped: 5 entries excluded
258
+
259
+ .gitignore:3 *.log 2
260
+ a.log
261
+ b.log
262
+ default exclude .git 1
263
+ .git
264
+ default exclude node_modules 1
265
+ node_modules
266
+ .gitignore:1 build/ 1
267
+ build
268
+
269
+ Sizes inside skipped directories are unknown. Measure one with: dat <dir> --all
270
+ ```
271
+
272
+ | Option | Description |
273
+ | -------------- | --------------------------------------------------------------------------------------- |
274
+ | `--root <dir>` | The scan root to evaluate. Default: the current directory. Patterns are relative to it. |
275
+ | `--limit <n>` | Entries listed per group, from `0` to `1000`. Default `20`. Counts are never truncated. |
276
+ | `-j, --json` | Print JSON (`explainVersion: 1`), versioned separately from the `analyze` report. |
277
+
278
+ All scan options are accepted, as are `--si`, `--color`, `--no-color`, `--no-progress`, and `-q`. The path is relative to the current directory and must be inside the root.
279
+
280
+ - **Decisions:** `included`, `excluded` (a default, a pattern, `.gitignore`, or `.git/info/exclude`), `filtered` (size or date), `skipped` (beyond `--max-depth`, a symbolic link that is not followed, a socket or device, or an unreadable folder), and `not-found`. The exit code is `0` for all of them, so read `decision`; `1` means an error, such as a path outside the root.
281
+ - **What it cannot know** is said, not guessed. dat never enters an excluded directory, so the size and count below one stay unknown (`descendants` is always `null`). Notes flag a negation that cannot work (`!build/keep/` under an ignored `build/`, `-e '!node_modules'`, or `-e '!x.log'` against a `.gitignore` rule), a scan root that Git ignores, nested repositories, matches that depend on the platform's case-insensitivity, and counts that depend on scan order (hard links, followed symlinks).
282
+ - **Not read:** Git's global excludes file (`core.excludesFile`, usually `~/.config/git/ignore`). Every `-g` explanation inside a repository says so. A `.git` file, which links a worktree or submodule to its repository, is counted as an ordinary file, because default excludes only skip directories.
283
+ - `--max-depth` skips are reported only here (`totals.depthSkipped`); `analyze` does not count them.
284
+
285
+ `dat explain` analyzes nothing; to analyze a directory that is literally named `explain`, run `dat ./explain`.
286
+
235
287
  ### `dat watch`
236
288
 
237
289
  `dat watch [directory] [options]` re-analyzes whenever something changes. It uses the operating system's native file watching: recursive on macOS and Windows; on Linux, one watcher per scanned folder, so skipped folders like `node_modules` are never watched. If watching fails, it falls back to polling.
@@ -266,7 +318,7 @@ All scan, report, and output options are accepted too (`pretty` and `json` forma
266
318
 
267
319
  **Ages and dates:** an age counts back from now (`45s`, `30min`, `12h`, `90d`, `2w`, `6mo`, `1y`). A date is `YYYY-MM-DD` in local time, or any ISO 8601 timestamp.
268
320
 
269
- **Patterns** use [gitignore syntax](https://git-scm.com/docs/gitignore#_pattern_format) relative to the analyzed directory: `*.log` matches at any depth, `build/` matches only directories, `/out` matches only at the top, `docs/**/*.pdf` matches nested files, and `!keep.log` re-includes a file.
321
+ **Patterns** use [gitignore syntax](https://git-scm.com/docs/gitignore#_pattern_format) relative to the analyzed directory: `*.log` matches at any depth, `build/` matches only directories, `/out` matches only at the top, `docs/**/*.pdf` matches nested files, and `!keep.log` re-includes a file that an earlier pattern in the same list excluded. A negation cannot re-include a file inside an excluded folder, a default exclude such as `node_modules` (use `--all`), or a file that `.gitignore` excludes, because exclude patterns are checked first. `dat explain <path>` shows which rule decided.
270
322
 
271
323
  ## Budgets in CI
272
324
 
@@ -418,6 +470,7 @@ await writeFile('report.md', renderAnalysisMarkdown(result));
418
470
  | `analyze(path, options?)` | Analyze a tree. Options mirror the CLI flags: `exclude`, `gitignore`, `maxDepth`, `minSize`, `modifiedAfter`, `top`, `largeFiles`, `duplicates`, `empty`, `stale`, `tree`, `budgets`, `concurrency`, `signal`, `onProgress`, and more. |
419
471
  | `compare(left, right, options?)` | Diff two trees. |
420
472
  | `listDirectories(path, options?)` | The folders a scan would enter. |
473
+ | `explainPath(root, path, options?)`, `explainSkips(root, options?)` | Why a scan counts or skips one path, and everything a scan skips grouped by rule (`limit` caps listed entries). Render with `renderPathExplanation` and `renderSkipsExplanation`. |
421
474
  | `renderAnalysis`, `renderAnalysisMarkdown`, `renderAnalysisCsv`, `renderAnalysisHtml` | Render a result in any format. `renderComparison*` does the same for comparisons. |
422
475
  | `formatBytes`, `parseSize`, `parseDuration`, `parsePointInTime` | Unit helpers. |
423
476
  | `loadConfig`, `validateConfig`, `buildJsonSchema` | Config helpers. |
@@ -439,7 +492,7 @@ Then ask in your own words, for example "why is this repo so big?" or "fail CI i
439
492
  ## How it works
440
493
 
441
494
  - **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.
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.
495
+ - **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.
443
496
  - **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.
444
497
  - **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.
445
498
  - **Duplicates,** in stages so most files are never read in full:
@@ -466,7 +519,7 @@ The benchmark script reports scan and duplicate timings plus process peak RSS (n
466
519
 
467
520
  | Code | Meaning |
468
521
  | ----- | ------------------------------------------------------------- |
469
- | `0` | Success |
522
+ | `0` | Success, including every `dat explain` decision |
470
523
  | `1` | Error: invalid option or config, missing directory, and so on |
471
524
  | `2` | A budget failed |
472
525
  | `130` | Interrupted (Ctrl+C) |
@@ -491,7 +544,7 @@ v3 is a rewrite with a new output format. Most commands keep working unchanged.
491
544
 
492
545
  ## FAQ
493
546
 
494
- **Why does the total differ from `du`?** `du` reports blocks allocated on disk, while the headline size is the sum of file lengths. The `On disk` line matches `du`. Also check what was skipped: `.git` and `node_modules` are excluded by default (`--all` includes them), and hard-linked data is counted once, as `du` does.
547
+ **Why does the total differ from `du`?** `du` reports blocks allocated on disk, while the headline size is the sum of file lengths. The `On disk` line matches `du`. Also check what was skipped: `.git` and `node_modules` are excluded by default (`--all` includes them), and hard-linked data is counted once, as `du` does. `dat explain` lists everything a scan skipped and why.
495
548
 
496
549
  **Is it safe to run on a huge directory?** Yes. The default scan keeps bounded top-N file lists, but folder metadata, hard-link tracking, and symlink tracking still require memory. Duplicate detection, directory comparisons, and optional file lists use additional memory, filesystem concurrency is bounded, and unreadable paths are reported rather than fatal. Press Ctrl+C at any time.
497
550
 
package/dist/cli.js CHANGED
@@ -1,10 +1,10 @@
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 parseBudget, C as MAX_EXPLAIN_LIMIT, E as compare, H as parseSize, J as DatError, K as parsePointInTime, M as joinRelative, P as Excluder, T as explainSkips, V as formatBytes, W as VERSION, X as errorMessage, Y as errorCode, a as renderComparisonCsv, c as renderAnalysis, d as escapeControlInLines, f as formatCount, h as supportsColor, i as renderAnalysisCsv, j as listDirectories, k as analyze, l as renderComparison, m as createStyle, n as renderSkipsExplanation, o as renderAnalysisMarkdown, p as stringifyJson, q as AbortError, r as renderAnalysisHtml, s as renderComparisonMarkdown, t as renderPathExplanation, u as escapeControl, v as loadConfig, w as explainPath, z as formatBudgetActual } from "./shared-DfKY8fSl.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";
6
6
  import { createInterface } from "node:readline";
7
- //#region src/cli/io.ts
7
+ // src/cli/io.ts
8
8
  function processIO(signal) {
9
9
  return {
10
10
  stdout: process.stdout,
@@ -33,8 +33,7 @@ function terminalWidth(io) {
33
33
  const fromEnv = Number(io.env["COLUMNS"]);
34
34
  return io.stdout.columns ?? (Number.isInteger(fromEnv) && fromEnv > 0 ? fromEnv : 100);
35
35
  }
36
- //#endregion
37
- //#region src/cli/command.ts
36
+ // src/cli/command.ts
38
37
  /**
39
38
  * A small command-line parser covering the subset of the commander API this
40
39
  * CLI uses: subcommands with a default, grouped options, repeatable and
@@ -577,8 +576,7 @@ function suggestSimilar(word, candidates) {
577
576
  if (similar.length > 1) return `one of ${similar.join(", ")}`;
578
577
  return similar[0] ?? "";
579
578
  }
580
- //#endregion
581
- //#region src/cli/argv.ts
579
+ // src/cli/argv.ts
582
580
  /**
583
581
  * Options whose value is optional. Commander would treat the next argument
584
582
  * as their value, so `dat -l ./photos` would read "./photos" as a size. For
@@ -646,8 +644,7 @@ function isPointInTime(value) {
646
644
  return false;
647
645
  }
648
646
  }
649
- //#endregion
650
- //#region src/reporters/index.ts
647
+ // src/reporters/index.ts
651
648
  const FORMATS = [
652
649
  "pretty",
653
650
  "json",
@@ -658,7 +655,7 @@ const FORMATS = [
658
655
  function renderAnalysisAs(format, result, options) {
659
656
  switch (format) {
660
657
  case "pretty": return renderAnalysis(result, options);
661
- case "json": return `${JSON.stringify(result, null, 2)}\n`;
658
+ case "json": return `${stringifyJson(result, 2)}\n`;
662
659
  case "markdown": return renderAnalysisMarkdown(result, options);
663
660
  case "csv": return renderAnalysisCsv(result);
664
661
  case "html": return renderAnalysisHtml(result, { units: options.units });
@@ -667,14 +664,13 @@ function renderAnalysisAs(format, result, options) {
667
664
  function renderComparisonAs(format, result, options) {
668
665
  switch (format) {
669
666
  case "pretty": return renderComparison(result, options);
670
- case "json": return `${JSON.stringify(result, null, 2)}\n`;
667
+ case "json": return `${stringifyJson(result, 2)}\n`;
671
668
  case "markdown": return renderComparisonMarkdown(result, options);
672
669
  case "csv": return renderComparisonCsv(result);
673
670
  case "html": throw new RangeError("HTML output is not available for compare; use pretty, json, markdown, or csv.");
674
671
  }
675
672
  }
676
- //#endregion
677
- //#region src/cli/options.ts
673
+ // src/cli/options.ts
678
674
  const SCAN_GROUP = "Scan options:";
679
675
  const REPORT_GROUP = "Report options:";
680
676
  const OUTPUT_GROUP = "Output options:";
@@ -804,8 +800,7 @@ function resolveDisplay(cli, config) {
804
800
  csv: read.flag(cli["csv"])
805
801
  };
806
802
  }
807
- //#endregion
808
- //#region src/cli/progress.ts
803
+ // src/cli/progress.ts
809
804
  const FRAMES = [
810
805
  "⠋",
811
806
  "⠙",
@@ -856,9 +851,8 @@ var ProgressLine = class {
856
851
  this.#visible = false;
857
852
  }
858
853
  };
859
- //#endregion
860
- //#region src/cli/commands/analyze.ts
861
- const EXAMPLES$2 = `
854
+ // src/cli/commands/analyze.ts
855
+ const EXAMPLES$3 = `
862
856
  Examples:
863
857
  $ dat analyze the current directory
864
858
  $ dat ~/Downloads -l 500MB list files of 500 MB or more
@@ -878,7 +872,7 @@ function registerAnalyze(program, ctx) {
878
872
  addReportOptions(command);
879
873
  addOutputOptions(command);
880
874
  addFileReportOptions(command);
881
- command.addHelpText("after", EXAMPLES$2);
875
+ command.addHelpText("after", EXAMPLES$3);
882
876
  command.action(async (directory, _options, cmd) => {
883
877
  const cli = explicitOptions(cmd);
884
878
  applyLegacyLargeFiles(cli, (message) => ctx.warn(message));
@@ -940,15 +934,14 @@ function reportBudgets(ctx, result, display) {
940
934
  }
941
935
  function displayPath(ctx, file) {
942
936
  const rel = relative(ctx.io.cwd, file);
943
- return rel && !rel.startsWith("..") ? rel : file;
937
+ return escapeControl(rel && !rel.startsWith("..") ? rel : file);
944
938
  }
945
939
  /** Items printed per list: the --top value, or 10 when the top lists are turned off. */
946
940
  function listLimit(top) {
947
941
  return top !== void 0 && top > 0 ? top : 10;
948
942
  }
949
- //#endregion
950
- //#region src/cli/commands/compare.ts
951
- const EXAMPLES$1 = `
943
+ // src/cli/commands/compare.ts
944
+ const EXAMPLES$2 = `
952
945
  Examples:
953
946
  $ dat compare dist-before dist-after what changed between two builds
954
947
  $ dat compare ./a ./b --content also detect same-size content changes
@@ -965,7 +958,7 @@ function registerCompare(program, ctx) {
965
958
  "markdown",
966
959
  "csv"
967
960
  ]);
968
- command.addHelpText("after", EXAMPLES$1);
961
+ command.addHelpText("after", EXAMPLES$2);
969
962
  command.action(async (left, right, _options, cmd) => {
970
963
  const cli = explicitOptions(cmd);
971
964
  const { config } = await ctx.loadConfig(cli, ctx.io.cwd);
@@ -994,12 +987,77 @@ function registerCompare(program, ctx) {
994
987
  });
995
988
  if (display.output) {
996
989
  const file = await ctx.writeFile(display.output, text);
997
- ctx.info(`${ctx.err.green("✔")} Comparison written to ${file}`, display.quiet);
990
+ ctx.info(`${ctx.err.green("✔")} Comparison written to ${escapeControl(file)}`, display.quiet);
998
991
  } else await ctx.stdout(text.endsWith("\n") ? text : `${text}\n`);
999
992
  });
1000
993
  }
1001
- //#endregion
1002
- //#region src/cli/prompt.ts
994
+ // src/cli/commands/explain.ts
995
+ const EXAMPLES$1 = `
996
+ Examples:
997
+ $ dat explain what a scan of this directory leaves out, and why
998
+ $ dat explain -g the same with .gitignore honored
999
+ $ dat explain build/out.js -g why one path is or is not counted
1000
+ $ dat explain node_modules/x -e '!node_modules'
1001
+ see why a negation has no effect
1002
+ $ dat explain src/a.ts --root .. explain against a scan of another root
1003
+ $ dat explain -g --json | jq '.groups[0]'
1004
+
1005
+ A path argument is relative to the current directory. To analyze a directory
1006
+ named "explain", run: dat ./explain
1007
+ Exit codes: 0 for any explanation (excluded and not-found included), 1 for errors.
1008
+ `;
1009
+ function limitOption(value) {
1010
+ const parsed = integer(0)(value);
1011
+ if (parsed > 1e3) throw new InvalidArgumentError(`Expected a whole number from 0 to ${MAX_EXPLAIN_LIMIT}.`);
1012
+ return parsed;
1013
+ }
1014
+ function registerExplain(program, ctx) {
1015
+ const command = program.command("explain").description("explain why a scan skips a path, or list everything it skips").argument("[path]", "a path to explain; omit it to summarize everything skipped");
1016
+ command.addOption(new Option("--root <dir>", "the scan root to evaluate (default: the current directory)").helpGroup("Explain options:"));
1017
+ command.addOption(new Option("--limit <n>", `entries listed per reason (default: 20, max: ${MAX_EXPLAIN_LIMIT})`).argParser(limitOption).helpGroup("Explain options:"));
1018
+ addScanOptions(command);
1019
+ command.addOption(new Option("-j, --json", "print JSON").helpGroup("Output options:")).addOption(new Option("--si", "use decimal units (kB, MB) instead of binary (KiB, MiB)").helpGroup("Output options:")).addOption(new Option("--color", "force colors").helpGroup("Output options:")).addOption(new Option("--no-color", "disable colors (also honors NO_COLOR)").helpGroup("Output options:")).addOption(new Option("--no-progress", "hide the progress line").helpGroup("Output options:")).addOption(new Option("-q, --quiet", "print only the explanation and errors").helpGroup("Output options:"));
1020
+ command.addHelpText("after", EXAMPLES$1);
1021
+ command.action(async (path, _options, cmd) => {
1022
+ const cli = explicitOptions(cmd);
1023
+ const root = ctx.resolvePath(read.string(cli["root"]) ?? ".");
1024
+ const { config } = await ctx.loadConfig(cli, root);
1025
+ const settings = resolveScanSettings(cli, config);
1026
+ const json = cli["json"] === true;
1027
+ const units = cli["si"] === true ? "si" : config.units ?? "iec";
1028
+ const style = ctx.outputStyle(read.boolean(cli["color"]), false);
1029
+ const width = terminalWidth(ctx.io);
1030
+ if (path !== void 0) {
1031
+ const result = await explainPath(root, ctx.resolvePath(path), {
1032
+ ...settings,
1033
+ signal: ctx.io.signal
1034
+ });
1035
+ await ctx.stdout(json ? `${stringifyJson(result, 2)}\n` : renderPathExplanation(result, {
1036
+ style,
1037
+ units
1038
+ }));
1039
+ return;
1040
+ }
1041
+ const progress = new ProgressLine(ctx.io.stderr, cli["progress"] !== false && cli["quiet"] !== true && ctx.io.stderr.isTTY === true, ctx.err, units);
1042
+ let result;
1043
+ try {
1044
+ if (progress.enabled) progress.update("Scanning for skipped entries");
1045
+ result = await explainSkips(root, {
1046
+ ...settings,
1047
+ limit: read.number(cli["limit"]),
1048
+ signal: ctx.io.signal
1049
+ });
1050
+ } finally {
1051
+ progress.clear();
1052
+ }
1053
+ await ctx.stdout(json ? `${stringifyJson(result, 2)}\n` : renderSkipsExplanation(result, {
1054
+ style,
1055
+ units,
1056
+ width
1057
+ }));
1058
+ });
1059
+ }
1060
+ // src/cli/prompt.ts
1003
1061
  /**
1004
1062
  * A tiny interactive prompt toolkit built on `node:readline`, so `dat init`
1005
1063
  * does not need a prompt library.
@@ -1128,8 +1186,7 @@ var Prompter = class {
1128
1186
  return rl;
1129
1187
  }
1130
1188
  };
1131
- //#endregion
1132
- //#region src/cli/commands/init.ts
1189
+ // src/cli/commands/init.ts
1133
1190
  const SCHEMA_URL = "https://unpkg.com/dir-analysis-tool@3/schema.json";
1134
1191
  function registerInit(program, ctx) {
1135
1192
  program.command("init").description("create a .dir-analyzer.json config file").argument("[directory]", "where to create the file", ".").addOption(new Option("-y, --yes", "skip the questions and write a starter config")).addOption(new Option("--force", "overwrite an existing config file")).action(async (directory, options) => {
@@ -1151,7 +1208,7 @@ function registerInit(program, ctx) {
1151
1208
  $schema: SCHEMA_URL,
1152
1209
  ...config
1153
1210
  }, null, 4)}\n`);
1154
- ctx.info(`${ctx.err.green("✔")} Wrote ${file}`, false);
1211
+ ctx.info(`${ctx.err.green("✔")} Wrote ${escapeControl(file)}`, false);
1155
1212
  });
1156
1213
  }
1157
1214
  /** Interactive questions, asked on the CLI's own stdin/stdout. */
@@ -1239,8 +1296,7 @@ function validateWith(value, parse) {
1239
1296
  return errorMessage(error);
1240
1297
  }
1241
1298
  }
1242
- //#endregion
1243
- //#region src/cli/watcher.ts
1299
+ // src/cli/watcher.ts
1244
1300
  /**
1245
1301
  * Watches a directory tree with the platform's native facility.
1246
1302
  *
@@ -1308,8 +1364,7 @@ var TreeWatcher = class {
1308
1364
  this.#watchers.set(dir, watcher);
1309
1365
  }
1310
1366
  };
1311
- //#endregion
1312
- //#region src/cli/commands/watch.ts
1367
+ // src/cli/commands/watch.ts
1313
1368
  const CLEAR_SCREEN = "\x1B[2J\x1B[3J\x1B[H";
1314
1369
  const EXAMPLES = `
1315
1370
  Examples:
@@ -1348,7 +1403,7 @@ function registerWatch(program, ctx) {
1348
1403
  });
1349
1404
  const render = async (result) => {
1350
1405
  if (display.format === "json") {
1351
- await ctx.stdout(`${JSON.stringify(result)}\n`);
1406
+ await ctx.stdout(`${stringifyJson(result)}\n`);
1352
1407
  return;
1353
1408
  }
1354
1409
  if (clear) await ctx.stdout(CLEAR_SCREEN);
@@ -1358,7 +1413,7 @@ function registerWatch(program, ctx) {
1358
1413
  csv: void 0
1359
1414
  }, listLimit(options.top));
1360
1415
  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);
1416
+ ctx.info(ctx.err.dim(`watching ${escapeControl(target)} · ${status} · ${(/* @__PURE__ */ new Date()).toLocaleTimeString()} · Ctrl+C to stop`), display.quiet);
1362
1417
  };
1363
1418
  let watcher = null;
1364
1419
  const run = async () => {
@@ -1382,7 +1437,7 @@ function registerWatch(program, ctx) {
1382
1437
  }
1383
1438
  } catch (error) {
1384
1439
  if (error instanceof AbortError) return;
1385
- ctx.io.stderr.write(`${ctx.err.red("error")} ${errorMessage(error)}\n`);
1440
+ ctx.io.stderr.write(`${ctx.err.red("error")} ${escapeControlInLines(errorMessage(error))}\n`);
1386
1441
  } finally {
1387
1442
  running = false;
1388
1443
  }
@@ -1406,7 +1461,7 @@ function registerWatch(program, ctx) {
1406
1461
  isIgnored: (rel) => excluder.isPathExcluded(rel),
1407
1462
  onChange: schedule,
1408
1463
  onError: (error) => {
1409
- ctx.warn(`file watching failed (${error.message}); falling back to polling every 5 seconds`);
1464
+ ctx.warn(`file watching failed (${escapeControl(error.message)}); falling back to polling every 5 seconds`);
1410
1465
  watcher?.close();
1411
1466
  watcher = null;
1412
1467
  if (!poller) startPolling(5);
@@ -1437,8 +1492,7 @@ function describeChange(previous, current, units) {
1437
1492
  if (files !== 0) parts.push(`${files > 0 ? "+" : ""}${formatCount(files)} ${Math.abs(files) === 1 ? "file" : "files"}`);
1438
1493
  return parts.join(", ");
1439
1494
  }
1440
- //#endregion
1441
- //#region src/cli/context.ts
1495
+ // src/cli/context.ts
1442
1496
  /** Shared state for one CLI invocation. */
1443
1497
  var Context = class {
1444
1498
  io;
@@ -1461,7 +1515,7 @@ var Context = class {
1461
1515
  if (!quiet) this.io.stderr.write(`${message}\n`);
1462
1516
  }
1463
1517
  warn(message) {
1464
- this.io.stderr.write(`${this.err.yellow("warning")} ${message}\n`);
1518
+ this.io.stderr.write(`${this.err.yellow("warning")} ${escapeControlInLines(message)}\n`);
1465
1519
  }
1466
1520
  async loadConfig(cli, searchFrom) {
1467
1521
  if (cli["config"] === false) return {
@@ -1487,17 +1541,17 @@ var Context = class {
1487
1541
  return write(this.io.stdout, text);
1488
1542
  }
1489
1543
  };
1490
- //#endregion
1491
- //#region src/cli/program.ts
1544
+ // src/cli/program.ts
1492
1545
  function createProgram(ctx) {
1493
1546
  const { io } = ctx;
1494
1547
  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
1548
  writeOut: (text) => io.stdout.write(text),
1496
1549
  writeErr: (text) => io.stderr.write(text),
1497
- outputError: (text, write) => write(ctx.err.red(text))
1550
+ outputError: (text, write) => write(ctx.err.red(escapeControlInLines(text)))
1498
1551
  }).showHelpAfterError("(run \"dat --help\" to see all options)").showSuggestionAfterError(true).exitOverride();
1499
1552
  registerAnalyze(program, ctx);
1500
1553
  registerCompare(program, ctx);
1554
+ registerExplain(program, ctx);
1501
1555
  registerWatch(program, ctx);
1502
1556
  registerInit(program, ctx);
1503
1557
  program.addHelpText("after", `
@@ -1528,18 +1582,17 @@ function handleError(error, ctx) {
1528
1582
  return ExitCode.Interrupted;
1529
1583
  }
1530
1584
  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`);
1585
+ io.stderr.write(`${err.red("error")} ${escapeControlInLines(error.message)}\n`);
1586
+ if (error.hint) io.stderr.write(`${err.dim(escapeControlInLines(error.hint))}\n`);
1533
1587
  return ExitCode.Error;
1534
1588
  }
1535
- const message = errorMessage(error);
1589
+ const message = escapeControlInLines(errorMessage(error));
1536
1590
  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`);
1591
+ if (io.env["DAT_DEBUG"] && error instanceof Error && error.stack) io.stderr.write(`${err.dim(escapeControlInLines(error.stack))}\n`);
1538
1592
  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
1593
  return ExitCode.Error;
1540
1594
  }
1541
- //#endregion
1542
- //#region src/cli/main.ts
1595
+ // src/cli/main.ts
1543
1596
  for (const stream of [process.stdout, process.stderr]) stream.on("error", (error) => {
1544
1597
  if (errorCode(error) === "EPIPE") process.exit(0);
1545
1598
  throw error;
@@ -1551,5 +1604,4 @@ process.on("SIGINT", () => {
1551
1604
  });
1552
1605
  process.on("SIGTERM", () => controller.abort());
1553
1606
  process.exitCode = await run(process.argv.slice(2), processIO(controller.signal));
1554
- //#endregion
1555
1607
  export {};