dustclaw 0.1.2 → 0.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
@@ -14,13 +14,14 @@ It scans your disk, shows you what is big, and knows where macOS and dev tools h
14
14
 
15
15
  ## Why Dustclaw Exists
16
16
 
17
- There are excellent disk space tools out there — [dust](https://github.com/bootandy/dust) and [dua-cli](https://github.com/Byron/dua-cli) are blazing fast Rust scanners, [duf](https://github.com/muesli/duf) is a beautiful Go replacement for `df`, and [npkill](https://github.com/voidcosmos/npkill) is great for cleaning up `node_modules`.
17
+ There are excellent disk space tools out there: [dust](https://github.com/bootandy/dust) and [dua-cli](https://github.com/Byron/dua-cli) are blazing fast Rust scanners, [duf](https://github.com/muesli/duf) is a beautiful Go replacement for `df`, and [npkill](https://github.com/voidcosmos/npkill) is great for cleaning up `node_modules`.
18
18
 
19
19
  Dustclaw takes a different angle. It focuses on dev-aware scanning and lives in the npm ecosystem:
20
20
 
21
- - **Dev-aware scanning** — knows about Xcode DerivedData, Docker data, Homebrew caches, Playwright browsers, Gradle, Maven, Cargo, and dozens of other known space wasters
22
- - **Cache breakdown** — shows every application cache individually instead of one mystery lump
23
- - **npm-installable** — `npx dustclaw` and you are running
21
+ - **Dev-aware scanning**: knows about Xcode DerivedData, Docker data, Homebrew caches, Playwright browsers, Gradle, Maven, Cargo, and dozens of other known space wasters
22
+ - **Cache breakdown**: shows every application cache individually instead of one mystery lump
23
+ - **Safe cleanup**: separates what is safe to delete from what needs manual review, prompts per item
24
+ - **npm-installable**: run `npx dustclaw` and you are up
24
25
 
25
26
  ## 10-Second Proof
26
27
 
@@ -28,38 +29,64 @@ Dustclaw takes a different angle. It focuses on dev-aware scanning and lives in
28
29
  npx dustclaw wasteland
29
30
  ```
30
31
 
31
- ```text
32
+ ```
32
33
  Wasteland Report
33
34
 
34
35
  Known space wasters:
35
36
 
36
- ┌────────────────────────────────┬───────────┬──────────────────────────────────────────────────┐
37
- │ Name │ Size │ Path │
38
- ┼────────────────────────────────┼───────────┼──────────────────────────────────────────────────┼
39
- │ Docker Desktop │ 460.5 GB │ ~/Library/Containers/com.docker.docker/Data │
40
- │ npm Cache │ 14.1 GB │ ~/.npm/_cacache │
41
- │ Cache: Cursor Updates │ 7.8 GB │ ~/Library/Caches/com.todesktop.230313mzl4w4u92 │
42
- │ Android Emulators │ 7.8 GB │ ~/.android/avd │
43
- │ Cache: Google/Chrome │ 3.9 GB │ ~/Library/Caches/Google │
44
- │ Homebrew Cache │ 3.4 GB │ ~/Library/Caches/Homebrew │
45
- │ Gradle Cache │ 2.5 GB │ ~/.gradle/caches │
46
- │ pnpm Store │ 2.4 GB │ ~/Library/pnpm/store │
47
- │ Cache: Playwright Browsers │ 2.2 GB │ ~/Library/Caches/ms-playwright │
48
- │ Cache: Spotify │ 1.3 GB │ ~/Library/Caches/com.spotify.client │
49
- └────────────────────────────────┴───────────┴──────────────────────────────────────────────────┘
37
+ ┌─────────────────────────────────────┬──────────┬───────────────────────────────────────────────────────────────────┐
38
+ │ Name │ Size │ Path │
39
+ ┼─────────────────────────────────────┼──────────┼───────────────────────────────────────────────────────────────────┼
40
+ │ Docker Desktop │ 50.9 GB │ /Users/you/Library/Containers/com.docker.docker/Data │
41
+ │ Android Emulators │ 7.7 GB │ /Users/you/.android/avd │
42
+ │ Puppeteer Cache │ 4.0 GB │ /Users/you/.cache/puppeteer │
43
+ │ Cache: Google/Chrome │ 4.0 GB │ /Users/you/Library/Caches/Google │
44
+ │ pnpm Store │ 2.7 GB │ /Users/you/Library/pnpm/store │
45
+ │ Playwright Browsers │ 2.2 GB │ /Users/you/Library/Caches/ms-playwright │
46
+ │ Cache: com.microsoft.VSCode.ShipIt │ 1.7 GB │ /Users/you/Library/Caches/com.microsoft.VSCode.ShipIt │
47
+ │ Cypress Cache │ 1.3 GB │ /Users/you/Library/Caches/Cypress │
48
+ │ Gradle Cache │ 2.5 GB │ /Users/you/.gradle/caches │
49
+ │ Maven Cache │ 332.6 MB │ /Users/you/.m2/repository │
50
+ └─────────────────────────────────────┴──────────┴───────────────────────────────────────────────────────────────────┘
51
+
52
+ Total reclaimable: 81.4 GB
53
+
54
+ Scan saved. Run dustclaw clean to remove safe items.
55
+ ```
56
+
57
+ Then clean what is safe:
50
58
 
51
- Total reclaimable: 515.1 GB
59
+ ```bash
60
+ npx dustclaw clean --force
52
61
  ```
53
62
 
54
- That is real output from a real machine.
63
+ ```
64
+ Safe to clean:
65
+
66
+ ┌──────────────────────┬────────┬──────────────────────────────────┐
67
+ │ Name │ Size │ Path │
68
+ ┼──────────────────────┼────────┼──────────────────────────────────┼
69
+ │ Gradle Cache │ 2.5 GB │ /Users/you/.gradle/caches │
70
+ │ Puppeteer Cache │ 4.0 GB │ /Users/you/.cache/puppeteer │
71
+ │ Playwright Browsers │ 2.2 GB │ /Users/you/Library/Caches/ms-... │
72
+ └──────────────────────┴────────┴──────────────────────────────────┘
73
+
74
+ WARNING: Deletion is permanent. There is no undo.
75
+
76
+ Delete Gradle Cache (2.5 GB)? [y/N] y
77
+ Deleted: /Users/you/.gradle/caches
78
+
79
+ Freed: 2.5 GB
80
+ ```
55
81
 
56
82
  ## Commands
57
83
 
58
84
  | Command | What it does |
59
85
  |---------|-------------|
60
- | `dustclaw` | Quick overview — disk usage, free space, top 10 biggest items |
61
- | `dustclaw scan [path]` | Deep scan — ranked list of largest files and folders |
62
- | `dustclaw wasteland` | Finds known space wasters — caches, build artifacts, Trash, Docker |
86
+ | `dustclaw` | Quick overview: disk usage, free space, top 10 biggest items |
87
+ | `dustclaw scan [path]` | Deep scan: ranked list of largest files and folders |
88
+ | `dustclaw wasteland` | Finds known space wasters: caches, build artifacts, Trash, Docker |
89
+ | `dustclaw clean` | Clean safe items from last wasteland scan (dry run by default) |
63
90
 
64
91
  ## Requirements
65
92
 
@@ -104,41 +131,123 @@ Scans known locations where dev tools and macOS pile up gigabytes:
104
131
 
105
132
  - Xcode DerivedData, archives, device support
106
133
  - Docker Desktop data
107
- - Homebrew, npm, pnpm, Yarn, pip caches
108
- - Gradle, Maven, Cargo caches
134
+ - Homebrew, npm, pnpm, Yarn, Bun caches
135
+ - Gradle, Maven, Cargo, Go, pip, Poetry, Composer caches
109
136
  - Android emulators, iOS simulators
110
- - Playwright and Cypress browsers
137
+ - Playwright, Cypress, Puppeteer browsers
138
+ - Terraform, Helm plugin caches
139
+ - Ollama and Hugging Face model caches
111
140
  - Every application cache in `~/Library/Caches`, broken down individually
112
- - Trash
141
+ - Trash and system logs
113
142
 
114
143
  ```bash
115
144
  dustclaw wasteland
116
145
  dustclaw wasteland --node-modules ~/Projects # also find all node_modules
117
146
  ```
118
147
 
148
+ ### Clean
149
+
150
+ Reads the last wasteland scan and removes safe items. Dry run by default.
151
+
152
+ ```bash
153
+ dustclaw clean # preview what would be removed
154
+ dustclaw clean --force # delete safe items, prompts per item
155
+ dustclaw clean --only "gradle cache" # filter to a specific entry
156
+ dustclaw clean --only playwright --force
157
+ ```
158
+
159
+ Items marked `safe: false` (Docker, Android Emulators, pnpm Store) are always shown but never auto-deleted. To override, add to `~/.dustclaw.json`:
160
+
161
+ ```json
162
+ {
163
+ "overrides": {
164
+ "pnpm Store": { "safe": true }
165
+ }
166
+ }
167
+ ```
168
+
119
169
  ## Flags
120
170
 
121
171
  | Flag | Available on | What it does |
122
172
  |------|-------------|-------------|
123
173
  | `--json` | all commands | Output as JSON for scripting |
124
- | `--older-than <age>` | scan | Filter by age — `30d`, `6m`, `1y` |
174
+ | `--older-than <age>` | scan | Filter by age: `30d`, `6m`, `1y` |
125
175
  | `-n, --top <count>` | overview, scan | Number of items to show |
126
176
  | `-d, --depth <depth>` | scan | Max directory depth |
127
177
  | `--files-only` | scan | Show only files |
128
178
  | `--dirs-only` | scan | Show only directories |
129
179
  | `--node-modules <path>` | wasteland | Also search for node_modules recursively |
180
+ | `--force` | clean | Actually delete (prompts per item) |
181
+ | `--only <name>` | clean | Filter to entries matching this name |
182
+
183
+ ## Configuration
184
+
185
+ Dustclaw reads `~/.dustclaw.json` for user overrides. All defaults can be changed:
186
+
187
+ ```json
188
+ {
189
+ "minCacheSizeMb": 50,
190
+ "staleThresholdHours": 24,
191
+ "nodeModulesMaxDepth": 5,
192
+ "encoding": "utf-8",
193
+ "scanDepth": 3,
194
+ "overviewTopCount": 10,
195
+ "scanTopCount": 20,
196
+ "overrides": {
197
+ "pnpm Store": { "safe": true }
198
+ },
199
+ "targets": [
200
+ {
201
+ "name": "My Build Cache",
202
+ "path": "~/work/build-cache",
203
+ "safe": true
204
+ }
205
+ ]
206
+ }
207
+ ```
208
+
209
+ ## Storage
210
+
211
+ Dustclaw writes two things to your home directory:
212
+
213
+ | Path | What it is |
214
+ |------|------------|
215
+ | `~/.dustclaw/last-scan.json` | Last wasteland scan result, read by `clean` |
216
+ | `~/.dustclaw.json` | Your config overrides (optional, you create this) |
217
+
218
+ Nothing else is written. To reset state, delete `~/.dustclaw/last-scan.json`.
219
+
220
+ ## Project Structure
221
+
222
+ ```
223
+ src/
224
+ commands/ # CLI commands (overview, scan, wasteland, clean)
225
+ data/
226
+ config.json # default configuration (minCacheSizeMb, scanDepth, encoding, ...)
227
+ targets.json # known waste targets and cache display names
228
+ utils/
229
+ config.ts # loads and merges config.json with ~/.dustclaw.json
230
+ disk.ts # disk info via df
231
+ format.ts # table rendering and size formatting
232
+ scan.ts # recursive directory walker and dirSize
233
+ state.ts # persists last wasteland scan to ~/.dustclaw/last-scan.json
234
+ wasteland.ts # finds known waste targets and Library/Caches entries
235
+ index.ts # CLI entry point
236
+ ```
237
+
238
+ All behavior is driven by `src/data/config.json` and `src/data/targets.json`. To add a new waste target or change defaults, edit those files — no code changes needed.
130
239
 
131
240
  ## Standing on the Shoulders of Giants
132
241
 
133
242
  Dustclaw exists because of the excellent work done by these projects:
134
243
 
135
- - [dust](https://github.com/bootandy/dust) — fast, intuitive disk usage viewer written in Rust. If raw scanning speed is what you need, dust is hard to beat.
136
- - [duf](https://github.com/muesli/duf) — a modern `df` replacement written in Go. Beautiful output and JSON support.
137
- - [dua-cli](https://github.com/Byron/dua-cli) — parallel disk usage analyzer with interactive deletion, written in Rust. Maxes out your SSD.
138
- - [npkill](https://github.com/voidcosmos/npkill) — finds and deletes `node_modules` folders. Simple, effective, widely used.
139
- - [space-hogs](https://github.com/dylang/space-hogs) — discovers surprisingly large directories from the command line.
244
+ - [dust](https://github.com/bootandy/dust): fast, intuitive disk usage viewer written in Rust. If raw scanning speed is what you need, dust is hard to beat.
245
+ - [duf](https://github.com/muesli/duf): a modern `df` replacement written in Go. Beautiful output and JSON support.
246
+ - [dua-cli](https://github.com/Byron/dua-cli): parallel disk usage analyzer with interactive deletion, written in Rust. Maxes out your SSD.
247
+ - [npkill](https://github.com/voidcosmos/npkill): finds and deletes `node_modules` folders. Simple, effective, widely used.
248
+ - [space-hogs](https://github.com/dylang/space-hogs): discovers surprisingly large directories from the command line.
140
249
 
141
- These tools do what they do very well. Dustclaw does not try to outperform them on raw speed. Instead, it brings dev-aware scanning and cache breakdown to the npm ecosystem — things those tools were not built to do.
250
+ These tools do what they do very well. Dustclaw does not try to outperform them on raw speed. Instead, it brings dev-aware scanning and cache breakdown to the npm ecosystem, filling a gap those tools were not built to fill.
142
251
 
143
252
  ## Development
144
253
 
@@ -153,15 +262,21 @@ pnpm lint
153
262
 
154
263
  ## Roadmap
155
264
 
156
- - **watch** — track disk usage over time, spot trends before you run out of space
157
- - **duplicates** — find duplicate large files by hash
158
- - **clean** — interactive cleanup with dry-run safety
265
+ - **spinner**: progress indicator during slow scans
266
+ - **watch**: track disk usage over time, spot trends before you run out of space
267
+ - **duplicates**: find duplicate large files by hash
159
268
 
160
269
  ## Related
161
270
 
162
- - 🦀 [Feedclaw](https://github.com/psandis/feedclaw) — RSS/Atom feed reader and AI digest CLI
163
- - 🦀 [Driftclaw](https://github.com/psandis/driftclaw) — Deployment drift detection across environments
164
- - 🦀 [OpenClaw](https://github.com/openclaw/openclaw) — Personal AI assistant
271
+ - 🦀 [Feedclaw](https://github.com/psandis/feedclaw): RSS/Atom feed reader and AI digest CLI
272
+ - 🦀 [Driftclaw](https://github.com/psandis/driftclaw): deployment drift detection across environments
273
+ - 🦀 [Dietclaw](https://github.com/psandis/dietclaw): codebase health monitor for size, bloat, and dependency weight
274
+ - 🦀 [Wirewatch](https://github.com/psandis/wirewatch): network traffic monitoring CLI with AI-assisted anomaly detection
275
+ - 🦀 [Mymailclaw](https://github.com/psandis/mymailclaw): email scanner, categorizer, and cleaner CLI
276
+ - 🦀 [Asciiclaw](https://github.com/psandis/asciiclaw): convert images to ASCII art in the terminal
277
+ - 🦀 [Unasciiclaw](https://github.com/psandis/unasciiclaw): convert ASCII art back to an image
278
+ - 🦀 [psclawmcp](https://github.com/psandis/psclawmcp): MCP server exposing all claw tools to AI assistants
279
+ - 🦀 [OpenClaw](https://github.com/openclaw/openclaw): personal AI assistant
165
280
 
166
281
  ## License
167
282
 
@@ -0,0 +1,6 @@
1
+ interface CleanOptions {
2
+ force?: boolean;
3
+ only?: string;
4
+ }
5
+ export declare function clean(opts: CleanOptions): Promise<void>;
6
+ export {};
@@ -0,0 +1,75 @@
1
+ import { rmSync } from "node:fs";
2
+ import { createInterface } from "node:readline";
3
+ import chalk from "chalk";
4
+ import { boxTable, colorSize, formatSize } from "../utils/format.js";
5
+ import { loadLastScan, scanAgePath, staleThresholdMs } from "../utils/state.js";
6
+ function ask(question) {
7
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
8
+ return new Promise((resolve) => {
9
+ rl.question(question, (answer) => {
10
+ rl.close();
11
+ resolve(answer.trim().toLowerCase());
12
+ });
13
+ });
14
+ }
15
+ function deleteEntry(entry) {
16
+ rmSync(entry.path, { recursive: true, force: true });
17
+ }
18
+ export async function clean(opts) {
19
+ const state = loadLastScan();
20
+ if (!state) {
21
+ console.log(chalk.yellow("\n No scan found. Run dustclaw wasteland first.\n"));
22
+ return;
23
+ }
24
+ const ageMs = scanAgePath(state);
25
+ if (ageMs > staleThresholdMs()) {
26
+ const hours = Math.floor(ageMs / (60 * 60 * 1000));
27
+ console.log(chalk.yellow(`\n Scan is ${hours}h old. Run dustclaw wasteland again for fresh results.\n`));
28
+ }
29
+ const filter = opts.only?.toLowerCase();
30
+ const safe = state.entries.filter((e) => e.safe && (!filter || e.name.toLowerCase().includes(filter)));
31
+ const unsafe = state.entries.filter((e) => !e.safe && (!filter || e.name.toLowerCase().includes(filter)));
32
+ if (filter && safe.length === 0 && unsafe.length === 0) {
33
+ console.log(chalk.yellow(`\n No entries matching "${opts.only}".\n`));
34
+ return;
35
+ }
36
+ if (safe.length === 0 && unsafe.length === 0) {
37
+ console.log(chalk.green("\n Nothing to clean.\n"));
38
+ return;
39
+ }
40
+ if (safe.length > 0) {
41
+ const safeTotal = safe.reduce((sum, e) => sum + e.size, 0);
42
+ console.log(chalk.bold("\n Safe to clean:\n"));
43
+ console.log(boxTable(["Name", "Size", "Path"], safe.map((e) => [e.name, colorSize(e.size), e.path])));
44
+ console.log(chalk.bold(`\n Total: ${colorSize(safeTotal)}\n`));
45
+ }
46
+ else {
47
+ console.log(chalk.yellow("\n No safely cleanable items found.\n"));
48
+ }
49
+ if (unsafe.length > 0) {
50
+ console.log(chalk.red.bold(" Manual only (cannot be auto-cleaned):\n"));
51
+ console.log(boxTable(["Name", "Size", "Path"], unsafe.map((e) => [e.name, colorSize(e.size), e.path])));
52
+ console.log(chalk.gray("\n These contain user data and must be cleaned manually.\n"));
53
+ console.log(chalk.gray(" To include them, set safe: true in ~/.dustclaw.json overrides.\n"));
54
+ }
55
+ if (safe.length === 0)
56
+ return;
57
+ if (!opts.force) {
58
+ console.log(chalk.yellow(" Dry run. Add --force to actually delete safe items.\n"));
59
+ return;
60
+ }
61
+ console.log(chalk.red.bold(" WARNING: Deletion is permanent. There is no undo.\n"));
62
+ let freed = 0;
63
+ for (const entry of safe) {
64
+ const answer = await ask(` Delete ${chalk.bold(entry.name)} (${formatSize(entry.size)})? [y/N] `);
65
+ if (answer === "y") {
66
+ deleteEntry(entry);
67
+ freed += entry.size;
68
+ console.log(chalk.green(` Deleted: ${entry.path}`));
69
+ }
70
+ else {
71
+ console.log(chalk.gray(` Skipped: ${entry.path}`));
72
+ }
73
+ }
74
+ console.log(chalk.bold(`\n Freed: ${colorSize(freed)}\n`));
75
+ }
@@ -1,13 +1,15 @@
1
1
  import { resolve } from "node:path";
2
2
  import chalk from "chalk";
3
+ import { resolveConfig } from "../utils/config.js";
3
4
  import { getDiskInfo } from "../utils/disk.js";
4
5
  import { boxTable, colorSize, formatPercent, formatSize } from "../utils/format.js";
5
6
  import { scanDir } from "../utils/scan.js";
6
7
  export function overview(opts) {
8
+ const { overviewDepth } = resolveConfig();
7
9
  const count = Number.parseInt(opts.top, 10);
8
10
  const targetPath = resolve(opts.path);
9
11
  const disks = getDiskInfo();
10
- const entries = scanDir(targetPath, { depth: 1 });
12
+ const entries = scanDir(targetPath, { depth: overviewDepth });
11
13
  const topEntries = entries.sort((a, b) => b.size - a.size).slice(0, count);
12
14
  if (opts.json) {
13
15
  console.log(JSON.stringify({
@@ -2,5 +2,5 @@ interface WastelandOptions {
2
2
  nodeModules?: string;
3
3
  json?: boolean;
4
4
  }
5
- export declare function wasteland(opts: WastelandOptions): void;
5
+ export declare function wasteland(opts: WastelandOptions): Promise<void>;
6
6
  export {};
@@ -1,8 +1,9 @@
1
1
  import { resolve } from "node:path";
2
2
  import chalk from "chalk";
3
3
  import { boxTable, colorSize, formatSize } from "../utils/format.js";
4
+ import { saveLastScan } from "../utils/state.js";
4
5
  import { findNodeModules, findWaste } from "../utils/wasteland.js";
5
- export function wasteland(opts) {
6
+ export async function wasteland(opts) {
6
7
  const waste = findWaste();
7
8
  let nmEntries = [];
8
9
  if (opts.nodeModules) {
@@ -27,6 +28,7 @@ export function wasteland(opts) {
27
28
  console.log(chalk.green("\n No wasteland found. Your disk is clean!\n"));
28
29
  return;
29
30
  }
31
+ saveLastScan(allEntries);
30
32
  console.log(chalk.bold("\n Wasteland Report\n"));
31
33
  if (waste.length > 0) {
32
34
  console.log(chalk.bold(" Known space wasters:\n"));
@@ -40,4 +42,5 @@ export function wasteland(opts) {
40
42
  console.log(boxTable(["Size", "Path"], nmRows));
41
43
  }
42
44
  console.log(chalk.bold(`\n Total reclaimable: ${colorSize(totalSize)}\n`));
45
+ console.log(chalk.gray(" Scan saved. Run dustclaw clean to remove safe items.\n"));
43
46
  }
package/dist/index.js CHANGED
@@ -1,25 +1,31 @@
1
1
  #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
2
4
  import { Command } from "commander";
5
+ import { clean } from "./commands/clean.js";
3
6
  import { overview } from "./commands/overview.js";
4
7
  import { scan } from "./commands/scan.js";
5
8
  import { wasteland } from "./commands/wasteland.js";
9
+ import { resolveConfig } from "./utils/config.js";
10
+ const { version } = JSON.parse(readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf-8"));
11
+ const { overviewTopCount, scanTopCount, scanDepth } = resolveConfig();
6
12
  const program = new Command();
7
13
  program
8
14
  .name("dustclaw")
9
15
  .description("Disk space monitoring, analysis, and cleanup CLI")
10
- .version("0.1.0");
16
+ .version(version);
11
17
  program
12
18
  .command("overview", { isDefault: true })
13
19
  .description("Quick overview: disk usage, free space, top 10 biggest dirs")
14
- .option("-n, --top <count>", "Number of top items to show", "10")
20
+ .option("-n, --top <count>", "Number of top items to show", String(overviewTopCount))
15
21
  .option("-p, --path <path>", "Path to analyze", ".")
16
22
  .option("--json", "Output as JSON")
17
23
  .action(overview);
18
24
  program
19
25
  .command("scan [path]")
20
26
  .description("Deep scan: ranked list of largest files and folders")
21
- .option("-n, --top <count>", "Number of top items to show", "20")
22
- .option("-d, --depth <depth>", "Max directory depth", "3")
27
+ .option("-n, --top <count>", "Number of top items to show", String(scanTopCount))
28
+ .option("-d, --depth <depth>", "Max directory depth", String(scanDepth))
23
29
  .option("--older-than <age>", "Filter by age (e.g. 30d, 6m, 1y)")
24
30
  .option("--files-only", "Show only files, not directories")
25
31
  .option("--dirs-only", "Show only directories, not files")
@@ -31,4 +37,10 @@ program
31
37
  .option("--node-modules <path>", "Also search for node_modules under this path")
32
38
  .option("--json", "Output as JSON")
33
39
  .action(wasteland);
40
+ program
41
+ .command("clean")
42
+ .description("Clean safe space wasters (dry run by default, use --force to delete)")
43
+ .option("--only <name>", "Filter to entries matching this name (case-insensitive)")
44
+ .option("--force", "Actually delete (irreversible, prompts per item)")
45
+ .action(clean);
34
46
  program.parse();
@@ -0,0 +1,26 @@
1
+ export interface TargetDef {
2
+ name: string;
3
+ path: string;
4
+ description: string;
5
+ platform: "mac" | "linux" | "all";
6
+ safe: boolean;
7
+ }
8
+ export interface DustclawConfig {
9
+ minCacheSizeMb: number;
10
+ minCacheSize: number;
11
+ staleThresholdHours: number;
12
+ staleThresholdMs: number;
13
+ nodeModulesMaxDepth: number;
14
+ encoding: BufferEncoding;
15
+ scanDepth: number;
16
+ overviewDepth: number;
17
+ overviewTopCount: number;
18
+ scanTopCount: number;
19
+ blockSize: number;
20
+ cachesPath: string;
21
+ cacheSkipList: string[];
22
+ opaqueDirectories: string[];
23
+ }
24
+ export declare function resolveConfig(): DustclawConfig;
25
+ export declare function resolveCacheNames(): Record<string, string>;
26
+ export declare function resolveTargets(): TargetDef[];
@@ -0,0 +1,68 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ const USER_CONFIG_PATH = join(homedir(), ".dustclaw.json");
6
+ function loadDefaultConfig() {
7
+ const file = fileURLToPath(new URL("../data/config.json", import.meta.url));
8
+ return JSON.parse(readFileSync(file, "utf-8"));
9
+ }
10
+ function loadUserConfig() {
11
+ if (!existsSync(USER_CONFIG_PATH))
12
+ return {};
13
+ try {
14
+ return JSON.parse(readFileSync(USER_CONFIG_PATH, "utf-8"));
15
+ }
16
+ catch {
17
+ return {};
18
+ }
19
+ }
20
+ export function resolveConfig() {
21
+ const defaults = loadDefaultConfig();
22
+ const user = loadUserConfig();
23
+ const minCacheSizeMb = user.minCacheSizeMb ?? defaults.minCacheSizeMb;
24
+ const staleThresholdHours = user.staleThresholdHours ?? defaults.staleThresholdHours;
25
+ return {
26
+ minCacheSizeMb,
27
+ minCacheSize: minCacheSizeMb * 1024 * 1024,
28
+ staleThresholdHours,
29
+ staleThresholdMs: staleThresholdHours * 60 * 60 * 1000,
30
+ nodeModulesMaxDepth: user.nodeModulesMaxDepth ?? defaults.nodeModulesMaxDepth,
31
+ encoding: user.encoding ?? defaults.encoding,
32
+ scanDepth: user.scanDepth ?? defaults.scanDepth,
33
+ overviewDepth: user.overviewDepth ?? defaults.overviewDepth,
34
+ overviewTopCount: user.overviewTopCount ?? defaults.overviewTopCount,
35
+ scanTopCount: user.scanTopCount ?? defaults.scanTopCount,
36
+ blockSize: user.blockSize ?? defaults.blockSize,
37
+ cachesPath: user.cachesPath ?? defaults.cachesPath,
38
+ cacheSkipList: user.cacheSkipList ?? defaults.cacheSkipList,
39
+ opaqueDirectories: user.opaqueDirectories ?? defaults.opaqueDirectories,
40
+ };
41
+ }
42
+ function loadTargetsFile() {
43
+ const file = fileURLToPath(new URL("../data/targets.json", import.meta.url));
44
+ return JSON.parse(readFileSync(file, "utf-8"));
45
+ }
46
+ export function resolveCacheNames() {
47
+ return loadTargetsFile().cacheNames;
48
+ }
49
+ export function resolveTargets() {
50
+ const platform = process.platform === "darwin" ? "mac" : "linux";
51
+ const base = loadTargetsFile().targets.filter((t) => t.platform === platform || t.platform === "all");
52
+ const user = loadUserConfig();
53
+ const overrides = user.overrides ?? {};
54
+ const merged = base.map((t) => {
55
+ const expanded = { ...t, path: t.path.replace(/^~/, homedir()) };
56
+ return overrides[t.name] !== undefined
57
+ ? { ...expanded, safe: overrides[t.name].safe }
58
+ : expanded;
59
+ });
60
+ const custom = (user.targets ?? []).map((t) => ({
61
+ name: t.name,
62
+ path: t.path.replace(/^~/, homedir()),
63
+ description: t.description ?? "",
64
+ platform: "all",
65
+ safe: t.safe,
66
+ }));
67
+ return [...merged, ...custom];
68
+ }
@@ -27,12 +27,19 @@ export function formatPercent(ratio) {
27
27
  return chalk.yellow(text);
28
28
  return chalk.green(text);
29
29
  }
30
+ function visLen(str) {
31
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional ANSI escape strip
32
+ return str.replace(/\x1B\[[0-9;]*m/g, "").length;
33
+ }
34
+ function padEndVis(str, width) {
35
+ return str + " ".repeat(Math.max(0, width - visLen(str)));
36
+ }
30
37
  export function boxTable(headers, rows) {
31
- const colWidths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? "").length)));
38
+ const colWidths = headers.map((h, i) => Math.max(visLen(h), ...rows.map((r) => visLen(r[i] ?? ""))));
32
39
  const sep = `┼${colWidths.map((w) => "─".repeat(w + 2)).join("┼")}┼`;
33
40
  const top = `┌${colWidths.map((w) => "─".repeat(w + 2)).join("┬")}┐`;
34
41
  const bot = `└${colWidths.map((w) => "─".repeat(w + 2)).join("┴")}┘`;
35
- const fmtRow = (cells) => `│${cells.map((c, i) => ` ${c.padEnd(colWidths[i])} `).join("│")}│`;
42
+ const fmtRow = (cells) => `│${cells.map((c, i) => ` ${padEndVis(c, colWidths[i])} `).join("│")}│`;
36
43
  const lines = [top, fmtRow(headers), sep, ...rows.map(fmtRow), bot];
37
44
  return lines.join("\n");
38
45
  }
@@ -1,7 +1,10 @@
1
1
  import { readdirSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { resolveConfig } from "./config.js";
3
4
  export function scanDir(root, opts = {}, currentDepth = 0) {
4
- const maxDepth = opts.depth ?? 3;
5
+ const { scanDepth, blockSize, opaqueDirectories } = resolveConfig();
6
+ const maxDepth = opts.depth ?? scanDepth;
7
+ const opaqueSet = new Set(opaqueDirectories);
5
8
  const entries = [];
6
9
  let items;
7
10
  try {
@@ -22,7 +25,7 @@ export function scanDir(root, opts = {}, currentDepth = 0) {
22
25
  continue;
23
26
  }
24
27
  if (stat.isDirectory()) {
25
- if (name === "node_modules" || name === ".git") {
28
+ if (opaqueSet.has(name)) {
26
29
  const size = dirSize(fullPath);
27
30
  if (!opts.filesOnly) {
28
31
  if (!opts.olderThan || stat.mtime < opts.olderThan) {
@@ -49,7 +52,7 @@ export function scanDir(root, opts = {}, currentDepth = 0) {
49
52
  if (!opts.olderThan || stat.mtime < opts.olderThan) {
50
53
  entries.push({
51
54
  path: fullPath,
52
- size: stat.size,
55
+ size: stat.blocks * blockSize,
53
56
  isDirectory: false,
54
57
  mtime: stat.mtime,
55
58
  });
@@ -60,6 +63,7 @@ export function scanDir(root, opts = {}, currentDepth = 0) {
60
63
  return entries;
61
64
  }
62
65
  export function dirSize(dirPath) {
66
+ const { blockSize } = resolveConfig();
63
67
  let total = 0;
64
68
  let items;
65
69
  try {
@@ -73,7 +77,7 @@ export function dirSize(dirPath) {
73
77
  try {
74
78
  const stat = statSync(fullPath);
75
79
  if (stat.isFile()) {
76
- total += stat.size;
80
+ total += stat.blocks * blockSize;
77
81
  }
78
82
  else if (stat.isDirectory()) {
79
83
  total += dirSize(fullPath);
@@ -0,0 +1,9 @@
1
+ import type { WasteEntry } from "./wasteland.js";
2
+ export interface ScanState {
3
+ scannedAt: string;
4
+ entries: WasteEntry[];
5
+ }
6
+ export declare function saveLastScan(entries: WasteEntry[]): void;
7
+ export declare function loadLastScan(): ScanState | null;
8
+ export declare function scanAgePath(state: ScanState): number;
9
+ export declare function staleThresholdMs(): number;
@@ -0,0 +1,32 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { resolveConfig } from "./config.js";
5
+ const STATE_DIR = join(homedir(), ".dustclaw");
6
+ const SCAN_FILE = join(STATE_DIR, "last-scan.json");
7
+ export function saveLastScan(entries) {
8
+ const { encoding } = resolveConfig();
9
+ mkdirSync(STATE_DIR, { recursive: true });
10
+ const state = {
11
+ scannedAt: new Date().toISOString(),
12
+ entries,
13
+ };
14
+ writeFileSync(SCAN_FILE, JSON.stringify(state, null, 2), encoding);
15
+ }
16
+ export function loadLastScan() {
17
+ if (!existsSync(SCAN_FILE))
18
+ return null;
19
+ const { encoding } = resolveConfig();
20
+ try {
21
+ return JSON.parse(readFileSync(SCAN_FILE, encoding));
22
+ }
23
+ catch {
24
+ return null;
25
+ }
26
+ }
27
+ export function scanAgePath(state) {
28
+ return Date.now() - new Date(state.scannedAt).getTime();
29
+ }
30
+ export function staleThresholdMs() {
31
+ return resolveConfig().staleThresholdMs;
32
+ }
@@ -3,6 +3,7 @@ export interface WasteEntry {
3
3
  path: string;
4
4
  size: number;
5
5
  description: string;
6
+ safe: boolean;
6
7
  }
7
8
  export declare function findCaches(): WasteEntry[];
8
9
  export declare function findWaste(): WasteEntry[];
@@ -1,95 +1,19 @@
1
- import { execSync } from "node:child_process";
2
1
  import { existsSync, readdirSync, statSync } from "node:fs";
3
2
  import { homedir } from "node:os";
4
3
  import { join } from "node:path";
4
+ import { resolveCacheNames, resolveConfig, resolveTargets } from "./config.js";
5
5
  import { dirSize } from "./scan.js";
6
6
  const home = homedir();
7
- const targets = [
8
- {
9
- name: "Xcode DerivedData",
10
- path: join(home, "Library/Developer/Xcode/DerivedData"),
11
- description: "Xcode build artifacts",
12
- },
13
- {
14
- name: "Xcode Archives",
15
- path: join(home, "Library/Developer/Xcode/Archives"),
16
- description: "Xcode archived builds",
17
- },
18
- {
19
- name: "Xcode Device Support",
20
- path: join(home, "Library/Developer/Xcode/iOS DeviceSupport"),
21
- description: "iOS device support files",
22
- },
23
- {
24
- name: "Homebrew Cache",
25
- path: () => {
26
- try {
27
- return execSync("brew --cache", { encoding: "utf-8" }).trim();
28
- }
29
- catch {
30
- return null;
31
- }
32
- },
33
- description: "Homebrew downloaded packages",
34
- },
35
- {
36
- name: "Gradle Cache",
37
- path: join(home, ".gradle/caches"),
38
- description: "Gradle build cache",
39
- },
40
- {
41
- name: "Maven Cache",
42
- path: join(home, ".m2/repository"),
43
- description: "Maven dependency cache",
44
- },
45
- {
46
- name: "Cargo Cache",
47
- path: join(home, ".cargo/registry"),
48
- description: "Rust crate cache",
49
- },
50
- {
51
- name: "pnpm Store",
52
- path: join(home, "Library/pnpm/store"),
53
- description: "pnpm content-addressable store",
54
- },
55
- {
56
- name: "npm Cache",
57
- path: join(home, ".npm/_cacache"),
58
- description: "npm download cache",
59
- },
60
- {
61
- name: "Docker Desktop",
62
- path: join(home, "Library/Containers/com.docker.docker/Data"),
63
- description: "Docker images, containers, and volumes",
64
- },
65
- {
66
- name: "iOS Simulators",
67
- path: join(home, "Library/Developer/CoreSimulator/Devices"),
68
- description: "iOS Simulator device data",
69
- },
70
- {
71
- name: "Android Emulators",
72
- path: join(home, ".android/avd"),
73
- description: "Android emulator images",
74
- },
75
- {
76
- name: "Trash",
77
- path: join(home, ".Trash"),
78
- description: "Files in Trash",
79
- },
80
- {
81
- name: "System Logs",
82
- path: join(home, "Library/Logs"),
83
- description: "Application and system logs",
84
- },
85
- ];
86
- const MIN_CACHE_SIZE = 50 * 1024 * 1024; // 50 MB minimum to show in breakdown
7
+ function friendlyName(dirName, cacheNames) {
8
+ return cacheNames[dirName] ?? dirName;
9
+ }
87
10
  export function findCaches() {
88
- const cachesDir = join(home, "Library/Caches");
11
+ const { minCacheSize, cachesPath, cacheSkipList } = resolveConfig();
12
+ const cachesDir = join(home, cachesPath);
89
13
  if (!existsSync(cachesDir))
90
14
  return [];
91
- // Paths already covered by specific targets — skip to avoid double-counting
92
- const skip = new Set(["Homebrew", "CocoaPods", "Yarn"]);
15
+ const skip = new Set(cacheSkipList);
16
+ const cacheNames = resolveCacheNames();
93
17
  const results = [];
94
18
  let items;
95
19
  try {
@@ -111,69 +35,49 @@ export function findCaches() {
111
35
  continue;
112
36
  }
113
37
  const size = dirSize(fullPath);
114
- if (size >= MIN_CACHE_SIZE) {
38
+ if (size >= minCacheSize) {
115
39
  results.push({
116
- name: `Cache: ${friendlyName(name)}`,
40
+ name: `Cache: ${friendlyName(name, cacheNames)}`,
117
41
  path: fullPath,
118
42
  size,
119
- description: `${name} cache`,
43
+ description: `${name} application cache`,
44
+ safe: true,
120
45
  });
121
46
  }
122
47
  }
123
48
  return results.sort((a, b) => b.size - a.size);
124
49
  }
125
- function friendlyName(dirName) {
126
- const map = {
127
- "com.spotify.client": "Spotify",
128
- "com.apple.Safari": "Safari",
129
- "com.google.Chrome": "Chrome",
130
- Google: "Google/Chrome",
131
- "com.docker.docker": "Docker",
132
- "com.microsoft.VSCode": "VS Code",
133
- "com.todesktop.230313mzl4w4u92.ShipIt": "Cursor Updates",
134
- "com.google.antigravity.ShipIt": "Chrome Updates",
135
- icloudmailagent: "iCloud Mail",
136
- "com.apple.callintelligenced": "Apple Call Intelligence",
137
- "ms-playwright": "Playwright Browsers",
138
- pip: "pip",
139
- Cypress: "Cypress",
140
- "node-gyp": "node-gyp",
141
- typescript: "TypeScript",
142
- pnpm: "pnpm",
143
- colima: "Colima",
144
- "com.openai.codex": "OpenAI Codex",
145
- };
146
- return map[dirName] ?? dirName;
147
- }
148
50
  export function findWaste() {
51
+ const targets = resolveTargets();
149
52
  const results = [];
150
53
  for (const target of targets) {
151
- const resolvedPath = typeof target.path === "function" ? target.path() : target.path;
152
- if (!resolvedPath)
153
- continue;
154
- if (!existsSync(resolvedPath))
54
+ if (!existsSync(target.path))
155
55
  continue;
156
- const size = dirSize(resolvedPath);
56
+ const size = dirSize(target.path);
157
57
  if (size > 0) {
158
58
  results.push({
159
59
  name: target.name,
160
- path: resolvedPath,
60
+ path: target.path,
161
61
  size,
162
62
  description: target.description,
63
+ safe: target.safe,
163
64
  });
164
65
  }
165
66
  }
166
67
  results.push(...findCaches());
167
68
  return results.sort((a, b) => b.size - a.size);
168
69
  }
169
- export function findNodeModules(root, maxDepth = 5) {
70
+ export function findNodeModules(root, maxDepth) {
71
+ const depth = maxDepth ?? resolveConfig().nodeModulesMaxDepth;
170
72
  const results = [];
171
- searchNodeModules(root, results, 0, maxDepth);
73
+ searchNodeModules(root, results, 0, depth);
172
74
  return results.sort((a, b) => b.size - a.size);
173
75
  }
174
76
  function searchNodeModules(dir, results, depth, maxDepth) {
175
77
  if (depth > maxDepth)
176
78
  return;
79
+ const { opaqueDirectories } = resolveConfig();
80
+ const opaqueSet = new Set(opaqueDirectories);
177
81
  let items;
178
82
  try {
179
83
  items = readdirSync(dir);
@@ -193,10 +97,13 @@ function searchNodeModules(dir, results, depth, maxDepth) {
193
97
  path: fullPath,
194
98
  size,
195
99
  description: `node_modules in ${dir}`,
100
+ safe: true,
196
101
  });
197
102
  }
198
103
  continue;
199
104
  }
105
+ if (opaqueSet.has(name))
106
+ continue;
200
107
  try {
201
108
  const stat = statSync(fullPath);
202
109
  if (stat.isDirectory()) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dustclaw",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "description": "Disk space monitoring, analysis, and cleanup CLI",
5
5
  "homepage": "https://github.com/psandis/dustclaw",
6
6
  "type": "module",