-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnext-cleaner.js
304 lines (255 loc) · 7.44 KB
/
next-cleaner.js
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
const fs = require("fs");
const path = require("path");
const readline = require("readline");
const os = require("os");
// Configuration
const CONFIG = {
DRY_RUN: process.argv.includes("--dry-run"),
MIN_DAYS: 14,
LOG_FILE: "next-cleaner.log",
// Directories to exclude from search
EXCLUDED_DIRS: [
"/System",
"/Library",
"/bin",
"/sbin",
"/private",
"/opt",
"/usr",
"/var",
"node_modules",
".git",
],
};
// Parse command line arguments
function parseArguments() {
const args = process.argv.slice(2);
const options = {
paths: [],
dryRun: CONFIG.DRY_RUN,
};
for (let i = 0; i < args.length; i++) {
if (args[i] === "--path" || args[i] === "-p") {
if (i + 1 < args.length) {
options.paths.push(path.resolve(args[++i]));
}
}
}
return options;
}
// Log message function
function logMessage(message) {
const timestamp = new Date().toISOString();
const logEntry = `[${timestamp}] ${message}\n`;
console.log(message);
fs.appendFileSync(CONFIG.LOG_FILE, logEntry);
}
// Error logging function
function logError(error, context) {
const errorMessage = `Error occurred (${context}): ${error.message}`;
logMessage(errorMessage);
}
// Get search paths
function getSearchPaths() {
const paths = [];
// Add home directory
paths.push(os.homedir());
// Add all user folders in /Users directory
try {
const usersDir = "/Users";
if (fs.existsSync(usersDir)) {
const users = fs.readdirSync(usersDir);
users.forEach((user) => {
if (user !== "Shared" && !user.startsWith(".")) {
paths.push(path.join(usersDir, user));
}
});
}
} catch (error) {
logError(error, "searching user directories");
}
return paths;
}
// Check if folder should be deleted
function shouldDeleteFolder(folderPath) {
try {
const stats = fs.statSync(folderPath);
const now = new Date();
const modifiedDate = new Date(stats.mtime);
const diffDays = (now - modifiedDate) / (1000 * 60 * 60 * 24);
// Check if it's a real Next.js project by verifying package.json
const parentDir = path.dirname(folderPath);
const hasPackageJson = fs.existsSync(path.join(parentDir, "package.json"));
if (!hasPackageJson) {
logMessage(
`Warning: No package.json found in ${parentDir}. Skipping this .next folder.`
);
return false;
}
return diffDays > CONFIG.MIN_DAYS;
} catch (error) {
logError(error, `checking folder (${folderPath})`);
return false;
}
}
// Check if path is in exclusion list
function isExcludedPath(pathToCheck) {
return CONFIG.EXCLUDED_DIRS.some(
(excluded) => pathToCheck.includes(excluded) || pathToCheck === excluded
);
}
// Find .next folders to delete
async function findNextFolders(startPath, foundFolders = []) {
try {
if (!fs.existsSync(startPath)) {
logMessage(`Path does not exist: ${startPath}`);
return foundFolders;
}
// Check excluded paths
if (isExcludedPath(startPath)) {
return foundFolders;
}
const files = fs.readdirSync(startPath);
for (const file of files) {
const filePath = path.join(startPath, file);
try {
if (!fs.existsSync(filePath)) {
continue;
}
const stats = fs.statSync(filePath);
if (stats.isDirectory()) {
if (file === ".next" && shouldDeleteFolder(filePath)) {
foundFolders.push({
path: filePath,
size: await getFolderSize(filePath),
mtime: stats.mtime,
});
} else if (!isExcludedPath(filePath)) {
await findNextFolders(filePath, foundFolders);
}
}
} catch (error) {
logError(error, `processing file (${filePath})`);
}
}
} catch (error) {
logError(error, `searching directory (${startPath})`);
}
return foundFolders;
}
// Calculate folder size
async function getFolderSize(folderPath) {
try {
let size = 0;
const files = fs.readdirSync(folderPath);
for (const file of files) {
const filePath = path.join(folderPath, file);
const stats = fs.statSync(filePath);
if (stats.isFile()) {
size += stats.size;
} else if (stats.isDirectory()) {
size += await getFolderSize(filePath);
}
}
return size;
} catch (error) {
logError(error, `calculating folder size (${folderPath})`);
return 0;
}
}
// Get user confirmation
async function getUserConfirmation(message) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(message + " (y/n): ", (answer) => {
rl.close();
resolve(answer.toLowerCase() === "y");
});
});
}
// Print help
function printHelp() {
console.log(`
Usage: node next-cleaner.js [options]
Options:
--path, -p <path> Specify search path (can be used multiple times)
--dry-run Preview without actual deletion
--help, -h Display this help message
Examples:
node next-cleaner.js --path /Users/projects --path /var/www
node next-cleaner.js -p /Users/projects --dry-run
`);
process.exit(0);
}
// Main function
async function main() {
// Display help
if (process.argv.includes("--help") || process.argv.includes("-h")) {
printHelp();
}
const options = parseArguments();
// Use current directory if no paths specified
if (options.paths.length === 0) {
options.paths.push(process.cwd());
}
logMessage("Starting full disk cleanup process...");
logMessage(
`Mode: ${CONFIG.DRY_RUN ? "DRY RUN (no actual deletion)" : "ACTUAL DELETE"}`
);
const searchPaths = getSearchPaths();
logMessage(`Starting search in paths:\n${searchPaths.join("\n")}`);
let allFoldersToDelete = [];
for (const startPath of options.paths) {
logMessage(`\nSearching in ${startPath}...`);
const foldersInPath = await findNextFolders(startPath);
allFoldersToDelete = allFoldersToDelete.concat(foldersInPath);
}
if (allFoldersToDelete.length === 0) {
logMessage("No .next folders found for deletion.");
return;
}
logMessage(`\nFound ${allFoldersToDelete.length} .next folders to delete.`);
logMessage("\nFolders to be deleted:");
const totalSize = allFoldersToDelete.reduce((sum, folder) => sum + folder.size, 0);
const totalSizeMB = (totalSize / 1024 / 1024).toFixed(2);
allFoldersToDelete.forEach((folder) => {
const sizeMB = (folder.size / 1024 / 1024).toFixed(2);
const date = folder.mtime.toLocaleDateString();
logMessage(`- ${folder.path} (${sizeMB}MB, last modified: ${date})`);
});
logMessage(`\nTotal size: ${totalSizeMB}MB`);
if (CONFIG.DRY_RUN) {
logMessage("\nDRY RUN mode: No actual deletions performed.");
return;
}
const confirmed = await getUserConfirmation(
"\nDo you want to delete these folders?"
);
if (!confirmed) {
logMessage("Operation cancelled.");
return;
}
let successCount = 0;
let errorCount = 0;
for (const folder of allFoldersToDelete) {
try {
fs.rmSync(folder.path, { recursive: true, force: true });
logMessage(`Success: Deleted ${folder.path}`);
successCount++;
} catch (error) {
logError(error, `deleting folder (${folder.path})`);
errorCount++;
}
}
logMessage(
`\nOperation completed: ${successCount} successful, ${errorCount} failed`
);
}
// Run script
main().catch((error) => {
logError(error, "main process");
process.exit(1);
});