Repository navigation
Expand file tree
/
Copy pathclearDevCache.ts
More file actions
316 lines (266 loc) · 9.33 KB
/
Copy pathclearDevCache.ts
File metadata and controls
316 lines (266 loc) · 9.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/**
* mcp/skills/clearDevCache.ts — clear_dev_cache skill
*
* Clears developer tool caches to free disk space. Supports npm, yarn,
* pnpm, pip, gradle, maven. Reports sizes before clearing. Safe to
* clear — tools rebuild caches as needed.
*
* Platform strategy
* -----------------
* darwin npm/yarn/pnpm via their CLI; pip/gradle/maven via directory paths
* under ~/Library/Caches and ~/.gradle/.m2
* win32 Same CLIs where available; paths from %APPDATA%/%LOCALAPPDATA%
*
* Smoke test
* npx tsx -r dotenv/config mcp/skills/clearDevCache.ts
*/
import * as os from "os";
import * as nodePath from "path";
import * as fs from "fs/promises";
import { exec } from "child_process";
import { promisify } from "util";
import { z } from "zod";
import { getDirSizeBytes } from "./_shared/dirSize";
const execAsync = promisify(exec);
// -- Meta ---------------------------------------------------------------------
export const meta = {
name: "clear_dev_cache",
description:
"Clears developer tool caches to free disk space. " +
"Supports npm, yarn, pnpm, pip, gradle, maven. " +
"Reports sizes before clearing. " +
"Safe to clear — tools rebuild caches as needed.",
riskLevel: "medium",
destructive: false,
requiresConsent: false,
supportsDryRun: true,
affectedScope: ["user"],
auditRequired: true,
tccCategories: ["FullDiskAccess"],
footprint: {
kind: "sweep",
// pip/Yarn live under ~/Library/Caches (excused by clear_app_cache's DEV
// excludes); npm/maven/gradle/pnpm live outside it (no overlap).
darwin: { roots: [
"~/.npm", "~/.m2/repository", "~/.gradle/caches", "~/Library/pnpm",
"~/Library/Caches/pip", "~/Library/Caches/Yarn",
] },
win32: { roots: [
"%USERPROFILE%/.m2/repository", "%USERPROFILE%/.gradle/caches",
"%LOCALAPPDATA%/npm-cache", "%LOCALAPPDATA%/pip", "%LOCALAPPDATA%/Yarn",
] },
},
outputKeys: ["caches","totalSizeMb","freedMb"],
schema: {
tools: z
.array(z.enum(["npm", "yarn", "pnpm", "pip", "gradle", "maven", "all"]))
.nullable().optional()
.describe("Tools to clear. Default: all detected"),
dryRun: z
.boolean()
.nullable().optional()
.describe("If true, report sizes without clearing. Default: true"),
},
} as const;
// -- Types --------------------------------------------------------------------
interface CacheEntry {
tool: string;
path: string | null;
sizeMb: number;
available: boolean;
cleared: boolean;
}
interface ClearDevCacheResult {
caches: CacheEntry[];
totalSizeMb: number;
freedMb: number;
}
// -- Helpers ------------------------------------------------------------------
const ALL_TOOLS = ["npm", "yarn", "pnpm", "pip", "gradle", "maven"] as const;
type ToolName = typeof ALL_TOOLS[number];
async function getDirSizeMb(dirPath: string): Promise<number> {
try {
if (os.platform() === "win32") {
const { sizeBytes } = await getDirSizeBytes(dirPath);
return isNaN(sizeBytes) ? 0 : Math.round((sizeBytes / 1_000_000) * 10) / 10;
} else {
const safePath = dirPath.replace(/'/g, "'\\''");
const { stdout } = await execAsync(
`du -sk '${safePath}' 2>/dev/null`,
{ maxBuffer: 10 * 1024 * 1024, shell: "/bin/bash" },
);
const kb = parseInt(stdout.split("\t")[0], 10);
return isNaN(kb) ? 0 : Math.round((kb / 1024) * 10) / 10;
}
} catch {
return 0;
}
}
async function pathExists(p: string): Promise<boolean> {
try { await fs.access(p); return true; } catch { return false; }
}
async function deleteDirContents(dirPath: string): Promise<void> {
await fs.rm(dirPath, { recursive: true, force: true });
}
async function commandExists(cmd: string): Promise<boolean> {
try {
const check = os.platform() === "win32" ? `where ${cmd}` : `which ${cmd}`;
await execAsync(check);
return true;
} catch {
return false;
}
}
// -- Per-tool handlers --------------------------------------------------------
async function handleNpm(dryRun: boolean): Promise<CacheEntry> {
const tool = "npm";
if (!(await commandExists("npm"))) {
return { tool, path: null, sizeMb: 0, available: false, cleared: false };
}
// Get cache dir
let cachePath: string | null = null;
try {
const { stdout } = await execAsync("npm config get cache");
cachePath = stdout.trim();
} catch { /* ignore */ }
const sizeMb = cachePath ? await getDirSizeMb(cachePath) : 0;
let cleared = false;
if (!dryRun) {
try {
await execAsync("npm cache clean --force");
cleared = true;
} catch { cleared = false; }
}
return { tool, path: cachePath, sizeMb, available: true, cleared };
}
async function handleYarn(dryRun: boolean): Promise<CacheEntry> {
const tool = "yarn";
if (!(await commandExists("yarn"))) {
return { tool, path: null, sizeMb: 0, available: false, cleared: false };
}
let cachePath: string | null = null;
try {
const { stdout } = await execAsync("yarn cache dir");
cachePath = stdout.trim();
} catch { /* ignore */ }
const sizeMb = cachePath ? await getDirSizeMb(cachePath) : 0;
let cleared = false;
if (!dryRun && cachePath) {
try {
await deleteDirContents(cachePath);
cleared = true;
} catch { cleared = false; }
}
return { tool, path: cachePath, sizeMb, available: true, cleared };
}
async function handlePnpm(dryRun: boolean): Promise<CacheEntry> {
const tool = "pnpm";
if (!(await commandExists("pnpm"))) {
return { tool, path: null, sizeMb: 0, available: false, cleared: false };
}
let cachePath: string | null = null;
try {
const { stdout } = await execAsync("pnpm store path");
cachePath = stdout.trim();
} catch { /* ignore */ }
const sizeMb = cachePath ? await getDirSizeMb(cachePath) : 0;
let cleared = false;
if (!dryRun) {
try {
await execAsync("pnpm store prune");
cleared = true;
} catch { cleared = false; }
}
return { tool, path: cachePath, sizeMb, available: true, cleared };
}
async function handlePip(dryRun: boolean): Promise<CacheEntry> {
const tool = "pip";
const home = os.homedir();
const cachePath = os.platform() === "win32"
? nodePath.join(process.env.LOCALAPPDATA ?? nodePath.join(home, "AppData", "Local"), "pip", "Cache")
: nodePath.join(home, "Library", "Caches", "pip");
const available = await pathExists(cachePath);
const sizeMb = available ? await getDirSizeMb(cachePath) : 0;
let cleared = false;
if (!dryRun && available) {
try {
// Try pip cache purge first (pip 20.1+)
try {
const pipCmd = (await commandExists("pip3")) ? "pip3" : "pip";
await execAsync(`${pipCmd} cache purge`);
} catch {
await deleteDirContents(cachePath);
}
cleared = true;
} catch { cleared = false; }
}
return { tool, path: cachePath, sizeMb, available, cleared };
}
async function handleGradle(dryRun: boolean): Promise<CacheEntry> {
const tool = "gradle";
const home = os.homedir();
const cachePath = os.platform() === "win32"
? nodePath.join(process.env.USERPROFILE ?? home, ".gradle", "caches")
: nodePath.join(home, ".gradle", "caches");
const available = await pathExists(cachePath);
const sizeMb = available ? await getDirSizeMb(cachePath) : 0;
let cleared = false;
if (!dryRun && available) {
try {
await deleteDirContents(cachePath);
cleared = true;
} catch { cleared = false; }
}
return { tool, path: cachePath, sizeMb, available, cleared };
}
async function handleMaven(dryRun: boolean): Promise<CacheEntry> {
const tool = "maven";
const home = os.homedir();
const cachePath = os.platform() === "win32"
? nodePath.join(process.env.USERPROFILE ?? home, ".m2", "repository")
: nodePath.join(home, ".m2", "repository");
const available = await pathExists(cachePath);
const sizeMb = available ? await getDirSizeMb(cachePath) : 0;
let cleared = false;
if (!dryRun && available) {
try {
await deleteDirContents(cachePath);
cleared = true;
} catch { cleared = false; }
}
return { tool, path: cachePath, sizeMb, available, cleared };
}
// -- Exported run function ----------------------------------------------------
export async function run({
tools = ["all"],
dryRun = true,
}: {
tools?: Array<"npm" | "yarn" | "pnpm" | "pip" | "gradle" | "maven" | "all">;
dryRun?: boolean;
} = {}) {
const selected: ToolName[] = tools.includes("all")
? [...ALL_TOOLS]
: (tools.filter((t) => t !== "all") as ToolName[]);
const handlers: Record<ToolName, (dryRun: boolean) => Promise<CacheEntry>> = {
npm: handleNpm,
yarn: handleYarn,
pnpm: handlePnpm,
pip: handlePip,
gradle: handleGradle,
maven: handleMaven,
};
const caches = await Promise.all(
selected.map((t) => handlers[t](dryRun)),
);
const totalSizeMb = Math.round(caches.reduce((acc, c) => acc + c.sizeMb, 0) * 10) / 10;
const freedMb = dryRun
? 0
: Math.round(caches.filter((c) => c.cleared).reduce((acc, c) => acc + c.sizeMb, 0) * 10) / 10;
return { caches, totalSizeMb, freedMb };
}
// -- Smoke test ---------------------------------------------------------------
if (false) {
run({})
.then(r => console.log(JSON.stringify(r, null, 2)))
.catch((err: Error) => { console.error(err.message); process.exit(1); });
}