dir-analysis-tool 2.0.7 → 3.0.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
@@ -1,12 +1,12 @@
1
1
  <div align="center">
2
2
 
3
3
  <a href="https://www.npmjs.com/package/dir-analysis-tool">
4
- <img src=".github/assets/dir-analysis-tool-banner.png" alt="dir-analysis-tool, fast and memory-safe directory analysis for your terminal" width="100%" />
4
+ <img src=".github/assets/dir-analysis-tool-banner.png" alt="dir-analysis-tool: fast, memory-bounded directory analysis for your terminal and CI" width="100%" />
5
5
  </a>
6
6
 
7
7
  <h1>dir-analysis-tool</h1>
8
8
 
9
- <p><strong>A fast, memory-safe CLI for directory analysis:</strong> file classification, duplicate detection, large-file identification, HTML reports, and multiple export formats.</p>
9
+ <p><strong>Find out what is taking up space, fast.</strong> Largest folders and files, type and extension breakdowns, duplicate detection, size budgets for CI, directory diffs, and self-contained reports.</p>
10
10
 
11
11
  <p>
12
12
  <a href="https://www.npmjs.com/package/dir-analysis-tool"><img src="https://shieldcn.dev/npm/dir-analysis-tool.svg?logo=npm" alt="npm version" /></a>
@@ -18,9 +18,7 @@
18
18
 
19
19
  <p>
20
20
  <a href="https://github.com/KhaledSaeed18/dir-analysis-tool/stargazers"><img src="https://shieldcn.dev/github/stars/KhaledSaeed18/dir-analysis-tool.svg?variant=outline" alt="GitHub stars" /></a>
21
- <a href="https://github.com/KhaledSaeed18/dir-analysis-tool/network/members"><img src="https://shieldcn.dev/github/forks/KhaledSaeed18/dir-analysis-tool.svg?variant=outline" alt="GitHub forks" /></a>
22
21
  <a href="https://github.com/KhaledSaeed18/dir-analysis-tool/issues"><img src="https://shieldcn.dev/github/issues/KhaledSaeed18/dir-analysis-tool.svg?variant=outline" alt="GitHub issues" /></a>
23
- <a href="https://github.com/KhaledSaeed18/dir-analysis-tool/pulls"><img src="https://shieldcn.dev/github/prs/KhaledSaeed18/dir-analysis-tool.svg?variant=outline" alt="GitHub pull requests" /></a>
24
22
  <a href="https://github.com/KhaledSaeed18/dir-analysis-tool/releases"><img src="https://shieldcn.dev/github/release/KhaledSaeed18/dir-analysis-tool.svg?variant=ghost" alt="Latest release" /></a>
25
23
  </p>
26
24
 
@@ -28,271 +26,465 @@
28
26
 
29
27
  ---
30
28
 
31
- ## Why dir-analysis-tool?
29
+ ```bash
30
+ npx dir-analysis-tool
31
+ ```
32
32
 
33
- `dat` walks any directory once, streams file hashes without loading them into memory, and gives you a clear picture of what is taking up space: the largest files, duplicated content, empty files, and a full breakdown by file type. It is safe to run on huge trees, safe to pipe into other tools, and ships a polished HTML report when you want to share results.
33
+ ## Why dir-analysis-tool?
34
34
 
35
- - **Single-pass and streaming.** One filesystem walk, streaming MD5 hashing, constant memory even on multi-gigabyte trees.
36
- - **Actionable insights.** Duplicates with wasted-space totals, large and empty file detection, top-N largest, and a type breakdown.
37
- - **Pipe-friendly.** `--json` emits clean, ANSI-free output, and the progress bar auto-disables outside a TTY.
38
- - **Reports and exports.** Self-contained HTML report with charts, plus CSV export for full analysis, large files, or duplicates.
39
- - **Configurable.** Project-level `.dir-analyzer.json`, an interactive generator, and CLI flags that always win.
35
+ - **Fast.** A concurrent, bounded scanner `stat`s every file exactly once. On a 140,000-file tree it is about 3× faster than v2, and duplicate detection is about 4× faster.
36
+ - **Light.** Memory stays flat while scanning (about 9 MB retained for 140,000 files), and the package has just three direct dependencies.
37
+ - **Answers the real question.** _Which folders and files take the space?_ Then types, extensions, duplicates, stale files, and empty ones.
38
+ - **Correct.** Hard-linked data is counted once, symlinks can be followed without looping, unreadable paths are reported instead of silently skipped, and output is deterministic.
39
+ - **Built for CI.** Size budgets fail the build with exit code 2, Markdown output drops straight into a pull request or job summary, and `--json` stays clean when piped.
40
+ - **Shareable.** A single-file HTML report that works offline, plus CSV export.
41
+ - **A library too.** Every feature is available as a typed API.
40
42
 
41
- ## Table of Contents
43
+ ## Contents
42
44
 
43
45
  - [Installation](#installation)
44
- - [Quick Start](#quick-start)
45
- - [Features](#features)
46
- - [CLI Reference](#cli-reference)
47
- - [`dat analyze`](#dat-directory--dat-analyze-directory)
48
- - [`dat watch`](#dat-watch-directory)
49
- - [`dat compare`](#dat-compare-dir1-dir2)
50
- - [`dat init`](#dat-init)
51
- - [Example Output](#example-output)
52
- - [JSON Output](#json-output)
46
+ - [Quick start](#quick-start)
47
+ - [What it shows](#what-it-shows)
48
+ - [Commands](#commands): [`analyze`](#dat-analyze), [`compare`](#dat-compare), [`watch`](#dat-watch), [`init`](#dat-init)
49
+ - [Sizes, ages, and patterns](#sizes-ages-and-patterns)
50
+ - [Budgets in CI](#budgets-in-ci)
51
+ - [Output formats](#output-formats)
53
52
  - [Configuration](#configuration)
54
- - [Migrating from v1](#migrating-from-v1)
55
- - [License](#license)
53
+ - [Library API](#library-api)
54
+ - [How it works](#how-it-works)
55
+ - [Exit codes](#exit-codes)
56
+ - [Migrating from v2](#migrating-from-v2)
57
+ - [FAQ](#faq)
56
58
 
57
59
  ## Installation
58
60
 
59
- Install globally to use the `dat` command anywhere:
61
+ Requires Node.js 22.12 or later.
60
62
 
61
63
  ```bash
62
- npm install -g dir-analysis-tool
63
- # or
64
- pnpm add -g dir-analysis-tool
65
- # or
66
- yarn global add dir-analysis-tool
64
+ npm install -g dir-analysis-tool # or: pnpm add -g dir-analysis-tool
67
65
  ```
68
66
 
69
- Prefer not to install? Run it on demand with `npx`:
67
+ Two equivalent commands are installed: `dat` (short) and `dir-analysis-tool`. To run without installing:
70
68
 
71
69
  ```bash
72
- npx dir-analysis-tool # analyze the current directory
73
- npx dir-analysis-tool /path/to/scan # analyze any path
70
+ npx dir-analysis-tool ~/Downloads
74
71
  ```
75
72
 
76
- Two binaries are installed and are fully interchangeable: **`dat`** (short) and **`dir-analysis-tool`** (full). This README uses `dat` throughout.
73
+ To use it from code:
74
+
75
+ ```bash
76
+ npm install dir-analysis-tool
77
+ ```
77
78
 
78
- ## Quick Start
79
+ ## Quick start
79
80
 
80
81
  ```bash
81
- dat # analyze the current directory
82
- dat /path/to/project # analyze any path
83
- dat analyze . --duplicates # find duplicate files and wasted space
84
- dat analyze . --large-files 50 # list files larger than 50 MB
85
- dat analyze . --html # generate a shareable HTML report
86
- dat analyze . --json | jq .types # pipe-safe JSON, no ANSI codes
82
+ dat # analyze the current directory
83
+ dat ~/Downloads -l 500MB # files of 500 MB or more
84
+ dat . -d # duplicate files and reclaimable space
85
+ dat . --stale 2y # files untouched for two years
86
+ dat . -t --tree-depth 2 # a size tree, two levels deep
87
+ dat . -g -x # honor .gitignore, show extensions
88
+ dat compare dist-old dist-new # what changed between two builds
89
+ dat . -b "size<=200MB" -b "duplicates=0" # fail CI when a budget is exceeded
90
+ dat . --html report.html # a self-contained HTML report
91
+ dat . --json | jq '.largestFiles[0]' # machine-readable output
87
92
  ```
88
93
 
89
- ## Features
94
+ ## What it shows
90
95
 
91
- | Feature | Description |
92
- |---|---|
93
- | **Single-pass streaming walk** | No double I/O. Every file is `stat`'d exactly once. |
94
- | **Streaming MD5 hashing** | Duplicate detection without ever loading a file into RAM. |
95
- | **TTY-aware progress** | Live progress in interactive terminals, silent and clean when piped. |
96
- | **File-type classification** | Images, videos, audio, documents, code, archives, other. |
97
- | **Duplicate detection** | Groups identical files by content hash and reports total wasted space. |
98
- | **Large-file detection** | Configurable threshold in MB. |
99
- | **Empty-file detection** | Surface every zero-byte file. |
100
- | **Top-N largest files** | Instant disk-usage overview. |
101
- | **HTML reports** | Self-contained page with charts and tables. |
102
- | **CSV export** | Full analysis, large-file list, or duplicate groups. |
103
- | **Tree view** | Visual directory structure (up to 1,000 files). |
104
- | **Watch mode** | Debounced re-analysis on every filesystem change. |
105
- | **Directory comparison** | Side-by-side stats for two directories. |
106
- | **Config file** | `.dir-analyzer.json` for reusable defaults. |
107
- | **Interactive init** | `dat init` generates the config file with prompts. |
96
+ `dat . -g -d` on this repository:
108
97
 
109
- ## CLI Reference
98
+ ```text
99
+ dat ~/code/dir-analysis-tool 5ms
100
+
101
+ Size 1.4 MiB (1.58 MiB on disk)
102
+ Files 83
103
+ Folders 19
104
+ Skipped 22 excluded
105
+
106
+ File types
107
+ Images ██████████▌ 937 KiB 65% 1 file
108
+ Code █████▏ 458 KiB 32% 71 files
109
+ Documents ▌ 39.3 KiB 3% 8 files
110
+ Other 113 B <1% 3 files
111
+
112
+ Largest folders
113
+ 937 KiB .github/assets/ 1 file
114
+ 212 KiB src/ 38 files
115
+ 78.7 KiB src/core/ 11 files
116
+ 74.7 KiB test/ 14 files
117
+ 51.1 KiB src/cli/ 12 files
118
+
119
+ Largest files
120
+ 937 KiB .github/assets/dir-analysis-tool-banner.png
121
+ 147 KiB pnpm-lock.yaml
122
+ 20.8 KiB src/core/analyze.ts
123
+ 18.1 KiB test/integration/analyze.test.ts
124
+ 17.2 KiB src/reporters/html.ts
125
+
126
+ Duplicates none found
127
+ ```
110
128
 
111
- ### `dat [directory]` / `dat analyze [directory]`
129
+ Colors are used in interactive terminals and turned off when output is piped, when `NO_COLOR` is set, or with `--no-color`.
112
130
 
113
- Analyze a directory. This is the default command, so `dat` and `dat analyze` are equivalent. Defaults to the current working directory.
131
+ A size tree (`dat src -t --tree-depth 2`):
114
132
 
115
- ```bash
116
- dat # analyze cwd
117
- dat /path/to/project # explicit path
118
- dat analyze . --json # JSON output (no ANSI, pipe-safe)
119
- dat analyze . --tree # directory tree view
120
- dat analyze . --duplicates # detect duplicate files
121
- dat analyze . --large-files # files > 100 MB (default threshold)
122
- dat analyze . --large-files 50 # files > 50 MB
123
- dat analyze . --empty-files # detect zero-byte files
124
- dat analyze . --top-n 20 # top 20 largest files
125
- dat analyze . --html # generate an HTML report
126
- dat analyze . --csv # export to CSV
127
- dat analyze . --exclude node_modules dist coverage
128
- dat analyze . --max-depth 3 # limit scan depth
129
- dat analyze . --min-size 1000 # files >= 1 KB only
130
- dat analyze . --date-from 2024-01-01 --date-to 2024-12-31
133
+ ```text
134
+ Tree
135
+ 212 KiB .
136
+ 78.7 KiB ├─ core/
137
+ 20.8 KiB │ ├─ analyze.ts
138
+ 13.9 KiB │ ├─ scanner.ts
139
+ 10 KiB │ ├─ compare.ts
140
+ 535 B │ └─ … 1 more entry
141
+ 51.1 KiB ├─ cli/
142
+ 23.1 KiB │ ├─ commands/
143
+ 13.5 KiB │ ├─ options.ts
144
+ …
131
145
  ```
132
146
 
133
- **Options**
134
-
135
- | Flag | Description |
136
- |---|---|
137
- | `--no-recursive` | Disable recursive scan. |
138
- | `-j, --json` | JSON output (suppresses progress, safe to pipe). |
139
- | `--tree` | Show directory tree. |
140
- | `--no-types` | Hide the file-type breakdown. |
141
- | `-e, --exclude <patterns...>` | Exclude dirs/files by name or glob. |
142
- | `-l, --large-files [mb]` | Detect large files (default threshold: 100 MB). |
143
- | `-d, --duplicates` | Enable duplicate detection. |
144
- | `--empty-files` | Detect zero-byte files. |
145
- | `--top-n <n>` | Show the top N largest files. |
146
- | `--max-depth <depth>` | Limit directory depth. |
147
- | `--min-size <bytes>` | Minimum file-size filter. |
148
- | `--max-size <bytes>` | Maximum file-size filter. |
149
- | `--date-from <YYYY-MM-DD>` | Files modified on or after this date. |
150
- | `--date-to <YYYY-MM-DD>` | Files modified on or before this date. |
151
- | `--csv [filename]` | Export full analysis to CSV. |
152
- | `--csv-large [filename]` | Export the large-file list to CSV. |
153
- | `--csv-duplicates [filename]` | Export duplicate groups to CSV. |
154
- | `--html [filename]` | Generate an HTML report with charts. |
155
- | `-c, --config [path]` | Path to a config file (auto-detected by default). |
147
+ ## Commands
148
+
149
+ ### `dat analyze`
150
+
151
+ `dat [directory] [options]`. `analyze` is the default command, so `dat .` and `dat analyze .` are the same.
152
+
153
+ **Scan options** decide which files are counted. They also apply to `compare` and `watch`.
154
+
155
+ | Option | Description |
156
+ | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
157
+ | `-e, --exclude <pattern>` | Skip paths matching a gitignore-style pattern. Repeatable: `-e '*.log' -e build/`. |
158
+ | `-a, --all` | Include `.git`, `.hg`, `.svn`, and `node_modules`, which are skipped by default. |
159
+ | `-g, --gitignore` | Honor `.gitignore` files, including those above the directory and `.git/info/exclude`. |
160
+ | `--max-depth <n>` | Descend at most `n` levels. `0` scans only the top-level files. |
161
+ | `-L, --follow-symlinks` | Follow symbolic links. Cycles are detected and every file is counted once. |
162
+ | `--count-hardlinks` | Count every hard link separately. By default, shared data is counted once. |
163
+ | `--min-size <size>`, `--max-size <size>` | Only include files in a size range, such as `--min-size 1MB`. |
164
+ | `--newer-than <when>`, `--older-than <when>` | Only include files modified after or before an age (`30d`) or a date (`2024-01-31`). Dates include the whole day. |
165
+ | `-c, --config <file>` | Use this config file instead of discovering one. |
166
+ | `--no-config` | Ignore config files. |
167
+
168
+ **Report options** turn reports on or off. Largest folders, largest files, and the type breakdown are always shown.
169
+
170
+ | Option | Description |
171
+ | ----------------------------- | --------------------------------------------------------------------------------------------- |
172
+ | `-n, --top <n>` | Length of the largest folders and files lists. Default `10`; `0` hides them. |
173
+ | `-l, --large-files [size]` | List files at least this large. Default `100MiB`. |
174
+ | `-d, --duplicates` | Find files with identical contents and the space they waste. |
175
+ | `--min-duplicate-size <size>` | Ignore smaller files when looking for duplicates. |
176
+ | `--empty` | List empty files and empty folders. |
177
+ | `--stale [when]` | List files not modified since an age or date. Default `1y`. |
178
+ | `-x, --extensions` | Show the breakdown by file extension. |
179
+ | `--no-types` | Hide the breakdown by file type. |
180
+ | `-t, --tree` | Show a size tree. |
181
+ | `--tree-depth <n>` | Levels shown by `--tree`. Default `3`. |
182
+ | `-b, --budget <rule>` | Fail with exit code 2 unless the rule holds. Repeatable. See [Budgets in CI](#budgets-in-ci). |
183
+
184
+ **Output options:**
185
+
186
+ | Option | Description |
187
+ | ----------------------- | ------------------------------------------------------------------------------------ |
188
+ | `-f, --format <format>` | `pretty` (default), `json`, `markdown`, `csv`, or `html`. |
189
+ | `-j, --json` | Same as `--format json`. |
190
+ | `-o, --output <file>` | Write the report to a file instead of stdout. |
191
+ | `--html [file.html]` | Also write an HTML report. Default name `directory-analysis-<date>.html`. |
192
+ | `--csv [file.csv]` | Also write a CSV export. Default name `directory-analysis.csv`. |
193
+ | `--si` | Decimal units (kB, MB, powers of 1000) instead of binary (KiB, MiB, powers of 1024). |
194
+ | `--color`, `--no-color` | Force colors on or off. `NO_COLOR` and `FORCE_COLOR` are honored. |
195
+ | `--no-progress` | Hide the progress line. It is only ever drawn on an interactive stderr. |
196
+ | `-q, --quiet` | Print only the report and errors. |
197
+
198
+ ### `dat compare`
199
+
200
+ `dat compare <left> <right> [options]` shows what changed between two directories: files added, removed, and changed, size changes per type, and the folders that changed most. Both sides use the same scan options.
156
201
 
157
- ---
202
+ ```text
203
+ dat compare 2ms
158
204
 
159
- ### `dat watch [directory]`
205
+ left ~/build/before
206
+ right ~/build/after
160
207
 
161
- Watch a directory and re-analyze automatically (debounced 2 s) after each change. Accepts the same analysis flags as `dat analyze`.
208
+ Overview
209
+ left right change
210
+ Size 164 KiB 189 KiB +24.6 KiB (+15.0%)
211
+ On disk 172 KiB 200 KiB +28 KiB
212
+ Files 4 4 ±0
213
+ Folders 0 0 ±0
162
214
 
163
- ```bash
164
- dat watch .
165
- dat watch /path/to/project --duplicates --top-n 10
215
+ Added 1 file · 39.1 KiB
216
+ + 39.1 KiB chunk-new.js
217
+
218
+ Removed 1 file · 18.8 KiB
219
+ - 18.8 KiB index.d.ts
220
+
221
+ Changed 1 file · +4.39 KiB net
222
+ ~ +4.39 KiB cli.js 35.9 KiB → 40.3 KiB
223
+
224
+ 2 files unchanged (compared by size)
166
225
  ```
167
226
 
168
- ---
227
+ | Option | Description |
228
+ | ----------------------- | ------------------------------------------------------------------------------------------- |
229
+ | `--content` | Also compare same-sized files by content (SHA-256). By default, files are compared by size. |
230
+ | `-n, --top <n>` | Items per list. Default `10`. |
231
+ | `-f, --format <format>` | `pretty`, `json`, `markdown`, or `csv`. |
169
232
 
170
- ### `dat compare <dir1> <dir2>`
233
+ All scan and output options above are accepted too.
171
234
 
172
- Compare two directories side by side. Useful for diffing a build against its source, or comparing two versions of a project.
235
+ ### `dat watch`
236
+
237
+ `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.
173
238
 
174
239
  ```bash
175
- dat compare src/ dist/
176
- dat compare /project-v1 /project-v2 --json
240
+ dat watch . -l 1GB # keep an eye on large files
241
+ dat watch . --json | jq -c .summary # one JSON document per line (NDJSON)
177
242
  ```
178
243
 
179
- ---
244
+ | Option | Description |
245
+ | ------------------ | ---------------------------------------------------------- |
246
+ | `--debounce <ms>` | Wait this long after the last change. Default `300`. |
247
+ | `--poll <seconds>` | Re-scan on an interval instead of using filesystem events. |
248
+ | `--no-clear` | Keep earlier reports instead of clearing the screen. |
249
+
250
+ All scan, report, and output options are accepted too (`pretty` and `json` formats).
180
251
 
181
252
  ### `dat init`
182
253
 
183
- Interactively create a `.dir-analyzer.json` config file in the current directory.
254
+ `dat init [directory]` asks a few questions and writes a `.dir-analyzer.json`. Use `--yes` to write a starter file without questions, and `--force` to overwrite an existing one.
255
+
256
+ ## Sizes, ages, and patterns
257
+
258
+ **Sizes** are bytes or a number with a unit, case-insensitive:
259
+
260
+ | Input | Meaning |
261
+ | ---------------------- | ----------------------------------------------------- |
262
+ | `4096` | 4,096 bytes |
263
+ | `10k`, `10KiB` | 10 × 1,024 bytes |
264
+ | `1.5M`, `1.5MiB` | 1.5 × 1,024² bytes |
265
+ | `10kB`, `500MB`, `1GB` | Decimal: 10,000, 500,000,000, and 1,000,000,000 bytes |
266
+
267
+ **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
+
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.
270
+
271
+ ## Budgets in CI
272
+
273
+ A budget is a rule that must hold. When any budget fails, `dat` exits with code 2 and says which one failed, so the CI step fails.
184
274
 
185
275
  ```bash
186
- dat init
276
+ dat dist -b "size<=2MB" -b "largest<500kB" -b "files<200"
277
+ dat . -g -b "duplicates=0" -b "wasted<1MB"
187
278
  ```
188
279
 
189
- ## Example Output
280
+ Rules are `<metric><operator><value>`, with operators `<`, `<=`, `>`, `>=`, `=`, and `!=`.
190
281
 
191
- Running `dat analyze . --duplicates --top-n 3` on a project prints a color-coded summary:
282
+ | Metric | Meaning |
283
+ | ---------------------- | -------------------------------------------------------------------- |
284
+ | `size`, `disk` | Total apparent size, total size on disk |
285
+ | `files`, `dirs` | Number of files, number of folders |
286
+ | `largest` | Size of the largest file |
287
+ | `large` | Number of large files (turns on `--large-files`) |
288
+ | `duplicates`, `wasted` | Duplicate groups, and the space they waste (turns on `--duplicates`) |
289
+ | `empty` | Number of empty files (turns on `--empty`) |
290
+ | `stale` | Number of stale files (turns on `--stale`) |
291
+ | `errors` | Number of unreadable paths |
192
292
 
193
- ```text
194
- Directory: /Users/you/project
195
- Total Size: 48.2 MB
196
- Folders: 214
197
- Files: 1,932
198
-
199
- File Types:
200
- Images: 42
201
- Documents: 18
202
- Code: 1,806
203
- Archives: 3
204
- Other: 63
205
-
206
- Duplicates: 4 groups, 6.1 MB wasted
207
- ab12cd... (3 files, 2.0 MB each)
208
- src/assets/logo.png
209
- public/logo.png
210
- dist/logo.png
211
-
212
- Top 3 Largest Files:
213
- 1. dist/bundle.js, 5.4 MB
214
- 2. assets/demo.mp4, 3.1 MB
215
- 3. docs/manual.pdf, 1.2 MB
293
+ A GitHub Actions step that posts a report to the job summary and enforces a budget:
294
+
295
+ ```yaml
296
+ - name: Check the bundle size
297
+ run: npx dir-analysis-tool@3 dist -b "size<=2MB" -f markdown >> "$GITHUB_STEP_SUMMARY"
216
298
  ```
217
299
 
218
- > Piping the same command with `--json` produces machine-readable output with no ANSI escape codes and no progress bar, ideal for CI and scripting.
300
+ ## Output formats
219
301
 
220
- ## JSON Output
302
+ | Format | Use it for |
303
+ | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
304
+ | `pretty` | Reading in a terminal. |
305
+ | `json` | Scripts and tools. The library returns exactly this shape. |
306
+ | `markdown` | Pull request comments and CI job summaries (GitHub-flavored tables). |
307
+ | `csv` | Spreadsheets. One row per item, with a `section` column. UTF-8 with BOM. Cells that could run as formulas are neutralized. |
308
+ | `html` | Sharing. One self-contained file with inline SVG charts, light and dark themes, a path filter, and a Content-Security-Policy that blocks every network request. |
221
309
 
222
- `dat analyze . --json` emits the full result object. Optional sections (`largeFiles`, `duplicateGroups`, `duplicateStats`, `emptyFiles`, `topLargestFiles`, `treeView`) appear only when the corresponding flag is enabled.
310
+ Only the report goes to stdout. Progress, warnings, and status messages go to stderr, so `dat . --json > out.json` and pipes always get clean data.
311
+
312
+ JSON is versioned (`"schemaVersion": 3`). Sizes are raw bytes, dates are ISO 8601, and paths are relative to `root` with `/` separators on every platform. The [types](src/types.ts) document every field. In short:
223
313
 
224
314
  ```jsonc
225
315
  {
226
- "path": "/absolute/path",
227
- "totalSizeBytes": 12345678,
228
- "totalSizeFormatted": "12.3 MB",
229
- "totalSizeMB": 12.3,
230
- "folders": 42,
231
- "files": 512,
232
- "types": {
233
- "images": 10, "videos": 0, "documents": 5,
234
- "audio": 0, "code": 480, "archives": 2, "other": 15
316
+ "schemaVersion": 3,
317
+ "tool": { "name": "dir-analysis-tool", "version": "3.0.0" },
318
+ "root": "/home/me/project",
319
+ "durationMs": 42,
320
+ "summary": {
321
+ "bytes": 1468006,
322
+ "diskBytes": 1656832,
323
+ "files": 83,
324
+ "directories": 19,
325
+ "largestFileBytes": 959488,
326
+ "symlinks": 0,
327
+ "hardlinks": 0,
328
+ "excluded": 22,
329
+ "filtered": 0,
330
+ "errors": 0,
235
331
  },
236
- "largeFiles": [
237
- { "path": "...", "size": 104857600, "sizeFormatted": "105 MB" }
238
- ],
239
- "duplicateGroups": [
240
- { "hash": "...", "size": 4096, "sizeFormatted": "4.1 kB",
241
- "files": ["...", "..."], "wastedSpace": 4096, "wastedSpaceFormatted": "4.1 kB" }
242
- ],
243
- "duplicateStats": {
244
- "totalGroups": 3, "wastedSpace": 12288, "wastedSpaceFormatted": "12.3 kB"
332
+ "types": {
333
+ "code": { "files": 71, "bytes": 469000 },
334
+ "images": { "files": 1, "bytes": 959488 } /* every category */,
245
335
  },
246
- "emptyFiles": [
247
- { "path": "...", "mtime": "2024-01-01T00:00:00.000Z" }
336
+ "extensions": [{ "extension": ".png", "files": 1, "bytes": 959488 }],
337
+ "largestDirectories": [{ "path": ".github/assets", "bytes": 959488, "files": 1 }],
338
+ "largestFiles": [
339
+ {
340
+ "path": ".github/assets/banner.png",
341
+ "bytes": 959488,
342
+ "modified": "2026-07-03T17:40:00.000Z",
343
+ },
248
344
  ],
249
- "topLargestFiles": [
250
- { "path": "...", "size": 1048576, "sizeFormatted": "1.05 MB" }
251
- ],
252
- "treeView": "project\n ..."
345
+ "duplicates": { "count": 0, "files": 0, "bytes": 0, "wastedBytes": 0, "items": [] }, // with --duplicates
346
+ "errors": [],
253
347
  }
254
348
  ```
255
349
 
350
+ Optional sections appear only when their report is on: `largeFiles`, `duplicates`, `emptyFiles`, `emptyDirectories`, `staleFiles`, `tree`, and `budgets`.
351
+
256
352
  ## Configuration
257
353
 
258
- Create `.dir-analyzer.json` in your project root (or run `dat init`):
354
+ Settings can live in `.dir-analyzer.json` (or `dir-analyzer.config.json`). `dat` looks for one in the analyzed directory and then in each parent. `watch` does the same; `compare` searches from the current directory. **Command-line flags always win.** Exclude patterns and budgets from the file and from flags are combined.
259
355
 
260
356
  ```json
261
357
  {
262
- "excludePatterns": ["coverage", "tmp", "__pycache__"],
263
- "clearDefaultExclusions": false,
264
- "largeSizeThresholdMB": 100,
265
- "enableDuplicateDetection": false,
266
- "maxDepth": -1,
267
- "topN": 10,
268
- "showEmptyFiles": false
358
+ "$schema": "https://unpkg.com/dir-analysis-tool@3/schema.json",
359
+ "exclude": ["coverage/", "*.log"],
360
+ "gitignore": true,
361
+ "top": 15,
362
+ "largeFiles": "50MB",
363
+ "duplicates": true,
364
+ "budgets": ["size<=500MB", "duplicates=0"]
269
365
  }
270
366
  ```
271
367
 
272
- | Key | Type | Default | Description |
273
- |---|---|---|---|
274
- | `excludePatterns` | `string[]` | `[]` | Names or globs (for example `*.log`) to exclude, on top of the defaults. |
275
- | `clearDefaultExclusions` | `boolean` | `false` | When `true`, ignore the built-in default exclusions. |
276
- | `largeSizeThresholdMB` | `number` | `100` | Large-file threshold in MB. |
277
- | `enableDuplicateDetection` | `boolean` | `false` | Enable content-hash duplicate detection. |
278
- | `maxDepth` | `number` | `-1` | Maximum directory depth (`-1` means unlimited). |
279
- | `topN` | `number` | none | Number of largest files to report. |
280
- | `showEmptyFiles` | `boolean` | `false` | Include zero-byte files in the report. |
281
-
282
- `dat` searches for the config starting in the current directory and walking up the tree (both `.dir-analyzer.json` and `dir-analyzer.config.json` are recognized). **CLI flags always override config values.**
283
-
284
- **Default excluded directories** (unless `clearDefaultExclusions: true`): `node_modules`, `.git`, `.svn`, `.hg`, `dist`, `build`, `.cache`.
285
-
286
- ## Migrating from v1
287
-
288
- | v1 | v2 |
289
- |---|---|
290
- | `dir-analysis-tool` | `dat` (or still `dir-analysis-tool`) |
291
- | `--path <dir>` | positional argument: `dat <dir>` |
292
- | `--interactive` | `dat init` (creates config) |
293
- | `--progress` / `--no-progress` | auto-detected from TTY |
294
- | `--large-files <bytes>` | `--large-files <mb>` (value now in MB) |
295
- | `bin/` build output | `dist/` build output |
368
+ The `$schema` line gives you autocompletion and validation in most editors. Every key:
369
+
370
+ | Key | Type | Default | Flag |
371
+ | ------------------------ | ----------------------- | --------- | ------------------------------ |
372
+ | `exclude` | `string[]` | `[]` | `--exclude` |
373
+ | `defaultExcludes` | `boolean` | `true` | `--all` sets it to `false` |
374
+ | `gitignore` | `boolean` | `false` | `--gitignore` |
375
+ | `maxDepth` | `integer` | unlimited | `--max-depth` |
376
+ | `followSymlinks` | `boolean` | `false` | `--follow-symlinks` |
377
+ | `countHardlinks` | `boolean` | `false` | `--count-hardlinks` |
378
+ | `minSize`, `maxSize` | size | none | `--min-size`, `--max-size` |
379
+ | `newerThan`, `olderThan` | age or date | none | `--newer-than`, `--older-than` |
380
+ | `top` | `integer` | `10` | `--top` |
381
+ | `largeFiles` | size or `boolean` | off | `--large-files` |
382
+ | `duplicates` | `boolean` | `false` | `--duplicates` |
383
+ | `minDuplicateSize` | size | `1` | `--min-duplicate-size` |
384
+ | `empty` | `boolean` | `false` | `--empty` |
385
+ | `stale` | age, date, or `boolean` | off | `--stale` |
386
+ | `extensions` | `boolean` | `false` | `--extensions` |
387
+ | `tree`, `treeDepth` | `boolean`, `integer` | off, `3` | `--tree`, `--tree-depth` |
388
+ | `units` | `"iec"` or `"si"` | `"iec"` | `--si` |
389
+ | `budgets` | `string[]` | `[]` | `--budget` |
390
+
391
+ Invalid values stop the run with a precise message. Unknown keys produce a warning. Config files from v1 and v2 still work: their keys are translated, with a deprecation warning.
392
+
393
+ ## Library API
394
+
395
+ Everything the CLI does is available from code. Results are plain JSON-serializable objects. The package ships ESM with full TypeScript types.
396
+
397
+ ```ts
398
+ import { analyze, compare, formatBytes, renderAnalysisMarkdown } from 'dir-analysis-tool';
399
+
400
+ const result = await analyze('./dist', {
401
+ exclude: ['*.map'],
402
+ duplicates: true,
403
+ budgets: ['size<=2MB'],
404
+ });
405
+
406
+ console.log(formatBytes(result.summary.bytes)); // "1.4 MiB"
407
+ console.log(result.largestFiles[0]?.path);
408
+ console.log(result.budgets?.every((b) => b.passed));
409
+
410
+ const diff = await compare('./dist-main', './dist', { content: true });
411
+ console.log(diff.added.count, diff.changed.count, formatBytes(diff.delta.bytes));
412
+
413
+ await writeFile('report.md', renderAnalysisMarkdown(result));
414
+ ```
415
+
416
+ | Export | Purpose |
417
+ | ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
418
+ | `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
+ | `compare(left, right, options?)` | Diff two trees. |
420
+ | `listDirectories(path, options?)` | The folders a scan would enter. |
421
+ | `renderAnalysis`, `renderAnalysisMarkdown`, `renderAnalysisCsv`, `renderAnalysisHtml` | Render a result in any format. `renderComparison*` does the same for comparisons. |
422
+ | `formatBytes`, `parseSize`, `parseDuration`, `parsePointInTime` | Unit helpers. |
423
+ | `loadConfig`, `validateConfig`, `buildJsonSchema` | Config helpers. |
424
+ | `parseBudget`, `evaluateBudgets` | Budget helpers. |
425
+ | `DatError`, `AbortError` | Expected failures, and cancellation through `signal`. |
426
+
427
+ Sizes and times accept the same strings as the CLI (`minSize: '10MB'`, `modifiedAfter: '30d'`), as well as numbers and `Date`s.
428
+
429
+ ## How it works
430
+
431
+ - **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, so no tree, however wide, can exhaust file handles. Work is scheduled depth-first to keep the queue small.
432
+ - **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
+ - **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
+ - **Duplicates,** in stages so most files are never read in full:
435
+ 1. Only sizes shared by at least two files are considered. Empty files are excluded, and hard links to the same data are not copies.
436
+ 2. Files over 256 KiB are compared by a SHA-256 sample of their first and last 64 KiB.
437
+ 3. Remaining candidates are hashed in full with streaming SHA-256 and reusable buffers.
438
+ - **Disk usage.** Sizes are apparent sizes (file lengths). `On disk` is the space allocated in blocks, which is what `du` reports.
439
+ - **Determinism.** Results are sorted by size and then by path, so the same tree always produces the same output, whatever order the filesystem returned it in.
440
+
441
+ **Benchmarks** (Apple M4, warm cache, 140,237 files, 2.97 GB):
442
+
443
+ | Task | v2.0.7 | v3 |
444
+ | ------------------------ | -----: | ---------: |
445
+ | Scan | 1.74 s | **0.61 s** |
446
+ | Scan and find duplicates | 12.3 s | **2.9 s** |
447
+
448
+ Both versions found the same files, bytes, and duplicate groups. Run `pnpm bench` (or `pnpm bench <directory>`) to measure on your machine.
449
+
450
+ ## Exit codes
451
+
452
+ | Code | Meaning |
453
+ | ----- | ------------------------------------------------------------- |
454
+ | `0` | Success |
455
+ | `1` | Error: invalid option or config, missing directory, and so on |
456
+ | `2` | A budget failed |
457
+ | `130` | Interrupted (Ctrl+C) |
458
+
459
+ ## Migrating from v2
460
+
461
+ v3 is a rewrite with a new output format. Most commands keep working unchanged.
462
+
463
+ | v2 | v3 |
464
+ | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
465
+ | Node.js 18 or 20 | Node.js 22.12 or later |
466
+ | `--json` output with `totalSizeBytes`, `totalSizeFormatted`, absolute paths | `schemaVersion: 3` with `summary.bytes`, root-relative paths, and no preformatted strings |
467
+ | `-e a b c` | `-e a -e b -e c`. One pattern per flag, so the directory argument is never swallowed. |
468
+ | `--empty-files` | `--empty` (also lists empty folders). The old name still works. |
469
+ | `--date-from`, `--date-to` | `--newer-than`, `--older-than`, which also accept ages such as `30d`. The old names still work. |
470
+ | `--top-n` | `-n, --top`. The old name still works. |
471
+ | `--large-files 100` meant 100 MB | Still read as 100 MiB, with a hint to add a unit; any size such as `--large-files 1.5GB` works. |
472
+ | `--csv-large`, `--csv-duplicates` | `--csv`, which exports every section with a `section` column |
473
+ | `dist/`, `build/`, `.cache/` excluded by default | Only `.git`, `.hg`, `.svn`, and `node_modules` are; use `--gitignore` or `-e` for more |
474
+ | Sizes in decimal units (`MB`) | Binary units by default (`MiB`); `--si` switches to decimal |
475
+ | Config keys `excludePatterns`, `topN`, `largeSizeThresholdMB`, … | `exclude`, `top`, `largeFiles`, …, read with a deprecation warning |
476
+
477
+ ## FAQ
478
+
479
+ **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.
480
+
481
+ **Is it safe to run on a huge directory?** Yes. Memory does not grow with the number of files unless you ask for a report that lists them, filesystem concurrency is bounded, and unreadable paths are reported rather than fatal. Press Ctrl+C at any time.
482
+
483
+ **Does it modify anything?** No. `dat` only reads, except for report files you ask it to write.
484
+
485
+ ## Contributing
486
+
487
+ Bug reports and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for the development setup, and run `pnpm check` before opening a pull request.
296
488
 
297
489
  ## License
298
490