dir-analysis-tool 2.0.6 → 3.0.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
@@ -1,195 +1,491 @@
1
- # dir-analysis-tool
1
+ <div align="center">
2
2
 
3
- [![npm version](https://img.shields.io/npm/v/dir-analysis-tool.svg)](https://www.npmjs.com/package/dir-analysis-tool)
4
- [![CI](https://github.com/KhaledSaeed18/dir-analysis-tool/actions/workflows/ci.yml/badge.svg)](https://github.com/KhaledSaeed18/dir-analysis-tool/actions/workflows/ci.yml)
5
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
- [![Node.js Version](https://img.shields.io/node/v/dir-analysis-tool.svg)](https://nodejs.org/)
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, memory-bounded directory analysis for your terminal and CI" width="100%" />
5
+ </a>
7
6
 
8
- A fast, memory-safe CLI for directory analysis — file classification, duplicate detection, large-file identification, HTML reports, and multiple export formats.
7
+ <h1>dir-analysis-tool</h1>
9
8
 
10
- ## Quick Start
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>
11
10
 
12
- ```bash
13
- npm install -g dir-analysis-tool # install globally
11
+ <p>
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>
13
+ <a href="https://www.npmjs.com/package/dir-analysis-tool"><img src="https://shieldcn.dev/npm/dw/dir-analysis-tool.svg" alt="npm downloads" /></a>
14
+ <a href="https://github.com/KhaledSaeed18/dir-analysis-tool/actions/workflows/ci.yml"><img src="https://shieldcn.dev/github/ci/KhaledSaeed18/dir-analysis-tool.svg" alt="CI status" /></a>
15
+ <a href="https://www.npmjs.com/package/dir-analysis-tool"><img src="https://shieldcn.dev/npm/types/dir-analysis-tool.svg" alt="TypeScript types" /></a>
16
+ <a href="LICENSE"><img src="https://shieldcn.dev/npm/license/dir-analysis-tool.svg?variant=secondary" alt="License: MIT" /></a>
17
+ </p>
18
+
19
+ <p>
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/issues"><img src="https://shieldcn.dev/github/issues/KhaledSaeed18/dir-analysis-tool.svg?variant=outline" alt="GitHub issues" /></a>
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>
23
+ </p>
24
+
25
+ </div>
26
+
27
+ ---
14
28
 
15
- dat # analyze current directory
16
- dat /path/to/project # analyze any path
17
- dat analyze . --json | jq .files # pipe-safe JSON output
29
+ ```bash
30
+ npx dir-analysis-tool
18
31
  ```
19
32
 
20
- ## Features
33
+ ## Why dir-analysis-tool?
34
+
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.
21
42
 
22
- | Feature | Description |
23
- |---|---|
24
- | Single-pass streaming walk | No double I/O — files are stat'd once |
25
- | Streaming MD5 hashing | Duplicate detection without loading files into RAM |
26
- | TTY-aware progress | Progress bar only in interactive terminals; silent in pipes |
27
- | File type classification | Images, videos, audio, documents, code, archives, other |
28
- | Duplicate detection | Groups identical files by content hash; shows wasted space |
29
- | Large-file detection | Configurable threshold in MB |
30
- | Empty-file detection | Find all zero-byte files |
31
- | Top-N largest files | Quick disk usage overview |
32
- | HTML reports | Charts and tables, matrix/terminal aesthetic |
33
- | CSV export | Full analysis, large files, or duplicates |
34
- | Tree view | Visual directory structure (up to 1 000 files) |
35
- | Watch mode | Debounced re-analysis on every filesystem change |
36
- | Directory comparison | Side-by-side stats for two directories |
37
- | Config file | `.dir-analyzer.json` for default settings |
38
- | Interactive init | `dat init` creates the config file with prompts |
43
+ ## Contents
39
44
 
40
- ## CLI Reference
45
+ - [Installation](#installation)
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)
52
+ - [Configuration](#configuration)
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)
41
58
 
42
- ### `dat [directory]` / `dat analyze [directory]`
59
+ ## Installation
43
60
 
44
- Analyze a directory. Defaults to the current working directory.
61
+ Requires Node.js 22.12 or later.
45
62
 
46
63
  ```bash
47
- dat # analyze cwd
48
- dat /path/to/project # explicit path
49
- dat analyze . --json # JSON output (no ANSI, pipe-safe)
50
- dat analyze . --tree # directory tree view
51
- dat analyze . --duplicates # detect duplicate files
52
- dat analyze . --large-files # files > 100 MB
53
- dat analyze . --large-files 50 # files > 50 MB
54
- dat analyze . --empty-files # detect zero-byte files
55
- dat analyze . --top-n 20 # top 20 largest files
56
- dat analyze . --html # generate HTML report
57
- dat analyze . --csv # export to CSV
58
- dat analyze . --exclude node_modules dist coverage
59
- dat analyze . --max-depth 3 # limit scan depth
60
- dat analyze . --min-size 1000 # files >= 1 KB only
61
- dat analyze . --date-from 2024-01-01 --date-to 2024-12-31
64
+ npm install -g dir-analysis-tool # or: pnpm add -g dir-analysis-tool
62
65
  ```
63
66
 
64
- **Options**
65
-
66
- | Flag | Description |
67
- |---|---|
68
- | `--no-recursive` | Disable recursive scan |
69
- | `-j, --json` | JSON output (suppresses progress, safe to pipe) |
70
- | `--tree` | Show directory tree |
71
- | `--no-types` | Hide file-type breakdown |
72
- | `-e, --exclude <patterns...>` | Exclude dirs/files by name or glob |
73
- | `-l, --large-files [mb]` | Detect large files (default threshold: 100 MB) |
74
- | `-d, --duplicates` | Enable duplicate detection |
75
- | `--empty-files` | Detect zero-byte files |
76
- | `--top-n <n>` | Show top N largest files |
77
- | `--max-depth <depth>` | Limit directory depth |
78
- | `--min-size <bytes>` | Minimum file size filter |
79
- | `--max-size <bytes>` | Maximum file size filter |
80
- | `--date-from <YYYY-MM-DD>` | Files modified after this date |
81
- | `--date-to <YYYY-MM-DD>` | Files modified before this date |
82
- | `--csv [filename]` | Export full analysis to CSV |
83
- | `--csv-large [filename]` | Export large-file list to CSV |
84
- | `--csv-duplicates [filename]` | Export duplicate groups to CSV |
85
- | `--html [filename]` | Generate HTML report with charts |
86
- | `-c, --config [path]` | Path to config file |
67
+ Two equivalent commands are installed: `dat` (short) and `dir-analysis-tool`. To run without installing:
87
68
 
88
- ---
69
+ ```bash
70
+ npx dir-analysis-tool ~/Downloads
71
+ ```
72
+
73
+ To use it from code:
89
74
 
90
- ### `dat watch [directory]`
75
+ ```bash
76
+ npm install dir-analysis-tool
77
+ ```
91
78
 
92
- Watch a directory and re-analyze automatically (debounced 2 s) after changes.
79
+ ## Quick start
93
80
 
94
81
  ```bash
95
- dat watch .
96
- dat watch /path/to/project --duplicates --top-n 10
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
97
92
  ```
98
93
 
99
- ---
94
+ ## What it shows
95
+
96
+ `dat . -g -d` on this repository:
97
+
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
100
105
 
101
- ### `dat compare <dir1> <dir2>`
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
102
111
 
103
- Compare two directories side by side.
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
+ ```
128
+
129
+ Colors are used in interactive terminals and turned off when output is piped, when `NO_COLOR` is set, or with `--no-color`.
130
+
131
+ A size tree (`dat src -t --tree-depth 2`):
132
+
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
+ …
145
+ ```
146
+
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.
201
+
202
+ ```text
203
+ dat compare 2ms
204
+
205
+ left ~/build/before
206
+ right ~/build/after
207
+
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
214
+
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)
225
+ ```
226
+
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`. |
232
+
233
+ All scan and output options above are accepted too.
234
+
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.
104
238
 
105
239
  ```bash
106
- dat compare src/ dist/
107
- 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)
108
242
  ```
109
243
 
110
- ---
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).
111
251
 
112
252
  ### `dat init`
113
253
 
114
- 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.
115
274
 
116
275
  ```bash
117
- dat init
276
+ dat dist -b "size<=2MB" -b "largest<500kB" -b "files<200"
277
+ dat . -g -b "duplicates=0" -b "wasted<1MB"
118
278
  ```
119
279
 
120
- ---
280
+ Rules are `<metric><operator><value>`, with operators `<`, `<=`, `>`, `>=`, `=`, and `!=`.
121
281
 
122
- ## Configuration
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 |
123
292
 
124
- Create `.dir-analyzer.json` in your project root (or run `dat init`):
293
+ A GitHub Actions step that posts a report to the job summary and enforces a budget:
125
294
 
126
- ```json
127
- {
128
- "excludePatterns": ["coverage", "tmp", "__pycache__"],
129
- "clearDefaultExclusions": false,
130
- "largeSizeThresholdMB": 100,
131
- "enableDuplicateDetection": false,
132
- "maxDepth": -1,
133
- "topN": 10,
134
- "showEmptyFiles": false
135
- }
295
+ ```yaml
296
+ - name: Check the bundle size
297
+ run: npx dir-analysis-tool@3 dist -b "size<=2MB" -f markdown >> "$GITHUB_STEP_SUMMARY"
136
298
  ```
137
299
 
138
- `dat` searches for this file starting in the current directory and walking up the tree. CLI flags always override config values.
300
+ ## Output formats
139
301
 
140
- **Default excluded directories** (unless `clearDefaultExclusions: true`): `node_modules`, `.git`, `.svn`, `.hg`, `dist`, `build`, `.cache`
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. |
141
309
 
142
- ---
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.
143
311
 
144
- ## JSON Output
145
-
146
- All fields from a `dat analyze . --json` call:
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:
147
313
 
148
314
  ```jsonc
149
315
  {
150
- "path": "/absolute/path",
151
- "totalSizeBytes": 12345678,
152
- "totalSizeFormatted": "12.3 MB",
153
- "totalSizeMB": 12.3,
154
- "folders": 42,
155
- "files": 512,
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,
331
+ },
156
332
  "types": {
157
- "images": 10, "videos": 0, "documents": 5,
158
- "audio": 0, "code": 480, "archives": 2, "other": 15
333
+ "code": { "files": 71, "bytes": 469000 },
334
+ "images": { "files": 1, "bytes": 959488 } /* every category */,
159
335
  },
160
- "largeFiles": [{ "path": "...", "size": 104857600, "sizeFormatted": "105 MB" }],
161
- "duplicateGroups": [{ "hash": "...", "size": 4096, "files": ["...", "..."], "wastedSpace": 4096 }],
162
- "duplicateStats": { "totalGroups": 3, "wastedSpace": 12288, "wastedSpaceFormatted": "12.3 kB" },
163
- "emptyFiles": [{ "path": "...", "mtime": "2024-01-01T00:00:00.000Z" }],
164
- "topLargestFiles": [{ "path": "...", "size": 1048576, "sizeFormatted": "1.05 MB" }],
165
- "treeView": "📁 project\n└── ..."
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
+ },
344
+ ],
345
+ "duplicates": { "count": 0, "files": 0, "bytes": 0, "wastedBytes": 0, "items": [] }, // with --duplicates
346
+ "errors": [],
166
347
  }
167
348
  ```
168
349
 
169
- ---
350
+ Optional sections appear only when their report is on: `largeFiles`, `duplicates`, `emptyFiles`, `emptyDirectories`, `staleFiles`, `tree`, and `budgets`.
170
351
 
171
- ## Migrating from v1
352
+ ## Configuration
172
353
 
173
- | v1 | v2 |
174
- |---|---|
175
- | `dir-analysis-tool` | `dat` (or still `dir-analysis-tool`) |
176
- | `--path <dir>` | positional argument: `dat <dir>` |
177
- | `--interactive` | `dat init` (creates config) |
178
- | `--progress` / `--no-progress` | auto-detected from TTY |
179
- | `--large-files <bytes>` | `--large-files <mb>` (value now in MB) |
180
- | `bin/` build output | `dist/` build output |
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.
181
355
 
182
- ---
356
+ ```json
357
+ {
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"]
365
+ }
366
+ ```
367
+
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.
183
480
 
184
- ## Requirements
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.
185
482
 
186
- - Node.js >= 18.0.0
187
- - pnpm (for development)
483
+ **Does it modify anything?** No. `dat` only reads, except for report files you ask it to write.
188
484
 
189
485
  ## Contributing
190
486
 
191
- See [CONTRIBUTING.md](CONTRIBUTING.md).
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.
192
488
 
193
489
  ## License
194
490
 
195
- [MIT](LICENSE)
491
+ [MIT](LICENSE), by [Khaled Saeed](https://github.com/KhaledSaeed18).