@iyowei/sweep-node-modules 0.3.0 → 0.5.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/LICENSE +1 -1
- package/README.md +628 -82
- package/README.zh-CN.md +675 -0
- package/dist/classify.d.ts +48 -0
- package/dist/codes.d.ts +41 -0
- package/dist/config.d.ts +115 -0
- package/dist/delete.d.ts +155 -0
- package/dist/display.d.ts +29 -0
- package/dist/errors.d.ts +43 -0
- package/dist/guard.d.ts +230 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +1775 -0
- package/dist/manifest.json +8 -0
- package/dist/runtime.d.ts +26 -0
- package/dist/scan-native.d.ts +2 -0
- package/dist/scan-parallel.d.ts +2 -0
- package/dist/scan-prune.d.ts +2 -0
- package/dist/scan.d.ts +6 -0
- package/dist/size-du.d.ts +33 -0
- package/dist/size-js.d.ts +2 -0
- package/dist/size.d.ts +2 -0
- package/dist/skip.d.ts +35 -0
- package/dist/summary.d.ts +38 -0
- package/dist/sweep.d.ts +7 -0
- package/dist/types.d.ts +458 -0
- package/package.json +18 -31
- package/bin/sweep-nm.mjs +0 -43
- package/dist/cli.js +0 -1348
package/dist/index.js
ADDED
|
@@ -0,0 +1,1775 @@
|
|
|
1
|
+
// src/classify.ts
|
|
2
|
+
import { homedir as homedir3 } from "node:os";
|
|
3
|
+
|
|
4
|
+
// src/config.ts
|
|
5
|
+
import { readFile } from "node:fs/promises";
|
|
6
|
+
import { homedir } from "node:os";
|
|
7
|
+
import { posix, win32 } from "node:path";
|
|
8
|
+
|
|
9
|
+
// src/errors.ts
|
|
10
|
+
var SWEEP_ERROR_CODES = new Set([
|
|
11
|
+
"CONFIG_READ_FAILED",
|
|
12
|
+
"CONFIG_CORRUPT_JSON",
|
|
13
|
+
"CONFIG_CORRUPT_SHAPE",
|
|
14
|
+
"CONFIG_ABSENT",
|
|
15
|
+
"INVALID_ARGUMENT",
|
|
16
|
+
"CANCELLED"
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
class SweepError extends Error {
|
|
20
|
+
name = "SweepError";
|
|
21
|
+
code;
|
|
22
|
+
details;
|
|
23
|
+
constructor(code, message, details) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.code = code;
|
|
26
|
+
this.details = details;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function isSweepError(value) {
|
|
30
|
+
if (typeof value !== "object" || value === null)
|
|
31
|
+
return false;
|
|
32
|
+
const candidate = value;
|
|
33
|
+
return candidate.name === "SweepError" && typeof candidate.code === "string" && SWEEP_ERROR_CODES.has(candidate.code);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// src/config.ts
|
|
37
|
+
var DEFAULT_EXCLUDE = [
|
|
38
|
+
".bun",
|
|
39
|
+
".npm",
|
|
40
|
+
".pnpm-store",
|
|
41
|
+
".yarn",
|
|
42
|
+
".nvm",
|
|
43
|
+
"nvm",
|
|
44
|
+
".fnm",
|
|
45
|
+
".volta",
|
|
46
|
+
".asdf",
|
|
47
|
+
".n",
|
|
48
|
+
".vscode",
|
|
49
|
+
".vscode-insiders",
|
|
50
|
+
".vscode-server",
|
|
51
|
+
".cursor",
|
|
52
|
+
".antigravity",
|
|
53
|
+
"Library",
|
|
54
|
+
".local",
|
|
55
|
+
".config",
|
|
56
|
+
".cache",
|
|
57
|
+
".claude"
|
|
58
|
+
];
|
|
59
|
+
function platformDefaultPath(platform, env, home) {
|
|
60
|
+
if (platform === "win32") {
|
|
61
|
+
const roaming = env.APPDATA || win32.join(env.USERPROFILE || home, "AppData", "Roaming");
|
|
62
|
+
return win32.join(roaming, "sweep-node-modules", "config.json");
|
|
63
|
+
}
|
|
64
|
+
return posix.join(home, ".config", "sweep-node-modules", "config.json");
|
|
65
|
+
}
|
|
66
|
+
function resolveConfigPath(options) {
|
|
67
|
+
if (options.flag) {
|
|
68
|
+
return { path: options.flag, source: "flag" };
|
|
69
|
+
}
|
|
70
|
+
const env = options.env ?? process.env;
|
|
71
|
+
if (env.SWEEP_NM_CONFIG) {
|
|
72
|
+
return { path: env.SWEEP_NM_CONFIG, source: "env" };
|
|
73
|
+
}
|
|
74
|
+
const platform = options.platform ?? process.platform;
|
|
75
|
+
const home = options.homedir ?? homedir();
|
|
76
|
+
return {
|
|
77
|
+
path: platformDefaultPath(platform, env, home),
|
|
78
|
+
source: "platform-default"
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function describeActual(value) {
|
|
82
|
+
if (value === undefined)
|
|
83
|
+
return "缺失";
|
|
84
|
+
if (value === null)
|
|
85
|
+
return "null";
|
|
86
|
+
if (Array.isArray(value))
|
|
87
|
+
return "array";
|
|
88
|
+
return typeof value;
|
|
89
|
+
}
|
|
90
|
+
function fieldError(container, field, optional) {
|
|
91
|
+
const value = container[field];
|
|
92
|
+
if (value === undefined) {
|
|
93
|
+
return optional ? null : { field, message: `${field} 应为字符串数组 (实际: 缺失)` };
|
|
94
|
+
}
|
|
95
|
+
if (!Array.isArray(value)) {
|
|
96
|
+
return {
|
|
97
|
+
field,
|
|
98
|
+
message: `${field} 应为字符串数组 (实际: ${describeActual(value)})`
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
const badIndex = value.findIndex((item) => typeof item !== "string");
|
|
102
|
+
if (badIndex !== -1) {
|
|
103
|
+
return {
|
|
104
|
+
field,
|
|
105
|
+
message: `${field} 第 ${badIndex + 1} 项应为字符串 (实际: ${describeActual(value[badIndex])})`
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
function shapeError(value) {
|
|
111
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
112
|
+
return {
|
|
113
|
+
field: "顶层",
|
|
114
|
+
message: `顶层应为对象 (实际: ${describeActual(value)})`
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
const candidate = value;
|
|
118
|
+
const rootsError = fieldError(candidate, "roots", false);
|
|
119
|
+
if (rootsError !== null)
|
|
120
|
+
return rootsError;
|
|
121
|
+
const excludeError = fieldError(candidate, "exclude", true);
|
|
122
|
+
if (excludeError !== null)
|
|
123
|
+
return excludeError;
|
|
124
|
+
return fieldError(candidate, "include", true);
|
|
125
|
+
}
|
|
126
|
+
async function loadConfig(path) {
|
|
127
|
+
let text;
|
|
128
|
+
try {
|
|
129
|
+
text = await readFile(path, "utf8");
|
|
130
|
+
} catch (error) {
|
|
131
|
+
if (error.code === "ENOENT")
|
|
132
|
+
return { state: "absent" };
|
|
133
|
+
throw new SweepError("CONFIG_READ_FAILED", `配置读取失败 (${path}): ${error.message}`, { path, errno: error.code });
|
|
134
|
+
}
|
|
135
|
+
let data;
|
|
136
|
+
try {
|
|
137
|
+
data = JSON.parse(text);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
throw new SweepError("CONFIG_CORRUPT_JSON", `配置损坏 (${path}): JSON 解析失败: ${error.message}`, { path });
|
|
140
|
+
}
|
|
141
|
+
const problem = shapeError(data);
|
|
142
|
+
if (problem !== null) {
|
|
143
|
+
throw new SweepError("CONFIG_CORRUPT_SHAPE", `配置损坏 (${path}): ${problem.message}`, { path, field: problem.field });
|
|
144
|
+
}
|
|
145
|
+
const raw = data;
|
|
146
|
+
return {
|
|
147
|
+
state: "ok",
|
|
148
|
+
config: {
|
|
149
|
+
roots: raw.roots,
|
|
150
|
+
exclude: raw.exclude ?? [...DEFAULT_EXCLUDE],
|
|
151
|
+
include: raw.include ?? []
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
async function loadResolvedConfig(resolved) {
|
|
156
|
+
const result = await loadConfig(resolved.path);
|
|
157
|
+
if (result.state === "absent" && resolved.source !== "platform-default") {
|
|
158
|
+
throw new SweepError("CONFIG_ABSENT", `配置不存在 (${resolved.path}), 请检查路径`, { path: resolved.path, source: resolved.source });
|
|
159
|
+
}
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
function mergeNames(configNames, cliNames) {
|
|
163
|
+
return [...new Set([...configNames, ...cliNames])].filter((name) => name !== "node_modules" && name !== ".git");
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/guard.ts
|
|
167
|
+
import { lstat, realpath, stat } from "node:fs/promises";
|
|
168
|
+
import { homedir as homedir2 } from "node:os";
|
|
169
|
+
import { posix as posix2, win32 as win322 } from "node:path";
|
|
170
|
+
var POSIX_STYLE = {
|
|
171
|
+
name: "posix",
|
|
172
|
+
ops: posix2,
|
|
173
|
+
caseInsensitive: false
|
|
174
|
+
};
|
|
175
|
+
var WIN32_STYLE = {
|
|
176
|
+
name: "win32",
|
|
177
|
+
ops: win322,
|
|
178
|
+
caseInsensitive: true
|
|
179
|
+
};
|
|
180
|
+
function nativeStyle() {
|
|
181
|
+
return process.platform === "win32" ? WIN32_STYLE : POSIX_STYLE;
|
|
182
|
+
}
|
|
183
|
+
function fold(p, style) {
|
|
184
|
+
return style.caseInsensitive ? p.toLowerCase() : p;
|
|
185
|
+
}
|
|
186
|
+
function dedupeKey(realPath, style) {
|
|
187
|
+
return fold(realPath, style);
|
|
188
|
+
}
|
|
189
|
+
function hasNodeModulesLeaf(target, style) {
|
|
190
|
+
return fold(style.ops.basename(target), style) === "node_modules";
|
|
191
|
+
}
|
|
192
|
+
function insideAnyRoot(realPath, roots, style) {
|
|
193
|
+
return roots.some((root) => {
|
|
194
|
+
const rel = style.ops.relative(fold(root, style), fold(realPath, style));
|
|
195
|
+
if (rel === "" || style.ops.isAbsolute(rel))
|
|
196
|
+
return false;
|
|
197
|
+
return rel !== ".." && !rel.startsWith(`..${style.ops.sep}`);
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
function isFilesystemRootBody(realPath, style) {
|
|
201
|
+
return fold(style.ops.parse(realPath).root, style) === fold(realPath, style);
|
|
202
|
+
}
|
|
203
|
+
function isHomeBody(realPath, home, style) {
|
|
204
|
+
return home !== null && dedupeKey(realPath, style) === dedupeKey(home, style);
|
|
205
|
+
}
|
|
206
|
+
function firstSymlinkOnAnchor(links) {
|
|
207
|
+
for (const link of links) {
|
|
208
|
+
if (link.symlink)
|
|
209
|
+
return link.path;
|
|
210
|
+
}
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
function anchorChainPaths(root, style) {
|
|
214
|
+
const absolute = style.ops.isAbsolute(root) ? root : style.ops.resolve(root);
|
|
215
|
+
const prefix = style.ops.parse(absolute).root;
|
|
216
|
+
const chain = [];
|
|
217
|
+
let cursor = prefix;
|
|
218
|
+
for (const part of absolute.slice(prefix.length).split(style.ops.sep)) {
|
|
219
|
+
if (part === "")
|
|
220
|
+
continue;
|
|
221
|
+
cursor = style.ops.join(cursor, part);
|
|
222
|
+
chain.push(cursor);
|
|
223
|
+
}
|
|
224
|
+
return chain;
|
|
225
|
+
}
|
|
226
|
+
async function tryRealpath(p) {
|
|
227
|
+
try {
|
|
228
|
+
return await realpath(p);
|
|
229
|
+
} catch {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
async function collectAnchorLinks(root, style) {
|
|
234
|
+
const links = [];
|
|
235
|
+
for (const path of anchorChainPaths(root, style)) {
|
|
236
|
+
try {
|
|
237
|
+
links.push({ path, symlink: (await lstat(path)).isSymbolicLink() });
|
|
238
|
+
} catch {}
|
|
239
|
+
}
|
|
240
|
+
return links;
|
|
241
|
+
}
|
|
242
|
+
async function firstSymlinkOnTarget(target) {
|
|
243
|
+
return firstSymlinkOnAnchor(await collectAnchorLinks(target, nativeStyle()));
|
|
244
|
+
}
|
|
245
|
+
async function firstSymlinkOnRoot(root) {
|
|
246
|
+
return firstSymlinkOnTarget(root);
|
|
247
|
+
}
|
|
248
|
+
async function validateTargets(targets, options) {
|
|
249
|
+
const style = options.style ?? nativeStyle();
|
|
250
|
+
const homeOption = options.home === undefined ? homedir2() : options.home;
|
|
251
|
+
const anchors = [];
|
|
252
|
+
for (const root of options.roots) {
|
|
253
|
+
anchors.push({
|
|
254
|
+
configured: root,
|
|
255
|
+
real: await tryRealpath(root),
|
|
256
|
+
link: firstSymlinkOnAnchor(await collectAnchorLinks(root, style))
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
const brokenAnchors = anchors.filter((anchor) => anchor.real !== null && anchor.link !== null);
|
|
260
|
+
const roots = [];
|
|
261
|
+
for (const anchor of anchors) {
|
|
262
|
+
if (anchor.real !== null)
|
|
263
|
+
roots.push(anchor.real);
|
|
264
|
+
}
|
|
265
|
+
const home = homeOption === null ? null : await tryRealpath(homeOption) ?? homeOption;
|
|
266
|
+
const accepted = [];
|
|
267
|
+
const rejected = [];
|
|
268
|
+
const mappings = [];
|
|
269
|
+
const seen = new Set;
|
|
270
|
+
for (const target of targets) {
|
|
271
|
+
if (options.signal?.aborted) {
|
|
272
|
+
throw new SweepError("CANCELLED", "安全闸校验在逐目标检查点被取消", {
|
|
273
|
+
phase: "validate"
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
if (!hasNodeModulesLeaf(target, style)) {
|
|
277
|
+
rejected.push({
|
|
278
|
+
target,
|
|
279
|
+
code: "GUARD_LEAF_NOT_NODE_MODULES",
|
|
280
|
+
message: "路径末段不是 node_modules"
|
|
281
|
+
});
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
let real = null;
|
|
285
|
+
let realpathErrno;
|
|
286
|
+
try {
|
|
287
|
+
real = await realpath(target);
|
|
288
|
+
} catch (error) {
|
|
289
|
+
realpathErrno = error.code;
|
|
290
|
+
}
|
|
291
|
+
if (real === null) {
|
|
292
|
+
let code = "GUARD_REALPATH_FAILED";
|
|
293
|
+
if (realpathErrno === "ENOENT")
|
|
294
|
+
code = "GUARD_TARGET_MISSING";
|
|
295
|
+
else if (realpathErrno === "EACCES" || realpathErrno === "EPERM") {
|
|
296
|
+
code = "GUARD_TARGET_UNREADABLE";
|
|
297
|
+
}
|
|
298
|
+
rejected.push({
|
|
299
|
+
target,
|
|
300
|
+
code,
|
|
301
|
+
message: "realpath 失败 (目标不存在或不可读)",
|
|
302
|
+
details: { errno: realpathErrno }
|
|
303
|
+
});
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
const brokenAnchor = brokenAnchors.find((anchor) => insideAnyRoot(real, [anchor.real], style));
|
|
307
|
+
if (brokenAnchor !== undefined) {
|
|
308
|
+
rejected.push({
|
|
309
|
+
target,
|
|
310
|
+
code: "GUARD_ROOT_ANCHOR_SYMLINK",
|
|
311
|
+
message: `根锚点被换位为符号链接 (根: ${brokenAnchor.configured}; 符号链接: ${brokenAnchor.link}), 请把配置根改为不含符号链接的真实路径`,
|
|
312
|
+
details: { root: brokenAnchor.configured, symlink: brokenAnchor.link }
|
|
313
|
+
});
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
if (isFilesystemRootBody(real, style)) {
|
|
317
|
+
rejected.push({
|
|
318
|
+
target,
|
|
319
|
+
code: "GUARD_FILESYSTEM_ROOT_BODY",
|
|
320
|
+
message: "目标是文件系统根本体"
|
|
321
|
+
});
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (isHomeBody(real, home, style)) {
|
|
325
|
+
rejected.push({
|
|
326
|
+
target,
|
|
327
|
+
code: "GUARD_HOME_BODY",
|
|
328
|
+
message: "目标是 home 本体"
|
|
329
|
+
});
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
if (!hasNodeModulesLeaf(real, style)) {
|
|
333
|
+
rejected.push({
|
|
334
|
+
target,
|
|
335
|
+
code: "GUARD_REAL_LEAF_NOT_NODE_MODULES",
|
|
336
|
+
message: "realpath 后的末段不是 node_modules"
|
|
337
|
+
});
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (!insideAnyRoot(real, roots, style)) {
|
|
341
|
+
rejected.push({
|
|
342
|
+
target,
|
|
343
|
+
code: "GUARD_OUTSIDE_ROOTS",
|
|
344
|
+
message: "realpath 后不在任何 root 之下"
|
|
345
|
+
});
|
|
346
|
+
continue;
|
|
347
|
+
}
|
|
348
|
+
const key = dedupeKey(real, style);
|
|
349
|
+
if (seen.has(key)) {
|
|
350
|
+
rejected.push({
|
|
351
|
+
target,
|
|
352
|
+
code: "GUARD_DUPLICATE_TARGET",
|
|
353
|
+
message: "重复目标 (realpath 去重)"
|
|
354
|
+
});
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
seen.add(key);
|
|
358
|
+
accepted.push(real);
|
|
359
|
+
mappings.push({ original: target, real });
|
|
360
|
+
}
|
|
361
|
+
return { accepted, rejected, mappings };
|
|
362
|
+
}
|
|
363
|
+
var fsDeviceProbe = async (path, follow) => {
|
|
364
|
+
try {
|
|
365
|
+
return (await (follow ? stat : lstat)(path)).dev;
|
|
366
|
+
} catch {
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
};
|
|
370
|
+
function owningRoot(target, roots, style) {
|
|
371
|
+
let best = null;
|
|
372
|
+
for (const root of roots) {
|
|
373
|
+
if (!insideAnyRoot(target, [root], style))
|
|
374
|
+
continue;
|
|
375
|
+
if (best === null || root.length > best.length)
|
|
376
|
+
best = root;
|
|
377
|
+
}
|
|
378
|
+
return best;
|
|
379
|
+
}
|
|
380
|
+
async function findCrossDeviceTargets(targets, options) {
|
|
381
|
+
const style = options.style ?? nativeStyle();
|
|
382
|
+
const probe = options.probe ?? fsDeviceProbe;
|
|
383
|
+
const devices = new Map;
|
|
384
|
+
const found = new Map;
|
|
385
|
+
for (const target of targets) {
|
|
386
|
+
const root = owningRoot(target, options.roots, style);
|
|
387
|
+
if (root === null)
|
|
388
|
+
continue;
|
|
389
|
+
let rootDev = devices.get(root);
|
|
390
|
+
if (rootDev === undefined) {
|
|
391
|
+
rootDev = await probe(root, true);
|
|
392
|
+
devices.set(root, rootDev);
|
|
393
|
+
}
|
|
394
|
+
if (rootDev === null)
|
|
395
|
+
continue;
|
|
396
|
+
const targetDev = await probe(target, false);
|
|
397
|
+
if (targetDev === null || targetDev === rootDev)
|
|
398
|
+
continue;
|
|
399
|
+
const parentDev = await probe(style.ops.dirname(target), true);
|
|
400
|
+
found.set(target, parentDev !== null && parentDev !== targetDev ? "target-itself" : "on-path");
|
|
401
|
+
}
|
|
402
|
+
return [...found.entries()].map(([target, kind]) => ({ target, kind }));
|
|
403
|
+
}
|
|
404
|
+
function crossDeviceIndex(entries) {
|
|
405
|
+
return new Map(entries.map((entry) => [entry.target, entry.kind]));
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// src/classify.ts
|
|
409
|
+
var fold2 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
|
|
410
|
+
var INSTALL_TREE_SEGMENTS = new Set([...DEFAULT_EXCLUDE, "extensions", "_npx"].map((name) => name.toLowerCase()));
|
|
411
|
+
function classifyTarget(target, options = {}) {
|
|
412
|
+
const style = options.style ?? nativeStyle();
|
|
413
|
+
const homeOption = options.home === undefined ? homedir3() : options.home;
|
|
414
|
+
const parts = target.split(style.ops.sep).filter((part) => part !== "");
|
|
415
|
+
const ancestors = parts.slice(0, -1);
|
|
416
|
+
for (const segment of ancestors) {
|
|
417
|
+
if (INSTALL_TREE_SEGMENTS.has(segment.toLowerCase()))
|
|
418
|
+
return {
|
|
419
|
+
kind: "suspect-install-tree",
|
|
420
|
+
reason: `位于 ${segment} 安装树目录`
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
const parent = ancestors[ancestors.length - 1];
|
|
424
|
+
if (parent !== undefined && parent.toLowerCase() === "lib")
|
|
425
|
+
return {
|
|
426
|
+
kind: "suspect-install-tree",
|
|
427
|
+
reason: "父目录为 lib, 形如版本管理器的 node 安装树"
|
|
428
|
+
};
|
|
429
|
+
if (homeOption !== null) {
|
|
430
|
+
const relative = style.ops.relative(fold2(homeOption, style), fold2(target, style));
|
|
431
|
+
const [first] = relative.split(style.ops.sep);
|
|
432
|
+
if (first !== undefined && first !== ".." && first !== "." && first.startsWith(".") && !style.ops.isAbsolute(relative))
|
|
433
|
+
return {
|
|
434
|
+
kind: "suspect-install-tree",
|
|
435
|
+
reason: `位于 ${first} (家目录下的隐藏目录)`
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
return { kind: "project" };
|
|
439
|
+
}
|
|
440
|
+
// src/delete.ts
|
|
441
|
+
import { lstat as lstat2, realpath as realpath2, rm } from "node:fs/promises";
|
|
442
|
+
import { isAbsolute, join, relative, sep } from "node:path";
|
|
443
|
+
var ERROR_HINTS = {
|
|
444
|
+
EACCES: "权限不足, 拒绝删除",
|
|
445
|
+
EPERM: "操作不被允许",
|
|
446
|
+
EBUSY: "目标被占用",
|
|
447
|
+
ENOTEMPTY: "目录非空",
|
|
448
|
+
EROFS: "目标位于只读文件系统"
|
|
449
|
+
};
|
|
450
|
+
var PARTIAL_DELETION_HINT = "注意: 目录内容可能已被部分或全部删除, 请复查";
|
|
451
|
+
function describeCode(error) {
|
|
452
|
+
const fsError = error;
|
|
453
|
+
const code = fsError?.code;
|
|
454
|
+
if (typeof code !== "string" || code === "") {
|
|
455
|
+
return `未知错误: ${fsError?.message ?? String(error)}`;
|
|
456
|
+
}
|
|
457
|
+
return `${code}: ${ERROR_HINTS[code] ?? "删除未成功"}`;
|
|
458
|
+
}
|
|
459
|
+
function describeRemovalError(target, error) {
|
|
460
|
+
return `${describeCode(error)} (目标: ${target}; ${PARTIAL_DELETION_HINT})`;
|
|
461
|
+
}
|
|
462
|
+
function describeReviewError(target, path, error) {
|
|
463
|
+
return `安全复核未完成 (${describeCode(error)}) (目标: ${target}; 组件: ${path}; 未执行删除)`;
|
|
464
|
+
}
|
|
465
|
+
function describeVanishedReview(target, path) {
|
|
466
|
+
return `安全复核未完成 (ENOENT: 路径组件消失) (目标: ${target}; 组件: ${path}; 请复查目标是否仍存在; 未执行删除; 若目标确已不存在, 可忽略此条)`;
|
|
467
|
+
}
|
|
468
|
+
async function checkGone(path) {
|
|
469
|
+
try {
|
|
470
|
+
await lstat2(path);
|
|
471
|
+
return "present";
|
|
472
|
+
} catch (error) {
|
|
473
|
+
return error?.code === "ENOENT" ? "gone" : "unknown";
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
function describeSurvivor(target, state) {
|
|
477
|
+
const review = state === "present" ? "复核确认目标仍存在" : "目标是否仍存在未能核验";
|
|
478
|
+
return `ENOENT: 删除中途失败 (${review}) (目标: ${target}; ${PARTIAL_DELETION_HINT})`;
|
|
479
|
+
}
|
|
480
|
+
function isUnder(root, target) {
|
|
481
|
+
const rel = relative(root, target);
|
|
482
|
+
if (rel === "" || isAbsolute(rel))
|
|
483
|
+
return false;
|
|
484
|
+
return rel !== ".." && !rel.startsWith(`..${sep}`);
|
|
485
|
+
}
|
|
486
|
+
function componentChain(root, target) {
|
|
487
|
+
const chain = [root];
|
|
488
|
+
let cursor = root;
|
|
489
|
+
for (const part of relative(root, target).split(sep).slice(0, -1)) {
|
|
490
|
+
cursor = join(cursor, part);
|
|
491
|
+
chain.push(cursor);
|
|
492
|
+
}
|
|
493
|
+
return chain;
|
|
494
|
+
}
|
|
495
|
+
async function isSymlinkHead(path) {
|
|
496
|
+
try {
|
|
497
|
+
return (await lstat2(path)).isSymbolicLink();
|
|
498
|
+
} catch {
|
|
499
|
+
return false;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
async function reviewComponents(chain) {
|
|
503
|
+
for (const path of chain) {
|
|
504
|
+
try {
|
|
505
|
+
const stats = await lstat2(path);
|
|
506
|
+
if (!stats.isDirectory())
|
|
507
|
+
return { kind: "unsafe", path };
|
|
508
|
+
} catch (error) {
|
|
509
|
+
const code = error?.code;
|
|
510
|
+
if (code === "ENOENT")
|
|
511
|
+
return { kind: "vanished", path };
|
|
512
|
+
return { kind: "unverified", path, error };
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
return null;
|
|
516
|
+
}
|
|
517
|
+
var REMOVAL_CONCURRENCY = 4;
|
|
518
|
+
async function removeTargets(targets, options) {
|
|
519
|
+
const roots = options?.roots ?? [];
|
|
520
|
+
const signal = options?.signal;
|
|
521
|
+
const emit = options?.onProgress;
|
|
522
|
+
const slots = Array.from({
|
|
523
|
+
length: targets.length
|
|
524
|
+
});
|
|
525
|
+
let aborted;
|
|
526
|
+
let abortedIndex = Number.POSITIVE_INFINITY;
|
|
527
|
+
const recordAbort = (index, info) => {
|
|
528
|
+
if (index >= abortedIndex)
|
|
529
|
+
return;
|
|
530
|
+
aborted = info;
|
|
531
|
+
abortedIndex = index;
|
|
532
|
+
};
|
|
533
|
+
let cancelled = false;
|
|
534
|
+
const failures = [];
|
|
535
|
+
let next = 0;
|
|
536
|
+
let active = 0;
|
|
537
|
+
let resolveDrained = null;
|
|
538
|
+
const drained = new Promise((resolve) => {
|
|
539
|
+
resolveDrained = resolve;
|
|
540
|
+
});
|
|
541
|
+
const halted = () => cancelled || aborted !== undefined;
|
|
542
|
+
function pump() {
|
|
543
|
+
while (active < REMOVAL_CONCURRENCY && next < targets.length && !halted()) {
|
|
544
|
+
const index = next;
|
|
545
|
+
next += 1;
|
|
546
|
+
active += 1;
|
|
547
|
+
removeOne(index);
|
|
548
|
+
}
|
|
549
|
+
if (active === 0 && resolveDrained !== null) {
|
|
550
|
+
const resolve = resolveDrained;
|
|
551
|
+
resolveDrained = null;
|
|
552
|
+
resolve();
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
async function removeOne(index) {
|
|
556
|
+
try {
|
|
557
|
+
const target = targets[index];
|
|
558
|
+
if (target === undefined)
|
|
559
|
+
return;
|
|
560
|
+
if (signal?.aborted) {
|
|
561
|
+
cancelled = true;
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
const root = roots.find((candidate) => isUnder(candidate.real, target));
|
|
565
|
+
if (root === undefined) {
|
|
566
|
+
const info = {
|
|
567
|
+
target,
|
|
568
|
+
code: "REVIEW_NOT_UNDER_ANY_ROOT",
|
|
569
|
+
message: `安全复核失败 (目标不在任何 roots 之下): ${target}`,
|
|
570
|
+
path: target
|
|
571
|
+
};
|
|
572
|
+
recordAbort(index, info);
|
|
573
|
+
slots[index] = { kind: "aborted" };
|
|
574
|
+
emit?.({ kind: "aborted", aborted: info });
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
if (await isSymlinkHead(root.configured)) {
|
|
578
|
+
const info = {
|
|
579
|
+
target,
|
|
580
|
+
code: "REVIEW_HEAD_SYMLINK",
|
|
581
|
+
message: `安全复核失败 (根被替换为符号链接): ${root.configured}`,
|
|
582
|
+
path: root.configured
|
|
583
|
+
};
|
|
584
|
+
recordAbort(index, info);
|
|
585
|
+
slots[index] = { kind: "aborted" };
|
|
586
|
+
emit?.({ kind: "aborted", aborted: info });
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
const finding = await reviewComponents(componentChain(root.real, target));
|
|
590
|
+
if (finding !== null) {
|
|
591
|
+
if (finding.kind === "vanished") {
|
|
592
|
+
const vanished = {
|
|
593
|
+
target,
|
|
594
|
+
code: "REVIEW_COMPONENT_VANISHED",
|
|
595
|
+
message: describeVanishedReview(target, finding.path),
|
|
596
|
+
partialRisk: false
|
|
597
|
+
};
|
|
598
|
+
slots[index] = { kind: "failed", failure: vanished };
|
|
599
|
+
emit?.({ kind: "failed", failure: vanished });
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
if (finding.kind === "unsafe") {
|
|
603
|
+
const info = {
|
|
604
|
+
target,
|
|
605
|
+
code: "REVIEW_COMPONENT_REPLACED",
|
|
606
|
+
message: `安全复核失败 (路径组件被替换): ${finding.path}`,
|
|
607
|
+
path: finding.path
|
|
608
|
+
};
|
|
609
|
+
recordAbort(index, info);
|
|
610
|
+
slots[index] = { kind: "aborted" };
|
|
611
|
+
emit?.({ kind: "aborted", aborted: info });
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
const unverified = {
|
|
615
|
+
target,
|
|
616
|
+
code: "REVIEW_UNVERIFIED",
|
|
617
|
+
message: describeReviewError(target, finding.path, finding.error),
|
|
618
|
+
partialRisk: false
|
|
619
|
+
};
|
|
620
|
+
slots[index] = { kind: "failed", failure: unverified };
|
|
621
|
+
emit?.({ kind: "failed", failure: unverified });
|
|
622
|
+
return;
|
|
623
|
+
}
|
|
624
|
+
try {
|
|
625
|
+
await rm(target, { recursive: true, force: false });
|
|
626
|
+
slots[index] = { kind: "removed", target };
|
|
627
|
+
emit?.({ kind: "removed", target });
|
|
628
|
+
} catch (error) {
|
|
629
|
+
if (error?.code === "ENOENT") {
|
|
630
|
+
const state = await checkGone(target);
|
|
631
|
+
if (state === "gone") {
|
|
632
|
+
slots[index] = { kind: "missing", target };
|
|
633
|
+
emit?.({ kind: "missing", target });
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
const survivor = {
|
|
637
|
+
target,
|
|
638
|
+
code: "REMOVE_ENOENT_SURVIVOR",
|
|
639
|
+
message: describeSurvivor(target, state),
|
|
640
|
+
partialRisk: true
|
|
641
|
+
};
|
|
642
|
+
slots[index] = { kind: "failed", failure: survivor };
|
|
643
|
+
emit?.({ kind: "failed", failure: survivor });
|
|
644
|
+
return;
|
|
645
|
+
}
|
|
646
|
+
const failure = {
|
|
647
|
+
target,
|
|
648
|
+
code: "REMOVE_FAILED",
|
|
649
|
+
errno: error?.code,
|
|
650
|
+
message: describeRemovalError(target, error),
|
|
651
|
+
partialRisk: true
|
|
652
|
+
};
|
|
653
|
+
slots[index] = { kind: "failed", failure };
|
|
654
|
+
emit?.({ kind: "failed", failure });
|
|
655
|
+
}
|
|
656
|
+
} catch (error) {
|
|
657
|
+
if (failures.length === 0)
|
|
658
|
+
failures.push(error);
|
|
659
|
+
} finally {
|
|
660
|
+
if (signal?.aborted)
|
|
661
|
+
cancelled = true;
|
|
662
|
+
active -= 1;
|
|
663
|
+
pump();
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
pump();
|
|
667
|
+
await drained;
|
|
668
|
+
if (failures.length > 0)
|
|
669
|
+
throw failures[0];
|
|
670
|
+
const result = { removed: [], missing: [], failed: [] };
|
|
671
|
+
for (const slot of slots) {
|
|
672
|
+
if (slot === undefined)
|
|
673
|
+
continue;
|
|
674
|
+
switch (slot.kind) {
|
|
675
|
+
case "removed":
|
|
676
|
+
result.removed.push(slot.target);
|
|
677
|
+
break;
|
|
678
|
+
case "missing":
|
|
679
|
+
result.missing.push(slot.target);
|
|
680
|
+
break;
|
|
681
|
+
case "failed":
|
|
682
|
+
result.failed.push(slot.failure);
|
|
683
|
+
break;
|
|
684
|
+
case "aborted":
|
|
685
|
+
break;
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
if (aborted !== undefined)
|
|
689
|
+
result.aborted = aborted;
|
|
690
|
+
if (cancelled) {
|
|
691
|
+
throw new SweepError("CANCELLED", "删除在条目间检查点被取消", {
|
|
692
|
+
phase: "remove",
|
|
693
|
+
partial: result
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
return result;
|
|
697
|
+
}
|
|
698
|
+
async function toTrustRoots(roots) {
|
|
699
|
+
return Promise.all(roots.map(async (root) => ({
|
|
700
|
+
configured: root,
|
|
701
|
+
real: await realpath2(root).catch(() => null) ?? root
|
|
702
|
+
})));
|
|
703
|
+
}
|
|
704
|
+
function splitStaleRejections(rejected, staleTargets) {
|
|
705
|
+
if (staleTargets !== "missing")
|
|
706
|
+
return { rejected, stale: [] };
|
|
707
|
+
const rest = [];
|
|
708
|
+
const stale = [];
|
|
709
|
+
for (const item of rejected) {
|
|
710
|
+
if (item.code === "GUARD_TARGET_MISSING")
|
|
711
|
+
stale.push(item.target);
|
|
712
|
+
else
|
|
713
|
+
rest.push(item);
|
|
714
|
+
}
|
|
715
|
+
return { rejected: rest, stale };
|
|
716
|
+
}
|
|
717
|
+
async function removeBatch(targets, options) {
|
|
718
|
+
const validation = await validateTargets(targets, {
|
|
719
|
+
roots: options.roots,
|
|
720
|
+
home: options.home,
|
|
721
|
+
style: options.style,
|
|
722
|
+
signal: options.signal
|
|
723
|
+
});
|
|
724
|
+
const { rejected, stale } = splitStaleRejections(validation.rejected, options.staleTargets);
|
|
725
|
+
if (rejected.length > 0) {
|
|
726
|
+
return { status: "rejected", rejected };
|
|
727
|
+
}
|
|
728
|
+
const removal = await removeTargets(validation.accepted, {
|
|
729
|
+
roots: await toTrustRoots(options.roots),
|
|
730
|
+
signal: options.signal,
|
|
731
|
+
onProgress: options.onProgress
|
|
732
|
+
});
|
|
733
|
+
return {
|
|
734
|
+
status: "executed",
|
|
735
|
+
accepted: validation.accepted,
|
|
736
|
+
mappings: validation.mappings,
|
|
737
|
+
stale,
|
|
738
|
+
removal
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
// src/display.ts
|
|
742
|
+
function formatBytes(bytes) {
|
|
743
|
+
if (bytes < 1024)
|
|
744
|
+
return `${Math.round(bytes)} B`;
|
|
745
|
+
const units = ["KB", "MB", "GB", "TB"];
|
|
746
|
+
let value = bytes;
|
|
747
|
+
let index = -1;
|
|
748
|
+
do {
|
|
749
|
+
value /= 1024;
|
|
750
|
+
index += 1;
|
|
751
|
+
} while (value >= 1024 && index < units.length - 1);
|
|
752
|
+
return `${Math.round(value * 10) / 10} ${units[index]}`;
|
|
753
|
+
}
|
|
754
|
+
var sanitizeLine = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "").replace(/\s+/g, " ").trim();
|
|
755
|
+
var sanitizeOutputLine = (text) => {
|
|
756
|
+
const indent = /^[ \t]*/.exec(text)?.[0] ?? "";
|
|
757
|
+
return `${indent}${sanitizeLine(text)}`;
|
|
758
|
+
};
|
|
759
|
+
// src/scan-parallel.ts
|
|
760
|
+
import { readdir, realpath as realpath3, stat as stat2 } from "node:fs/promises";
|
|
761
|
+
import { join as join2 } from "node:path";
|
|
762
|
+
var NODE_MODULES = "node_modules";
|
|
763
|
+
var GIT_DIR = ".git";
|
|
764
|
+
var CONCURRENCY = 32;
|
|
765
|
+
function compareTarget(a, b) {
|
|
766
|
+
if (a.target < b.target)
|
|
767
|
+
return -1;
|
|
768
|
+
if (a.target > b.target)
|
|
769
|
+
return 1;
|
|
770
|
+
return 0;
|
|
771
|
+
}
|
|
772
|
+
function rootFailureWarning(error, root) {
|
|
773
|
+
const { code } = error;
|
|
774
|
+
switch (code) {
|
|
775
|
+
case "ENOENT":
|
|
776
|
+
return {
|
|
777
|
+
code: "SCAN_ROOT_MISSING",
|
|
778
|
+
message: `根不存在, 已跳过: ${root}`,
|
|
779
|
+
path: root
|
|
780
|
+
};
|
|
781
|
+
case "EACCES":
|
|
782
|
+
case "EPERM":
|
|
783
|
+
return {
|
|
784
|
+
code: "SCAN_ROOT_UNREADABLE",
|
|
785
|
+
message: `根不可读 (权限不足), 已跳过: ${root}`,
|
|
786
|
+
path: root,
|
|
787
|
+
errno: code
|
|
788
|
+
};
|
|
789
|
+
case "ENOTDIR":
|
|
790
|
+
return {
|
|
791
|
+
code: "SCAN_ROOT_NOT_DIR",
|
|
792
|
+
message: `根不是目录, 已跳过: ${root}`,
|
|
793
|
+
path: root
|
|
794
|
+
};
|
|
795
|
+
default:
|
|
796
|
+
return {
|
|
797
|
+
code: "SCAN_ROOT_UNAVAILABLE",
|
|
798
|
+
message: `根不可用 (${code ?? "UNKNOWN"}), 已跳过: ${root}`,
|
|
799
|
+
path: root,
|
|
800
|
+
errno: code
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
async function walkRoot(root, ctx) {
|
|
805
|
+
const {
|
|
806
|
+
style,
|
|
807
|
+
exclude,
|
|
808
|
+
excludeCounts,
|
|
809
|
+
include,
|
|
810
|
+
includeCounts,
|
|
811
|
+
hits,
|
|
812
|
+
warnings,
|
|
813
|
+
signal,
|
|
814
|
+
onProgress
|
|
815
|
+
} = ctx;
|
|
816
|
+
const stack = [{ dir: root, included: include.size === 0 }];
|
|
817
|
+
let outstanding = 1;
|
|
818
|
+
let active = 0;
|
|
819
|
+
const failures = [];
|
|
820
|
+
let resolveDrained = null;
|
|
821
|
+
const drained = new Promise((resolve) => {
|
|
822
|
+
resolveDrained = resolve;
|
|
823
|
+
});
|
|
824
|
+
function pump() {
|
|
825
|
+
while (active < CONCURRENCY && stack.length > 0) {
|
|
826
|
+
const next = stack.pop();
|
|
827
|
+
active += 1;
|
|
828
|
+
visit(next.dir, next.included);
|
|
829
|
+
}
|
|
830
|
+
if (outstanding === 0 && resolveDrained !== null) {
|
|
831
|
+
const resolve = resolveDrained;
|
|
832
|
+
resolveDrained = null;
|
|
833
|
+
resolve();
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
async function visit(dir, included) {
|
|
837
|
+
try {
|
|
838
|
+
if (signal?.aborted) {
|
|
839
|
+
throw new SweepError("CANCELLED", "扫描在遍历任务检查点被取消", {
|
|
840
|
+
phase: "scan"
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
let entries;
|
|
844
|
+
try {
|
|
845
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
846
|
+
} catch {
|
|
847
|
+
warnings.push({
|
|
848
|
+
code: "SCAN_DIR_UNREADABLE",
|
|
849
|
+
message: `目录不可读, 已跳过: ${dir}`,
|
|
850
|
+
path: dir
|
|
851
|
+
});
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
for (const entry of entries) {
|
|
855
|
+
if (!entry.isDirectory())
|
|
856
|
+
continue;
|
|
857
|
+
const name = entry.name;
|
|
858
|
+
if (name === NODE_MODULES) {
|
|
859
|
+
if (!included)
|
|
860
|
+
continue;
|
|
861
|
+
const target = join2(dir, name);
|
|
862
|
+
const key = dedupeKey(await realpath3(target).catch(() => target), style);
|
|
863
|
+
if (!hits.has(key)) {
|
|
864
|
+
const hit = { project: dir, target, root };
|
|
865
|
+
hits.set(key, hit);
|
|
866
|
+
onProgress?.({ kind: "hit", hit });
|
|
867
|
+
}
|
|
868
|
+
continue;
|
|
869
|
+
}
|
|
870
|
+
if (name === GIT_DIR)
|
|
871
|
+
continue;
|
|
872
|
+
const childIncluded = included || include.has(name);
|
|
873
|
+
if (!included && include.has(name)) {
|
|
874
|
+
includeCounts.set(name, (includeCounts.get(name) ?? 0) + 1);
|
|
875
|
+
}
|
|
876
|
+
if (exclude.has(name)) {
|
|
877
|
+
excludeCounts.set(name, (excludeCounts.get(name) ?? 0) + 1);
|
|
878
|
+
continue;
|
|
879
|
+
}
|
|
880
|
+
stack.push({ dir: join2(dir, name), included: childIncluded });
|
|
881
|
+
outstanding += 1;
|
|
882
|
+
}
|
|
883
|
+
} catch (error) {
|
|
884
|
+
if (failures.length === 0)
|
|
885
|
+
failures.push(error);
|
|
886
|
+
} finally {
|
|
887
|
+
active -= 1;
|
|
888
|
+
outstanding -= 1;
|
|
889
|
+
pump();
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
pump();
|
|
893
|
+
await drained;
|
|
894
|
+
if (failures.length > 0)
|
|
895
|
+
throw failures[0];
|
|
896
|
+
}
|
|
897
|
+
function createParallelScanner() {
|
|
898
|
+
return {
|
|
899
|
+
name: "parallel",
|
|
900
|
+
async scan(options) {
|
|
901
|
+
const warnings = [];
|
|
902
|
+
const exclude = new Set(options.exclude);
|
|
903
|
+
const excludeCounts = new Map;
|
|
904
|
+
for (const name of options.exclude) {
|
|
905
|
+
if (!excludeCounts.has(name))
|
|
906
|
+
excludeCounts.set(name, 0);
|
|
907
|
+
}
|
|
908
|
+
const include = new Set(options.include);
|
|
909
|
+
const includeCounts = new Map;
|
|
910
|
+
for (const name of options.include) {
|
|
911
|
+
if (!includeCounts.has(name))
|
|
912
|
+
includeCounts.set(name, 0);
|
|
913
|
+
}
|
|
914
|
+
const hitsByRealTarget = new Map;
|
|
915
|
+
const style = nativeStyle();
|
|
916
|
+
const seenRoots = new Set;
|
|
917
|
+
const roots = [];
|
|
918
|
+
for (const root of options.roots) {
|
|
919
|
+
let key;
|
|
920
|
+
try {
|
|
921
|
+
const resolved = await realpath3(root);
|
|
922
|
+
if (!(await stat2(resolved)).isDirectory()) {
|
|
923
|
+
warnings.push({
|
|
924
|
+
code: "SCAN_ROOT_NOT_DIR",
|
|
925
|
+
message: `根不是目录, 已跳过: ${root}`,
|
|
926
|
+
path: root
|
|
927
|
+
});
|
|
928
|
+
continue;
|
|
929
|
+
}
|
|
930
|
+
key = dedupeKey(resolved, style);
|
|
931
|
+
} catch (error) {
|
|
932
|
+
warnings.push(rootFailureWarning(error, root));
|
|
933
|
+
continue;
|
|
934
|
+
}
|
|
935
|
+
if (seenRoots.has(key))
|
|
936
|
+
continue;
|
|
937
|
+
seenRoots.add(key);
|
|
938
|
+
roots.push(root);
|
|
939
|
+
}
|
|
940
|
+
const context = {
|
|
941
|
+
style,
|
|
942
|
+
exclude,
|
|
943
|
+
excludeCounts,
|
|
944
|
+
include,
|
|
945
|
+
includeCounts,
|
|
946
|
+
hits: hitsByRealTarget,
|
|
947
|
+
warnings,
|
|
948
|
+
signal: options.signal,
|
|
949
|
+
onProgress: options.onProgress
|
|
950
|
+
};
|
|
951
|
+
for (const root of roots) {
|
|
952
|
+
await walkRoot(root, context);
|
|
953
|
+
}
|
|
954
|
+
const hits = [...hitsByRealTarget.values()].sort(compareTarget);
|
|
955
|
+
const excludeMatches = options.exclude.map((name) => ({
|
|
956
|
+
name,
|
|
957
|
+
hits: excludeCounts.get(name) ?? 0
|
|
958
|
+
}));
|
|
959
|
+
const includeMatches = options.include.map((name) => ({
|
|
960
|
+
name,
|
|
961
|
+
hits: includeCounts.get(name) ?? 0
|
|
962
|
+
}));
|
|
963
|
+
return { hits, warnings, excludeMatches, includeMatches };
|
|
964
|
+
}
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
// src/size-du.ts
|
|
968
|
+
import { spawn } from "node:child_process";
|
|
969
|
+
import { accessSync, constants } from "node:fs";
|
|
970
|
+
var DU_PROBES = ["/usr/bin/du", "/bin/du"];
|
|
971
|
+
var hasControlChar = (target) => target.includes(`
|
|
972
|
+
`) || target.includes("\r");
|
|
973
|
+
var PROG_PREFIX_RE = /^(?:\/[^\s:]*)?[a-z][a-z0-9_-]*:\s+/;
|
|
974
|
+
function findDu(platform = process.platform) {
|
|
975
|
+
if (platform === "win32")
|
|
976
|
+
return null;
|
|
977
|
+
for (const probe of DU_PROBES) {
|
|
978
|
+
try {
|
|
979
|
+
accessSync(probe, constants.X_OK);
|
|
980
|
+
return probe;
|
|
981
|
+
} catch {}
|
|
982
|
+
}
|
|
983
|
+
return null;
|
|
984
|
+
}
|
|
985
|
+
function runDu(bin, targets) {
|
|
986
|
+
return new Promise((resolve) => {
|
|
987
|
+
const child = spawn(bin, ["-sk", "--", ...targets], {
|
|
988
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
989
|
+
});
|
|
990
|
+
let stdout = "";
|
|
991
|
+
let stderr = "";
|
|
992
|
+
child.stdout.on("data", (chunk) => {
|
|
993
|
+
stdout += chunk;
|
|
994
|
+
});
|
|
995
|
+
child.stderr.on("data", (chunk) => {
|
|
996
|
+
stderr += chunk;
|
|
997
|
+
});
|
|
998
|
+
child.on("error", (error) => {
|
|
999
|
+
resolve({ stdout, stderr: `${stderr}${String(error)}` });
|
|
1000
|
+
});
|
|
1001
|
+
child.on("close", () => resolve({ stdout, stderr }));
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
function parseDuSizes(stdout) {
|
|
1005
|
+
const sizes = new Map;
|
|
1006
|
+
let duplicated = false;
|
|
1007
|
+
for (const line of stdout.split(`
|
|
1008
|
+
`)) {
|
|
1009
|
+
const match = /^(\d+)\t(.+)$/.exec(line);
|
|
1010
|
+
if (match === null)
|
|
1011
|
+
continue;
|
|
1012
|
+
const sizeKiB = match[1];
|
|
1013
|
+
const path = match[2];
|
|
1014
|
+
if (sizeKiB === undefined || path === undefined)
|
|
1015
|
+
continue;
|
|
1016
|
+
if (sizes.has(path))
|
|
1017
|
+
duplicated = true;
|
|
1018
|
+
sizes.set(path, Number(sizeKiB) * 1024);
|
|
1019
|
+
}
|
|
1020
|
+
return { sizes, duplicated };
|
|
1021
|
+
}
|
|
1022
|
+
function assessDuOutput(stdout, safeTargets) {
|
|
1023
|
+
const safeSet = new Set(safeTargets);
|
|
1024
|
+
const parsed = parseDuSizes(stdout);
|
|
1025
|
+
let unexpected = false;
|
|
1026
|
+
for (const path of parsed.sizes.keys()) {
|
|
1027
|
+
if (!safeSet.has(path))
|
|
1028
|
+
unexpected = true;
|
|
1029
|
+
}
|
|
1030
|
+
const intact = !parsed.duplicated && parsed.sizes.size <= safeTargets.length && !unexpected;
|
|
1031
|
+
return {
|
|
1032
|
+
sizes: parsed.sizes,
|
|
1033
|
+
intact,
|
|
1034
|
+
duplicated: parsed.duplicated,
|
|
1035
|
+
unexpected
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
function describeAnomaly(assessment) {
|
|
1039
|
+
const shapes = [];
|
|
1040
|
+
if (assessment.duplicated)
|
|
1041
|
+
shapes.push("同一路径多行");
|
|
1042
|
+
if (assessment.unexpected)
|
|
1043
|
+
shapes.push("含输入之外的路径");
|
|
1044
|
+
if (shapes.length === 0)
|
|
1045
|
+
shapes.push("行数与输入不符");
|
|
1046
|
+
return shapes.join(" / ");
|
|
1047
|
+
}
|
|
1048
|
+
function describeDuFailure(detail) {
|
|
1049
|
+
if (/no such file or directory/i.test(detail))
|
|
1050
|
+
return { missing: true, reason: "不存在" };
|
|
1051
|
+
if (/permission denied/i.test(detail))
|
|
1052
|
+
return {
|
|
1053
|
+
missing: false,
|
|
1054
|
+
code: "SIZE_UNMEASURED_PERMISSION",
|
|
1055
|
+
reason: "权限不足, 无法读取"
|
|
1056
|
+
};
|
|
1057
|
+
if (/not a directory/i.test(detail))
|
|
1058
|
+
return {
|
|
1059
|
+
missing: false,
|
|
1060
|
+
code: "SIZE_UNMEASURED_NOT_DIR",
|
|
1061
|
+
reason: "不是目录"
|
|
1062
|
+
};
|
|
1063
|
+
if (/too many levels of symbolic links/i.test(detail)) {
|
|
1064
|
+
return {
|
|
1065
|
+
missing: false,
|
|
1066
|
+
code: "SIZE_UNMEASURED_LOOP",
|
|
1067
|
+
reason: "符号链接层级过深"
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
return {
|
|
1071
|
+
missing: false,
|
|
1072
|
+
code: "SIZE_UNMEASURED_OTHER",
|
|
1073
|
+
reason: `读取失败 (${detail})`
|
|
1074
|
+
};
|
|
1075
|
+
}
|
|
1076
|
+
function parseDuErrorLine(line) {
|
|
1077
|
+
const body = line.replace(PROG_PREFIX_RE, "");
|
|
1078
|
+
const gnu = /^cannot\s+(?:access|read directory|stat|open)\s+'(.*)':\s+(.+)$/.exec(body);
|
|
1079
|
+
if (gnu !== null) {
|
|
1080
|
+
const path = gnu[1];
|
|
1081
|
+
const detail = gnu[2];
|
|
1082
|
+
if (path !== undefined && detail !== undefined)
|
|
1083
|
+
return { path, detail };
|
|
1084
|
+
}
|
|
1085
|
+
const match = /^(.+):\s+(.+)$/.exec(body);
|
|
1086
|
+
if (match === null)
|
|
1087
|
+
return null;
|
|
1088
|
+
const path = match[1];
|
|
1089
|
+
const detail = match[2];
|
|
1090
|
+
if (path === undefined || detail === undefined)
|
|
1091
|
+
return null;
|
|
1092
|
+
return { path, detail };
|
|
1093
|
+
}
|
|
1094
|
+
function createDuSizer(bin = findDu()) {
|
|
1095
|
+
return {
|
|
1096
|
+
name: "du",
|
|
1097
|
+
basis: "disk-usage",
|
|
1098
|
+
async measure(targets, options) {
|
|
1099
|
+
if (bin === null) {
|
|
1100
|
+
return {
|
|
1101
|
+
entries: [],
|
|
1102
|
+
basis: "disk-usage",
|
|
1103
|
+
warnings: [
|
|
1104
|
+
{
|
|
1105
|
+
code: "SIZE_DU_UNAVAILABLE",
|
|
1106
|
+
message: "du 候选不可用: /usr/bin/du 与 /bin/du 均不存在, 本候选跳过体积统计"
|
|
1107
|
+
}
|
|
1108
|
+
],
|
|
1109
|
+
unmeasured: [],
|
|
1110
|
+
gone: []
|
|
1111
|
+
};
|
|
1112
|
+
}
|
|
1113
|
+
if (targets.length === 0) {
|
|
1114
|
+
return {
|
|
1115
|
+
entries: [],
|
|
1116
|
+
basis: "disk-usage",
|
|
1117
|
+
warnings: [],
|
|
1118
|
+
unmeasured: [],
|
|
1119
|
+
gone: []
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
const sorted = [...targets].sort();
|
|
1123
|
+
const warnings = [];
|
|
1124
|
+
const entries = [];
|
|
1125
|
+
const unmeasured = [];
|
|
1126
|
+
const gone = [];
|
|
1127
|
+
const emit = options?.onProgress;
|
|
1128
|
+
const safeTargets = sorted.filter((target) => !hasControlChar(target));
|
|
1129
|
+
const safeSet = new Set(safeTargets);
|
|
1130
|
+
const sizes = new Map;
|
|
1131
|
+
const failures = new Map;
|
|
1132
|
+
let intact = true;
|
|
1133
|
+
if (safeTargets.length > 0) {
|
|
1134
|
+
const { stdout, stderr } = await runDu(bin, safeTargets);
|
|
1135
|
+
const assessment = assessDuOutput(stdout, safeTargets);
|
|
1136
|
+
intact = assessment.intact;
|
|
1137
|
+
if (!intact) {
|
|
1138
|
+
warnings.push({
|
|
1139
|
+
code: "SIZE_DU_OUTPUT_MISMATCH",
|
|
1140
|
+
message: `du 输出与输入集合不符 (${describeAnomaly(assessment)}): 本批 ${safeTargets.length} 个目标的体积均未采信`
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
for (const [path, bytes] of assessment.sizes)
|
|
1144
|
+
sizes.set(path, bytes);
|
|
1145
|
+
for (const line of stderr.split(`
|
|
1146
|
+
`)) {
|
|
1147
|
+
if (line.trim() === "")
|
|
1148
|
+
continue;
|
|
1149
|
+
const errorLine = parseDuErrorLine(line);
|
|
1150
|
+
if (errorLine === null) {
|
|
1151
|
+
warnings.push({
|
|
1152
|
+
code: "SIZE_DU_LINE_UNATTRIBUTED",
|
|
1153
|
+
message: `体积统计失败 (未归因): ${line.replace(PROG_PREFIX_RE, "").trim()}`
|
|
1154
|
+
});
|
|
1155
|
+
continue;
|
|
1156
|
+
}
|
|
1157
|
+
const failure = describeDuFailure(errorLine.detail);
|
|
1158
|
+
if (!safeSet.has(errorLine.path)) {
|
|
1159
|
+
warnings.push({
|
|
1160
|
+
code: "SIZE_SUBPATH_FAILED",
|
|
1161
|
+
message: `体积统计失败 (${failure.reason}): ${errorLine.path}`,
|
|
1162
|
+
path: errorLine.path
|
|
1163
|
+
});
|
|
1164
|
+
continue;
|
|
1165
|
+
}
|
|
1166
|
+
failures.set(errorLine.path, failure);
|
|
1167
|
+
}
|
|
1168
|
+
for (const path of failures.keys())
|
|
1169
|
+
sizes.delete(path);
|
|
1170
|
+
}
|
|
1171
|
+
const pushUnmeasured = (target, code, reason) => {
|
|
1172
|
+
unmeasured.push({ target, code, reason });
|
|
1173
|
+
emit?.({ kind: "unmeasured", target, code, reason });
|
|
1174
|
+
};
|
|
1175
|
+
for (const target of sorted) {
|
|
1176
|
+
if (options?.signal?.aborted) {
|
|
1177
|
+
throw new SweepError("CANCELLED", "体积统计在逐目标检查点被取消", {
|
|
1178
|
+
phase: "measure"
|
|
1179
|
+
});
|
|
1180
|
+
}
|
|
1181
|
+
if (hasControlChar(target)) {
|
|
1182
|
+
pushUnmeasured(target, "SIZE_UNMEASURED_CONTROL_CHAR", "路径含控制字符");
|
|
1183
|
+
continue;
|
|
1184
|
+
}
|
|
1185
|
+
if (!intact) {
|
|
1186
|
+
pushUnmeasured(target, "SIZE_UNMEASURED_UNPARSEABLE", "输出不可解析");
|
|
1187
|
+
continue;
|
|
1188
|
+
}
|
|
1189
|
+
const bytes = sizes.get(target);
|
|
1190
|
+
if (bytes !== undefined) {
|
|
1191
|
+
entries.push({ target, bytes });
|
|
1192
|
+
emit?.({ kind: "measured", target, bytes, basis: "disk-usage" });
|
|
1193
|
+
continue;
|
|
1194
|
+
}
|
|
1195
|
+
const failure = failures.get(target);
|
|
1196
|
+
if (failure === undefined) {
|
|
1197
|
+
pushUnmeasured(target, "SIZE_UNMEASURED_UNPARSEABLE", "输出不可解析");
|
|
1198
|
+
continue;
|
|
1199
|
+
}
|
|
1200
|
+
if (failure.missing) {
|
|
1201
|
+
gone.push(target);
|
|
1202
|
+
warnings.push({
|
|
1203
|
+
code: "SIZE_TARGET_VANISHED",
|
|
1204
|
+
message: `体积统计失败 (不存在): ${target}`,
|
|
1205
|
+
path: target
|
|
1206
|
+
});
|
|
1207
|
+
emit?.({ kind: "gone", target });
|
|
1208
|
+
continue;
|
|
1209
|
+
}
|
|
1210
|
+
pushUnmeasured(target, failure.code, failure.reason);
|
|
1211
|
+
}
|
|
1212
|
+
return { entries, basis: "disk-usage", warnings, unmeasured, gone };
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
// src/size-js.ts
|
|
1218
|
+
import { readdir as readdir2, stat as stat3 } from "node:fs/promises";
|
|
1219
|
+
import { join as join3 } from "node:path";
|
|
1220
|
+
function describeFailure(code) {
|
|
1221
|
+
switch (code) {
|
|
1222
|
+
case "ENOENT":
|
|
1223
|
+
return { missing: true, reason: "不存在" };
|
|
1224
|
+
case "EACCES":
|
|
1225
|
+
case "EPERM":
|
|
1226
|
+
return {
|
|
1227
|
+
missing: false,
|
|
1228
|
+
code: "SIZE_UNMEASURED_PERMISSION",
|
|
1229
|
+
reason: "权限不足, 无法读取"
|
|
1230
|
+
};
|
|
1231
|
+
case "ENOTDIR":
|
|
1232
|
+
return {
|
|
1233
|
+
missing: false,
|
|
1234
|
+
code: "SIZE_UNMEASURED_NOT_DIR",
|
|
1235
|
+
reason: "不是目录"
|
|
1236
|
+
};
|
|
1237
|
+
case "ELOOP":
|
|
1238
|
+
return {
|
|
1239
|
+
missing: false,
|
|
1240
|
+
code: "SIZE_UNMEASURED_LOOP",
|
|
1241
|
+
reason: "符号链接层级过深"
|
|
1242
|
+
};
|
|
1243
|
+
default:
|
|
1244
|
+
return {
|
|
1245
|
+
missing: false,
|
|
1246
|
+
code: "SIZE_UNMEASURED_OTHER",
|
|
1247
|
+
reason: code === undefined ? "读取失败" : `读取失败 (${code})`
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
function errorCode(error) {
|
|
1252
|
+
return error?.code;
|
|
1253
|
+
}
|
|
1254
|
+
async function sumEntries(dirents, dir, warnings) {
|
|
1255
|
+
let total = 0;
|
|
1256
|
+
for (const dirent of dirents) {
|
|
1257
|
+
if (dirent.isSymbolicLink())
|
|
1258
|
+
continue;
|
|
1259
|
+
const path = join3(dir, dirent.name);
|
|
1260
|
+
if (dirent.isDirectory()) {
|
|
1261
|
+
try {
|
|
1262
|
+
total += await sumEntries(await readdir2(path, { withFileTypes: true }), path, warnings);
|
|
1263
|
+
} catch (error) {
|
|
1264
|
+
warnings.push({
|
|
1265
|
+
code: "SIZE_SUBPATH_FAILED",
|
|
1266
|
+
message: `体积统计失败 (${describeFailure(errorCode(error)).reason}): ${path}`,
|
|
1267
|
+
path
|
|
1268
|
+
});
|
|
1269
|
+
}
|
|
1270
|
+
} else if (dirent.isFile()) {
|
|
1271
|
+
try {
|
|
1272
|
+
total += (await stat3(path)).size;
|
|
1273
|
+
} catch (error) {
|
|
1274
|
+
warnings.push({
|
|
1275
|
+
code: "SIZE_SUBPATH_FAILED",
|
|
1276
|
+
message: `体积统计失败 (${describeFailure(errorCode(error)).reason}): ${path}`,
|
|
1277
|
+
path
|
|
1278
|
+
});
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
return total;
|
|
1283
|
+
}
|
|
1284
|
+
function createJsSizer() {
|
|
1285
|
+
return {
|
|
1286
|
+
name: "js",
|
|
1287
|
+
basis: "logical-bytes",
|
|
1288
|
+
async measure(targets, options) {
|
|
1289
|
+
const warnings = [];
|
|
1290
|
+
const entries = [];
|
|
1291
|
+
const unmeasured = [];
|
|
1292
|
+
const gone = [];
|
|
1293
|
+
const emit = options?.onProgress;
|
|
1294
|
+
const pushUnmeasured = (target, code, reason) => {
|
|
1295
|
+
unmeasured.push({ target, code, reason });
|
|
1296
|
+
emit?.({ kind: "unmeasured", target, code, reason });
|
|
1297
|
+
};
|
|
1298
|
+
for (const target of [...targets].sort()) {
|
|
1299
|
+
if (options?.signal?.aborted) {
|
|
1300
|
+
throw new SweepError("CANCELLED", "体积统计在逐目标检查点被取消", {
|
|
1301
|
+
phase: "measure"
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
let dirents;
|
|
1305
|
+
try {
|
|
1306
|
+
dirents = await readdir2(target, { withFileTypes: true });
|
|
1307
|
+
} catch (error) {
|
|
1308
|
+
const failure = describeFailure(errorCode(error));
|
|
1309
|
+
if (failure.missing) {
|
|
1310
|
+
gone.push(target);
|
|
1311
|
+
warnings.push({
|
|
1312
|
+
code: "SIZE_TARGET_VANISHED",
|
|
1313
|
+
message: `体积统计失败 (${failure.reason}): ${target}`,
|
|
1314
|
+
path: target
|
|
1315
|
+
});
|
|
1316
|
+
emit?.({ kind: "gone", target });
|
|
1317
|
+
} else {
|
|
1318
|
+
pushUnmeasured(target, failure.code, failure.reason);
|
|
1319
|
+
}
|
|
1320
|
+
continue;
|
|
1321
|
+
}
|
|
1322
|
+
const bytes = await sumEntries(dirents, target, warnings);
|
|
1323
|
+
entries.push({ target, bytes });
|
|
1324
|
+
emit?.({ kind: "measured", target, bytes, basis: "logical-bytes" });
|
|
1325
|
+
}
|
|
1326
|
+
return { entries, basis: "logical-bytes", warnings, unmeasured, gone };
|
|
1327
|
+
}
|
|
1328
|
+
};
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
// src/size.ts
|
|
1332
|
+
function createSizer() {
|
|
1333
|
+
return findDu() !== null ? createDuSizer() : createJsSizer();
|
|
1334
|
+
}
|
|
1335
|
+
// src/skip.ts
|
|
1336
|
+
var SUSPECT_HINT = "已跳过 (加 --force 一并清理)";
|
|
1337
|
+
var CROSS_DEVICE_NOTES = {
|
|
1338
|
+
"on-path": "跨设备: 根与目标之间有挂载点",
|
|
1339
|
+
"target-itself": "跨设备: 目标本体即挂载点"
|
|
1340
|
+
};
|
|
1341
|
+
var CROSS_DEVICE_HINTS = {
|
|
1342
|
+
"on-path": "已跳过 (把该挂载点声明为独立根即可清理)",
|
|
1343
|
+
"target-itself": "已跳过 (挂载点无法删除, 需先卸载该卷)"
|
|
1344
|
+
};
|
|
1345
|
+
var CROSS_DEVICE_TRAILER_ACTIONS = {
|
|
1346
|
+
"on-path": "把根与目标之间的挂载点声明为独立根即可清理",
|
|
1347
|
+
"target-itself": "目标本体即挂载点, 需先卸载该卷"
|
|
1348
|
+
};
|
|
1349
|
+
function crossDeviceNote(kind) {
|
|
1350
|
+
return CROSS_DEVICE_NOTES[kind];
|
|
1351
|
+
}
|
|
1352
|
+
function skipReasonOf(entry, crossDevice, policy) {
|
|
1353
|
+
const deviceKind = crossDevice.get(entry.target);
|
|
1354
|
+
if (deviceKind !== undefined) {
|
|
1355
|
+
return deviceKind === "on-path" ? "cross-device:on-path" : "cross-device:target-itself";
|
|
1356
|
+
}
|
|
1357
|
+
if (entry.bytes === undefined)
|
|
1358
|
+
return "unmeasured";
|
|
1359
|
+
if (entry.suspect && !policy.releaseSuspects)
|
|
1360
|
+
return "suspect-install-tree";
|
|
1361
|
+
return null;
|
|
1362
|
+
}
|
|
1363
|
+
function skipsBatch(entry, crossDevice, policy) {
|
|
1364
|
+
return skipReasonOf(entry, crossDevice, policy) !== null;
|
|
1365
|
+
}
|
|
1366
|
+
function toSkipCandidates(hits, size, options) {
|
|
1367
|
+
const bytesOf = new Map(size.entries.map((entry) => [entry.target, entry.bytes]));
|
|
1368
|
+
const reasonOf = new Map(size.unmeasured.map((item) => [item.target, item.reason]));
|
|
1369
|
+
return hits.map((hit) => {
|
|
1370
|
+
const classification = classifyTarget(hit.target, options);
|
|
1371
|
+
return {
|
|
1372
|
+
target: hit.target,
|
|
1373
|
+
bytes: bytesOf.get(hit.target),
|
|
1374
|
+
unmeasuredReason: bytesOf.get(hit.target) === undefined ? reasonOf.get(hit.target) : undefined,
|
|
1375
|
+
suspect: classification.kind === "suspect-install-tree"
|
|
1376
|
+
};
|
|
1377
|
+
});
|
|
1378
|
+
}
|
|
1379
|
+
function deletionBatch(entries, crossDevice, policy) {
|
|
1380
|
+
return entries.filter((entry) => !skipsBatch(entry, crossDevice, policy)).map((entry) => entry.target);
|
|
1381
|
+
}
|
|
1382
|
+
function noteOf(entry, reason) {
|
|
1383
|
+
if (reason === "suspect-install-tree")
|
|
1384
|
+
return SUSPECT_HINT;
|
|
1385
|
+
if (reason === "unmeasured") {
|
|
1386
|
+
return `体积统计失败: ${entry.unmeasuredReason ?? "原因未知"}`;
|
|
1387
|
+
}
|
|
1388
|
+
return CROSS_DEVICE_HINTS[reason === "cross-device:on-path" ? "on-path" : "target-itself"];
|
|
1389
|
+
}
|
|
1390
|
+
function collectSkips(entries, crossDevice, policy) {
|
|
1391
|
+
const suspectSkipped = policy.releaseSuspects ? [] : entries.filter((entry) => entry.suspect);
|
|
1392
|
+
const deviceSkipped = entries.filter((entry) => crossDevice.has(entry.target));
|
|
1393
|
+
const trailer = [
|
|
1394
|
+
...suspectSkipped.length > 0 ? [`疑似安装树 ${suspectSkipped.length} 处默认跳过 (加 --force 一并清理)`] : [],
|
|
1395
|
+
...["on-path", "target-itself"].flatMap((kind) => {
|
|
1396
|
+
const count = deviceSkipped.filter((entry) => crossDevice.get(entry.target) === kind).length;
|
|
1397
|
+
return count === 0 ? [] : [
|
|
1398
|
+
`跨设备目标 ${count} 处默认跳过 (${CROSS_DEVICE_TRAILER_ACTIONS[kind]})`
|
|
1399
|
+
];
|
|
1400
|
+
})
|
|
1401
|
+
];
|
|
1402
|
+
const hints = new Map;
|
|
1403
|
+
for (const entry of suspectSkipped) {
|
|
1404
|
+
if (entry.bytes !== undefined)
|
|
1405
|
+
hints.set(entry.target, SUSPECT_HINT);
|
|
1406
|
+
}
|
|
1407
|
+
for (const entry of deviceSkipped) {
|
|
1408
|
+
const kind = crossDevice.get(entry.target);
|
|
1409
|
+
if (entry.bytes !== undefined && kind !== undefined) {
|
|
1410
|
+
hints.set(entry.target, CROSS_DEVICE_HINTS[kind]);
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
const book = [];
|
|
1414
|
+
for (const entry of entries) {
|
|
1415
|
+
const reason = skipReasonOf(entry, crossDevice, policy);
|
|
1416
|
+
if (reason === null)
|
|
1417
|
+
continue;
|
|
1418
|
+
book.push({ target: entry.target, reason, note: noteOf(entry, reason) });
|
|
1419
|
+
}
|
|
1420
|
+
return { entries: book, trailer, hints };
|
|
1421
|
+
}
|
|
1422
|
+
// src/summary.ts
|
|
1423
|
+
var SUCCESS_KINDS = new Set([
|
|
1424
|
+
"removed",
|
|
1425
|
+
"missing",
|
|
1426
|
+
"stale"
|
|
1427
|
+
]);
|
|
1428
|
+
function isSuccessOutcome(outcome) {
|
|
1429
|
+
return SUCCESS_KINDS.has(outcome.kind);
|
|
1430
|
+
}
|
|
1431
|
+
function summarizeReport(report) {
|
|
1432
|
+
const counts = {
|
|
1433
|
+
removed: 0,
|
|
1434
|
+
missing: 0,
|
|
1435
|
+
stale: 0,
|
|
1436
|
+
failed: 0,
|
|
1437
|
+
rejected: 0,
|
|
1438
|
+
"not-attempted": 0,
|
|
1439
|
+
"not-expected": 0,
|
|
1440
|
+
skipped: 0
|
|
1441
|
+
};
|
|
1442
|
+
for (const entry of report.entries)
|
|
1443
|
+
counts[entry.outcome.kind] += 1;
|
|
1444
|
+
return {
|
|
1445
|
+
counts,
|
|
1446
|
+
succeeded: counts.removed + counts.missing + counts.stale,
|
|
1447
|
+
unprocessed: counts.skipped + counts.rejected + counts["not-attempted"] + counts["not-expected"],
|
|
1448
|
+
failed: counts.failed,
|
|
1449
|
+
aborted: report.removal?.aborted !== undefined
|
|
1450
|
+
};
|
|
1451
|
+
}
|
|
1452
|
+
// src/sweep.ts
|
|
1453
|
+
import { homedir as homedir4 } from "node:os";
|
|
1454
|
+
var invalidArgument = (field, message) => new SweepError("INVALID_ARGUMENT", `${message} (字段: ${field})`, { field });
|
|
1455
|
+
function assertNameArray(value, field, required) {
|
|
1456
|
+
if (value === undefined) {
|
|
1457
|
+
if (required)
|
|
1458
|
+
throw invalidArgument(field, "为必填项");
|
|
1459
|
+
return;
|
|
1460
|
+
}
|
|
1461
|
+
if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item === ""))
|
|
1462
|
+
throw invalidArgument(field, "必须是非空字符串数组");
|
|
1463
|
+
if (required && value.length === 0)
|
|
1464
|
+
throw invalidArgument(field, "不能为空数组");
|
|
1465
|
+
}
|
|
1466
|
+
function assertShape(options) {
|
|
1467
|
+
if (typeof options !== "object" || options === null)
|
|
1468
|
+
throw invalidArgument("options", "构造选项必须是对象");
|
|
1469
|
+
assertNameArray(options.roots, "roots", true);
|
|
1470
|
+
assertNameArray(options.exclude, "exclude", false);
|
|
1471
|
+
assertNameArray(options.include, "include", false);
|
|
1472
|
+
if (options.home !== undefined && options.home !== null && typeof options.home !== "string")
|
|
1473
|
+
throw invalidArgument("home", "必须是字符串或 null");
|
|
1474
|
+
if (options.policy !== undefined && (typeof options.policy !== "object" || options.policy === null || typeof options.policy.releaseSuspects !== "boolean"))
|
|
1475
|
+
throw invalidArgument("policy", "releaseSuspects 必须是布尔值");
|
|
1476
|
+
}
|
|
1477
|
+
function resolveOptions(options) {
|
|
1478
|
+
assertShape(options);
|
|
1479
|
+
return Object.freeze({
|
|
1480
|
+
roots: [...options.roots],
|
|
1481
|
+
exclude: mergeNames(options.exclude ?? [...DEFAULT_EXCLUDE], []),
|
|
1482
|
+
include: mergeNames(options.include ?? [], []),
|
|
1483
|
+
home: options.home === undefined ? homedir4() : options.home,
|
|
1484
|
+
style: options.style ?? nativeStyle(),
|
|
1485
|
+
policy: Object.freeze({
|
|
1486
|
+
releaseSuspects: options.policy?.releaseSuspects ?? false
|
|
1487
|
+
})
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
var cancelledAt = (phase) => new SweepError("CANCELLED", `清理在 ${phase} 阶段被取消`, { phase });
|
|
1491
|
+
async function withPhase(phase, emit, signal, work) {
|
|
1492
|
+
if (signal?.aborted)
|
|
1493
|
+
throw cancelledAt(phase);
|
|
1494
|
+
const startedAt = Date.now();
|
|
1495
|
+
emit?.({ kind: "phase", phase, status: "start" });
|
|
1496
|
+
const value = await work();
|
|
1497
|
+
emit?.({
|
|
1498
|
+
kind: "phase",
|
|
1499
|
+
phase,
|
|
1500
|
+
status: "done",
|
|
1501
|
+
elapsedMs: Date.now() - startedAt
|
|
1502
|
+
});
|
|
1503
|
+
return value;
|
|
1504
|
+
}
|
|
1505
|
+
async function executePlan(resolved, options, signal) {
|
|
1506
|
+
const emit = options?.onProgress;
|
|
1507
|
+
const roots = resolved.roots;
|
|
1508
|
+
const scanResult = await withPhase("scan", emit, signal, async () => {
|
|
1509
|
+
const result = await createParallelScanner().scan({
|
|
1510
|
+
roots,
|
|
1511
|
+
exclude: resolved.exclude,
|
|
1512
|
+
include: resolved.include,
|
|
1513
|
+
signal,
|
|
1514
|
+
onProgress: (event) => emit?.(event)
|
|
1515
|
+
});
|
|
1516
|
+
for (const warning of result.warnings)
|
|
1517
|
+
emit?.({ kind: "warning", warning });
|
|
1518
|
+
return result;
|
|
1519
|
+
});
|
|
1520
|
+
const targets = scanResult.hits.map((hit) => hit.target);
|
|
1521
|
+
const sizeResult = await withPhase("measure", emit, signal, async () => {
|
|
1522
|
+
const result = await createSizer().measure(targets, {
|
|
1523
|
+
signal,
|
|
1524
|
+
onProgress: (event) => {
|
|
1525
|
+
if (event.kind === "gone")
|
|
1526
|
+
return;
|
|
1527
|
+
emit?.(event);
|
|
1528
|
+
}
|
|
1529
|
+
});
|
|
1530
|
+
for (const warning of result.warnings)
|
|
1531
|
+
emit?.({ kind: "warning", warning });
|
|
1532
|
+
return result;
|
|
1533
|
+
});
|
|
1534
|
+
const classifications = await withPhase("classify", emit, signal, () => scanResult.hits.map((hit) => classifyTarget(hit.target, {
|
|
1535
|
+
home: resolved.home,
|
|
1536
|
+
style: resolved.style
|
|
1537
|
+
})));
|
|
1538
|
+
const crossDevice = await withPhase("device", emit, signal, async () => crossDeviceIndex(await findCrossDeviceTargets(targets, {
|
|
1539
|
+
roots,
|
|
1540
|
+
style: resolved.style
|
|
1541
|
+
})));
|
|
1542
|
+
return withPhase("plan", emit, signal, () => {
|
|
1543
|
+
const policy = resolved.policy;
|
|
1544
|
+
const bytesOf = new Map(sizeResult.entries.map((entry) => [
|
|
1545
|
+
entry.target,
|
|
1546
|
+
entry.bytes
|
|
1547
|
+
]));
|
|
1548
|
+
const unmeasuredOf = new Map(sizeResult.unmeasured.map((item) => [item.target, item]));
|
|
1549
|
+
const goneSet = new Set(sizeResult.gone);
|
|
1550
|
+
const prepared = [];
|
|
1551
|
+
for (let index = 0;index < scanResult.hits.length; index += 1) {
|
|
1552
|
+
const hit = scanResult.hits[index];
|
|
1553
|
+
const classification = classifications[index];
|
|
1554
|
+
if (hit === undefined || classification === undefined)
|
|
1555
|
+
continue;
|
|
1556
|
+
if (goneSet.has(hit.target))
|
|
1557
|
+
continue;
|
|
1558
|
+
const bytes = bytesOf.get(hit.target);
|
|
1559
|
+
prepared.push({
|
|
1560
|
+
hit,
|
|
1561
|
+
classification,
|
|
1562
|
+
candidate: {
|
|
1563
|
+
target: hit.target,
|
|
1564
|
+
bytes,
|
|
1565
|
+
unmeasuredReason: bytes === undefined ? unmeasuredOf.get(hit.target)?.reason : undefined,
|
|
1566
|
+
suspect: classification.kind === "suspect-install-tree"
|
|
1567
|
+
}
|
|
1568
|
+
});
|
|
1569
|
+
}
|
|
1570
|
+
const candidates = prepared.map((item) => item.candidate);
|
|
1571
|
+
const batch = deletionBatch(candidates, crossDevice, policy);
|
|
1572
|
+
const book = collectSkips(candidates, crossDevice, policy);
|
|
1573
|
+
const noteOf = new Map(book.entries.map((item) => [item.target, item.note]));
|
|
1574
|
+
const entries = [];
|
|
1575
|
+
for (const { hit, classification, candidate } of prepared) {
|
|
1576
|
+
const reason = skipReasonOf(candidate, crossDevice, policy);
|
|
1577
|
+
const deviceKind = crossDevice.get(hit.target);
|
|
1578
|
+
const unmeasured = unmeasuredOf.get(hit.target);
|
|
1579
|
+
entries.push({
|
|
1580
|
+
target: hit.target,
|
|
1581
|
+
project: hit.project,
|
|
1582
|
+
root: hit.root,
|
|
1583
|
+
bytes: candidate.bytes,
|
|
1584
|
+
basis: candidate.bytes === undefined ? undefined : sizeResult.basis,
|
|
1585
|
+
kind: classification.kind,
|
|
1586
|
+
kindReason: classification.reason,
|
|
1587
|
+
crossDevice: deviceKind,
|
|
1588
|
+
unmeasuredCode: unmeasured?.code,
|
|
1589
|
+
unmeasuredReason: unmeasured?.reason,
|
|
1590
|
+
inBatch: reason === null,
|
|
1591
|
+
skipReason: reason ?? undefined,
|
|
1592
|
+
skipNote: reason === null ? undefined : noteOf.get(hit.target)
|
|
1593
|
+
});
|
|
1594
|
+
if (reason !== null)
|
|
1595
|
+
emit?.({ kind: "skipped", target: hit.target, reason });
|
|
1596
|
+
}
|
|
1597
|
+
return {
|
|
1598
|
+
roots: [...resolved.roots],
|
|
1599
|
+
exclude: [...resolved.exclude],
|
|
1600
|
+
include: [...resolved.include],
|
|
1601
|
+
policy,
|
|
1602
|
+
basis: entries.length > 0 ? sizeResult.basis : undefined,
|
|
1603
|
+
entries,
|
|
1604
|
+
batch,
|
|
1605
|
+
skipped: [...book.entries],
|
|
1606
|
+
warnings: [...scanResult.warnings, ...sizeResult.warnings],
|
|
1607
|
+
nameMatches: {
|
|
1608
|
+
exclude: scanResult.excludeMatches,
|
|
1609
|
+
include: scanResult.includeMatches
|
|
1610
|
+
}
|
|
1611
|
+
};
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
function buildOutcomeEntries(plan, expectedSet, stale, rejected, removal) {
|
|
1615
|
+
const staleSet = new Set(stale);
|
|
1616
|
+
const rejectedMap = rejected.length > 0 ? new Map(rejected.map((item) => [item.target, item])) : undefined;
|
|
1617
|
+
const removedSet = new Set(removal?.removed ?? []);
|
|
1618
|
+
const missingSet = new Set(removal?.missing ?? []);
|
|
1619
|
+
const failedMap = new Map((removal?.failed ?? []).map((item) => [
|
|
1620
|
+
item.target,
|
|
1621
|
+
item
|
|
1622
|
+
]));
|
|
1623
|
+
const outcomeOf = (entry) => {
|
|
1624
|
+
if (!entry.inBatch)
|
|
1625
|
+
return { kind: "skipped", reason: entry.skipReason };
|
|
1626
|
+
if (expectedSet !== undefined && !expectedSet.has(entry.target))
|
|
1627
|
+
return { kind: "not-expected" };
|
|
1628
|
+
if (staleSet.has(entry.target))
|
|
1629
|
+
return { kind: "stale" };
|
|
1630
|
+
if (rejectedMap !== undefined)
|
|
1631
|
+
return { kind: "rejected", rejection: rejectedMap.get(entry.target) };
|
|
1632
|
+
if (removedSet.has(entry.target))
|
|
1633
|
+
return { kind: "removed" };
|
|
1634
|
+
if (missingSet.has(entry.target))
|
|
1635
|
+
return { kind: "missing" };
|
|
1636
|
+
const failure = failedMap.get(entry.target);
|
|
1637
|
+
if (failure !== undefined)
|
|
1638
|
+
return { kind: "failed", failure };
|
|
1639
|
+
return { kind: "not-attempted", code: removal.aborted.code };
|
|
1640
|
+
};
|
|
1641
|
+
return plan.entries.map((entry) => ({ ...entry, outcome: outcomeOf(entry) }));
|
|
1642
|
+
}
|
|
1643
|
+
async function executeRun(resolved, options, signal) {
|
|
1644
|
+
const emit = options?.onProgress;
|
|
1645
|
+
const startedAt = Date.now();
|
|
1646
|
+
const plan = await executePlan(resolved, options, signal);
|
|
1647
|
+
const expected = options?.expectedBatch;
|
|
1648
|
+
const expectedSet = expected === undefined ? undefined : new Set(expected);
|
|
1649
|
+
const face = expectedSet === undefined ? plan.batch : plan.batch.filter((target) => expectedSet.has(target));
|
|
1650
|
+
const liveSet = new Set(plan.batch);
|
|
1651
|
+
const drift = expected === undefined || expectedSet === undefined ? undefined : {
|
|
1652
|
+
added: plan.batch.filter((target) => !expectedSet.has(target)),
|
|
1653
|
+
removed: expected.filter((target) => !liveSet.has(target))
|
|
1654
|
+
};
|
|
1655
|
+
let validation;
|
|
1656
|
+
let removal;
|
|
1657
|
+
let stale = [];
|
|
1658
|
+
let rejected = [];
|
|
1659
|
+
if (face.length > 0) {
|
|
1660
|
+
const raw = await withPhase("validate", emit, signal, () => validateTargets(face, {
|
|
1661
|
+
roots: resolved.roots,
|
|
1662
|
+
home: resolved.home,
|
|
1663
|
+
style: resolved.style,
|
|
1664
|
+
signal
|
|
1665
|
+
}));
|
|
1666
|
+
const split = splitStaleRejections(raw.rejected, options?.staleTargets);
|
|
1667
|
+
stale = split.stale;
|
|
1668
|
+
rejected = split.rejected;
|
|
1669
|
+
validation = {
|
|
1670
|
+
accepted: raw.accepted,
|
|
1671
|
+
rejected,
|
|
1672
|
+
mappings: raw.mappings
|
|
1673
|
+
};
|
|
1674
|
+
if (rejected.length === 0) {
|
|
1675
|
+
removal = await withPhase("remove", emit, signal, async () => removeTargets(raw.accepted, {
|
|
1676
|
+
roots: await toTrustRoots(resolved.roots),
|
|
1677
|
+
signal,
|
|
1678
|
+
onProgress: (event) => {
|
|
1679
|
+
if (event.kind === "removed" || event.kind === "missing") {
|
|
1680
|
+
emit?.({
|
|
1681
|
+
kind: "removed",
|
|
1682
|
+
target: event.target,
|
|
1683
|
+
outcome: event.kind
|
|
1684
|
+
});
|
|
1685
|
+
return;
|
|
1686
|
+
}
|
|
1687
|
+
emit?.(event);
|
|
1688
|
+
}
|
|
1689
|
+
}));
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
let status;
|
|
1693
|
+
if (face.length === 0)
|
|
1694
|
+
status = "nothing-to-do";
|
|
1695
|
+
else if (rejected.length > 0)
|
|
1696
|
+
status = "rejected";
|
|
1697
|
+
else
|
|
1698
|
+
status = "executed";
|
|
1699
|
+
const entries = buildOutcomeEntries(plan, expectedSet, stale, rejected, removal);
|
|
1700
|
+
const releasedBytes = entries.reduce((sum, entry) => isSuccessOutcome(entry.outcome) ? sum + (entry.bytes ?? 0) : sum, 0);
|
|
1701
|
+
const report = {
|
|
1702
|
+
status,
|
|
1703
|
+
plan,
|
|
1704
|
+
validation,
|
|
1705
|
+
removal,
|
|
1706
|
+
entries,
|
|
1707
|
+
stale,
|
|
1708
|
+
releasedBytes,
|
|
1709
|
+
drift
|
|
1710
|
+
};
|
|
1711
|
+
emit?.({ kind: "done", status, elapsedMs: Date.now() - startedAt });
|
|
1712
|
+
return report;
|
|
1713
|
+
}
|
|
1714
|
+
function createSweeper(options) {
|
|
1715
|
+
const resolved = resolveOptions(options);
|
|
1716
|
+
return {
|
|
1717
|
+
options: resolved,
|
|
1718
|
+
async plan(planOptions) {
|
|
1719
|
+
const startedAt = Date.now();
|
|
1720
|
+
const plan = await executePlan(resolved, planOptions, planOptions?.signal);
|
|
1721
|
+
planOptions?.onProgress?.({
|
|
1722
|
+
kind: "plan-done",
|
|
1723
|
+
plan,
|
|
1724
|
+
elapsedMs: Date.now() - startedAt
|
|
1725
|
+
});
|
|
1726
|
+
return plan;
|
|
1727
|
+
},
|
|
1728
|
+
run(runOptions) {
|
|
1729
|
+
return executeRun(resolved, runOptions, runOptions?.signal);
|
|
1730
|
+
}
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
export {
|
|
1734
|
+
DEFAULT_EXCLUDE,
|
|
1735
|
+
POSIX_STYLE,
|
|
1736
|
+
SweepError,
|
|
1737
|
+
WIN32_STYLE,
|
|
1738
|
+
anchorChainPaths,
|
|
1739
|
+
classifyTarget,
|
|
1740
|
+
collectSkips,
|
|
1741
|
+
createParallelScanner as createScanner,
|
|
1742
|
+
createSizer,
|
|
1743
|
+
createSweeper,
|
|
1744
|
+
crossDeviceIndex,
|
|
1745
|
+
crossDeviceNote,
|
|
1746
|
+
dedupeKey,
|
|
1747
|
+
deletionBatch,
|
|
1748
|
+
findCrossDeviceTargets,
|
|
1749
|
+
firstSymlinkOnAnchor,
|
|
1750
|
+
firstSymlinkOnRoot,
|
|
1751
|
+
firstSymlinkOnTarget,
|
|
1752
|
+
formatBytes,
|
|
1753
|
+
fsDeviceProbe,
|
|
1754
|
+
hasNodeModulesLeaf,
|
|
1755
|
+
insideAnyRoot,
|
|
1756
|
+
isFilesystemRootBody,
|
|
1757
|
+
isHomeBody,
|
|
1758
|
+
isSuccessOutcome,
|
|
1759
|
+
isSweepError,
|
|
1760
|
+
loadConfig,
|
|
1761
|
+
loadResolvedConfig,
|
|
1762
|
+
mergeNames,
|
|
1763
|
+
nativeStyle,
|
|
1764
|
+
removeBatch,
|
|
1765
|
+
removeTargets,
|
|
1766
|
+
resolveConfigPath,
|
|
1767
|
+
sanitizeLine,
|
|
1768
|
+
sanitizeOutputLine,
|
|
1769
|
+
skipReasonOf,
|
|
1770
|
+
skipsBatch,
|
|
1771
|
+
summarizeReport,
|
|
1772
|
+
toSkipCandidates,
|
|
1773
|
+
toTrustRoots,
|
|
1774
|
+
validateTargets
|
|
1775
|
+
};
|