@iyowei/sweep-node-modules-cli 0.1.2 → 0.2.1
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 +2 -4
- package/README.zh-CN.md +2 -4
- package/dist/cli.js +967 -313
- package/dist/manifest.json +3 -3
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,15 +1,34 @@
|
|
|
1
1
|
// src/cli.ts
|
|
2
|
-
import { lstat as lstat3, mkdir,
|
|
3
|
-
import { homedir as
|
|
2
|
+
import { lstat as lstat3, mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { homedir as homedir6 } from "node:os";
|
|
4
4
|
import { basename, dirname } from "node:path";
|
|
5
|
-
|
|
6
|
-
// ../sweep-node-modules/src/classify.ts
|
|
7
|
-
import { homedir as homedir3 } from "node:os";
|
|
8
|
-
|
|
9
5
|
// ../sweep-node-modules/src/config.ts
|
|
10
6
|
import { readFile } from "node:fs/promises";
|
|
11
7
|
import { homedir } from "node:os";
|
|
12
8
|
import { posix, win32 } from "node:path";
|
|
9
|
+
|
|
10
|
+
// ../sweep-node-modules/src/errors.ts
|
|
11
|
+
var SWEEP_ERROR_CODES = new Set([
|
|
12
|
+
"CONFIG_READ_FAILED",
|
|
13
|
+
"CONFIG_CORRUPT_JSON",
|
|
14
|
+
"CONFIG_CORRUPT_SHAPE",
|
|
15
|
+
"CONFIG_ABSENT",
|
|
16
|
+
"INVALID_ARGUMENT",
|
|
17
|
+
"CANCELLED"
|
|
18
|
+
]);
|
|
19
|
+
|
|
20
|
+
class SweepError extends Error {
|
|
21
|
+
name = "SweepError";
|
|
22
|
+
code;
|
|
23
|
+
details;
|
|
24
|
+
constructor(code, message, details) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.details = details;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// ../sweep-node-modules/src/config.ts
|
|
13
32
|
var DEFAULT_EXCLUDE = [
|
|
14
33
|
".bun",
|
|
15
34
|
".npm",
|
|
@@ -66,20 +85,29 @@ function describeActual(value) {
|
|
|
66
85
|
function fieldError(container, field, optional) {
|
|
67
86
|
const value = container[field];
|
|
68
87
|
if (value === undefined) {
|
|
69
|
-
return optional ? null : `${field} 应为字符串数组 (实际: 缺失)
|
|
88
|
+
return optional ? null : { field, message: `${field} 应为字符串数组 (实际: 缺失)` };
|
|
70
89
|
}
|
|
71
90
|
if (!Array.isArray(value)) {
|
|
72
|
-
return
|
|
91
|
+
return {
|
|
92
|
+
field,
|
|
93
|
+
message: `${field} 应为字符串数组 (实际: ${describeActual(value)})`
|
|
94
|
+
};
|
|
73
95
|
}
|
|
74
96
|
const badIndex = value.findIndex((item) => typeof item !== "string");
|
|
75
97
|
if (badIndex !== -1) {
|
|
76
|
-
return
|
|
98
|
+
return {
|
|
99
|
+
field,
|
|
100
|
+
message: `${field} 第 ${badIndex + 1} 项应为字符串 (实际: ${describeActual(value[badIndex])})`
|
|
101
|
+
};
|
|
77
102
|
}
|
|
78
103
|
return null;
|
|
79
104
|
}
|
|
80
105
|
function shapeError(value) {
|
|
81
106
|
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
82
|
-
return
|
|
107
|
+
return {
|
|
108
|
+
field: "顶层",
|
|
109
|
+
message: `顶层应为对象 (实际: ${describeActual(value)})`
|
|
110
|
+
};
|
|
83
111
|
}
|
|
84
112
|
const candidate = value;
|
|
85
113
|
const rootsError = fieldError(candidate, "roots", false);
|
|
@@ -97,17 +125,17 @@ async function loadConfig(path) {
|
|
|
97
125
|
} catch (error) {
|
|
98
126
|
if (error.code === "ENOENT")
|
|
99
127
|
return { state: "absent" };
|
|
100
|
-
throw new
|
|
128
|
+
throw new SweepError("CONFIG_READ_FAILED", `配置读取失败 (${path}): ${error.message}`, { path, errno: error.code });
|
|
101
129
|
}
|
|
102
130
|
let data;
|
|
103
131
|
try {
|
|
104
132
|
data = JSON.parse(text);
|
|
105
133
|
} catch (error) {
|
|
106
|
-
throw new
|
|
134
|
+
throw new SweepError("CONFIG_CORRUPT_JSON", `配置损坏 (${path}): JSON 解析失败: ${error.message}`, { path });
|
|
107
135
|
}
|
|
108
|
-
const
|
|
109
|
-
if (
|
|
110
|
-
throw new
|
|
136
|
+
const problem = shapeError(data);
|
|
137
|
+
if (problem !== null) {
|
|
138
|
+
throw new SweepError("CONFIG_CORRUPT_SHAPE", `配置损坏 (${path}): ${problem.message}`, { path, field: problem.field });
|
|
111
139
|
}
|
|
112
140
|
const raw = data;
|
|
113
141
|
return {
|
|
@@ -122,14 +150,31 @@ async function loadConfig(path) {
|
|
|
122
150
|
async function loadResolvedConfig(resolved) {
|
|
123
151
|
const result = await loadConfig(resolved.path);
|
|
124
152
|
if (result.state === "absent" && resolved.source !== "platform-default") {
|
|
125
|
-
throw new
|
|
153
|
+
throw new SweepError("CONFIG_ABSENT", `配置不存在 (${resolved.path}), 请检查路径`, { path: resolved.path, source: resolved.source });
|
|
126
154
|
}
|
|
127
155
|
return result;
|
|
128
156
|
}
|
|
129
157
|
function mergeNames(configNames, cliNames) {
|
|
130
158
|
return [...new Set([...configNames, ...cliNames])].filter((name) => name !== "node_modules" && name !== ".git");
|
|
131
159
|
}
|
|
132
|
-
|
|
160
|
+
// ../sweep-node-modules/src/display.ts
|
|
161
|
+
function formatBytes(bytes) {
|
|
162
|
+
if (bytes < 1024)
|
|
163
|
+
return `${Math.round(bytes)} B`;
|
|
164
|
+
const units = ["KB", "MB", "GB", "TB"];
|
|
165
|
+
let value = bytes;
|
|
166
|
+
let index = -1;
|
|
167
|
+
do {
|
|
168
|
+
value /= 1024;
|
|
169
|
+
index += 1;
|
|
170
|
+
} while (value >= 1024 && index < units.length - 1);
|
|
171
|
+
return `${Math.round(value * 10) / 10} ${units[index]}`;
|
|
172
|
+
}
|
|
173
|
+
var sanitizeLine = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "").replace(/\s+/g, " ").trim();
|
|
174
|
+
var sanitizeOutputLine = (text) => {
|
|
175
|
+
const indent = /^[ \t]*/.exec(text)?.[0] ?? "";
|
|
176
|
+
return `${indent}${sanitizeLine(text)}`;
|
|
177
|
+
};
|
|
133
178
|
// ../sweep-node-modules/src/guard.ts
|
|
134
179
|
import { lstat, realpath, stat } from "node:fs/promises";
|
|
135
180
|
import { homedir as homedir2 } from "node:os";
|
|
@@ -232,50 +277,100 @@ async function validateTargets(targets, options) {
|
|
|
232
277
|
const home = homeOption === null ? null : await tryRealpath(homeOption) ?? homeOption;
|
|
233
278
|
const accepted = [];
|
|
234
279
|
const rejected = [];
|
|
280
|
+
const mappings = [];
|
|
235
281
|
const seen = new Set;
|
|
236
282
|
for (const target of targets) {
|
|
283
|
+
if (options.signal?.aborted) {
|
|
284
|
+
throw new SweepError("CANCELLED", "安全闸校验在逐目标检查点被取消", {
|
|
285
|
+
phase: "validate"
|
|
286
|
+
});
|
|
287
|
+
}
|
|
237
288
|
if (!hasNodeModulesLeaf(target, style)) {
|
|
238
|
-
rejected.push({
|
|
289
|
+
rejected.push({
|
|
290
|
+
target,
|
|
291
|
+
code: "GUARD_LEAF_NOT_NODE_MODULES",
|
|
292
|
+
message: "路径末段不是 node_modules"
|
|
293
|
+
});
|
|
239
294
|
continue;
|
|
240
295
|
}
|
|
241
|
-
|
|
296
|
+
let real = null;
|
|
297
|
+
let realpathErrno;
|
|
298
|
+
try {
|
|
299
|
+
real = await realpath(target);
|
|
300
|
+
} catch (error) {
|
|
301
|
+
realpathErrno = error.code;
|
|
302
|
+
}
|
|
242
303
|
if (real === null) {
|
|
243
|
-
|
|
304
|
+
let code = "GUARD_REALPATH_FAILED";
|
|
305
|
+
if (realpathErrno === "ENOENT")
|
|
306
|
+
code = "GUARD_TARGET_MISSING";
|
|
307
|
+
else if (realpathErrno === "EACCES" || realpathErrno === "EPERM") {
|
|
308
|
+
code = "GUARD_TARGET_UNREADABLE";
|
|
309
|
+
}
|
|
310
|
+
rejected.push({
|
|
311
|
+
target,
|
|
312
|
+
code,
|
|
313
|
+
message: "realpath 失败 (目标不存在或不可读)",
|
|
314
|
+
details: { errno: realpathErrno }
|
|
315
|
+
});
|
|
244
316
|
continue;
|
|
245
317
|
}
|
|
246
318
|
const brokenAnchor = brokenAnchors.find((anchor) => insideAnyRoot(real, [anchor.real], style));
|
|
247
319
|
if (brokenAnchor !== undefined) {
|
|
248
320
|
rejected.push({
|
|
249
321
|
target,
|
|
250
|
-
|
|
322
|
+
code: "GUARD_ROOT_ANCHOR_SYMLINK",
|
|
323
|
+
message: `根锚点被换位为符号链接 (根: ${brokenAnchor.configured}; 符号链接: ${brokenAnchor.link}), 请把配置根改为不含符号链接的真实路径`,
|
|
324
|
+
details: { root: brokenAnchor.configured, symlink: brokenAnchor.link }
|
|
251
325
|
});
|
|
252
326
|
continue;
|
|
253
327
|
}
|
|
254
328
|
if (isFilesystemRootBody(real, style)) {
|
|
255
|
-
rejected.push({
|
|
329
|
+
rejected.push({
|
|
330
|
+
target,
|
|
331
|
+
code: "GUARD_FILESYSTEM_ROOT_BODY",
|
|
332
|
+
message: "目标是文件系统根本体"
|
|
333
|
+
});
|
|
256
334
|
continue;
|
|
257
335
|
}
|
|
258
336
|
if (isHomeBody(real, home, style)) {
|
|
259
|
-
rejected.push({
|
|
337
|
+
rejected.push({
|
|
338
|
+
target,
|
|
339
|
+
code: "GUARD_HOME_BODY",
|
|
340
|
+
message: "目标是 home 本体"
|
|
341
|
+
});
|
|
260
342
|
continue;
|
|
261
343
|
}
|
|
262
344
|
if (!hasNodeModulesLeaf(real, style)) {
|
|
263
|
-
rejected.push({
|
|
345
|
+
rejected.push({
|
|
346
|
+
target,
|
|
347
|
+
code: "GUARD_REAL_LEAF_NOT_NODE_MODULES",
|
|
348
|
+
message: "realpath 后的末段不是 node_modules"
|
|
349
|
+
});
|
|
264
350
|
continue;
|
|
265
351
|
}
|
|
266
352
|
if (!insideAnyRoot(real, roots, style)) {
|
|
267
|
-
rejected.push({
|
|
353
|
+
rejected.push({
|
|
354
|
+
target,
|
|
355
|
+
code: "GUARD_OUTSIDE_ROOTS",
|
|
356
|
+
message: "realpath 后不在任何 root 之下"
|
|
357
|
+
});
|
|
268
358
|
continue;
|
|
269
359
|
}
|
|
270
360
|
const key = dedupeKey(real, style);
|
|
271
361
|
if (seen.has(key)) {
|
|
272
|
-
rejected.push({
|
|
362
|
+
rejected.push({
|
|
363
|
+
target,
|
|
364
|
+
code: "GUARD_DUPLICATE_TARGET",
|
|
365
|
+
message: "重复目标 (realpath 去重)"
|
|
366
|
+
});
|
|
273
367
|
continue;
|
|
274
368
|
}
|
|
275
369
|
seen.add(key);
|
|
276
370
|
accepted.push(real);
|
|
371
|
+
mappings.push({ original: target, real });
|
|
277
372
|
}
|
|
278
|
-
return { accepted, rejected };
|
|
373
|
+
return { accepted, rejected, mappings };
|
|
279
374
|
}
|
|
280
375
|
var fsDeviceProbe = async (path, follow) => {
|
|
281
376
|
try {
|
|
@@ -316,10 +411,13 @@ async function findCrossDeviceTargets(targets, options) {
|
|
|
316
411
|
const parentDev = await probe(style.ops.dirname(target), true);
|
|
317
412
|
found.set(target, parentDev !== null && parentDev !== targetDev ? "target-itself" : "on-path");
|
|
318
413
|
}
|
|
319
|
-
return found;
|
|
414
|
+
return [...found.entries()].map(([target, kind]) => ({ target, kind }));
|
|
415
|
+
}
|
|
416
|
+
function crossDeviceIndex(entries) {
|
|
417
|
+
return new Map(entries.map((entry) => [entry.target, entry.kind]));
|
|
320
418
|
}
|
|
321
|
-
|
|
322
419
|
// ../sweep-node-modules/src/classify.ts
|
|
420
|
+
import { homedir as homedir3 } from "node:os";
|
|
323
421
|
var fold2 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
|
|
324
422
|
var INSTALL_TREE_SEGMENTS = new Set([...DEFAULT_EXCLUDE, "extensions", "_npx"].map((name) => name.toLowerCase()));
|
|
325
423
|
function classifyTarget(target, options = {}) {
|
|
@@ -351,8 +449,116 @@ function classifyTarget(target, options = {}) {
|
|
|
351
449
|
}
|
|
352
450
|
return { kind: "project" };
|
|
353
451
|
}
|
|
452
|
+
|
|
453
|
+
// ../sweep-node-modules/src/skip.ts
|
|
454
|
+
var SUSPECT_HINT = "已跳过 (加 --force 一并清理)";
|
|
455
|
+
var CROSS_DEVICE_NOTES = {
|
|
456
|
+
"on-path": "跨设备: 根与目标之间有挂载点",
|
|
457
|
+
"target-itself": "跨设备: 目标本体即挂载点"
|
|
458
|
+
};
|
|
459
|
+
var CROSS_DEVICE_HINTS = {
|
|
460
|
+
"on-path": "已跳过 (把该挂载点声明为独立根即可清理)",
|
|
461
|
+
"target-itself": "已跳过 (挂载点无法删除, 需先卸载该卷)"
|
|
462
|
+
};
|
|
463
|
+
var CROSS_DEVICE_TRAILER_ACTIONS = {
|
|
464
|
+
"on-path": "把根与目标之间的挂载点声明为独立根即可清理",
|
|
465
|
+
"target-itself": "目标本体即挂载点, 需先卸载该卷"
|
|
466
|
+
};
|
|
467
|
+
function crossDeviceNote(kind) {
|
|
468
|
+
return CROSS_DEVICE_NOTES[kind];
|
|
469
|
+
}
|
|
470
|
+
function skipReasonOf(entry, crossDevice, policy) {
|
|
471
|
+
const deviceKind = crossDevice.get(entry.target);
|
|
472
|
+
if (deviceKind !== undefined) {
|
|
473
|
+
return deviceKind === "on-path" ? "cross-device:on-path" : "cross-device:target-itself";
|
|
474
|
+
}
|
|
475
|
+
if (entry.bytes === undefined)
|
|
476
|
+
return "unmeasured";
|
|
477
|
+
if (entry.suspect && !policy.releaseSuspects)
|
|
478
|
+
return "suspect-install-tree";
|
|
479
|
+
return null;
|
|
480
|
+
}
|
|
481
|
+
function skipsBatch(entry, crossDevice, policy) {
|
|
482
|
+
return skipReasonOf(entry, crossDevice, policy) !== null;
|
|
483
|
+
}
|
|
484
|
+
function deletionBatch(entries, crossDevice, policy) {
|
|
485
|
+
return entries.filter((entry) => !skipsBatch(entry, crossDevice, policy)).map((entry) => entry.target);
|
|
486
|
+
}
|
|
487
|
+
function noteOf(entry, reason) {
|
|
488
|
+
if (reason === "suspect-install-tree")
|
|
489
|
+
return SUSPECT_HINT;
|
|
490
|
+
if (reason === "unmeasured") {
|
|
491
|
+
return `体积统计失败: ${entry.unmeasuredReason ?? "原因未知"}`;
|
|
492
|
+
}
|
|
493
|
+
return CROSS_DEVICE_HINTS[reason === "cross-device:on-path" ? "on-path" : "target-itself"];
|
|
494
|
+
}
|
|
495
|
+
function collectSkips(entries, crossDevice, policy) {
|
|
496
|
+
const suspectSkipped = policy.releaseSuspects ? [] : entries.filter((entry) => entry.suspect);
|
|
497
|
+
const deviceSkipped = entries.filter((entry) => crossDevice.has(entry.target));
|
|
498
|
+
const trailer = [
|
|
499
|
+
...suspectSkipped.length > 0 ? [`疑似安装树 ${suspectSkipped.length} 处默认跳过 (加 --force 一并清理)`] : [],
|
|
500
|
+
...["on-path", "target-itself"].flatMap((kind) => {
|
|
501
|
+
const count = deviceSkipped.filter((entry) => crossDevice.get(entry.target) === kind).length;
|
|
502
|
+
return count === 0 ? [] : [
|
|
503
|
+
`跨设备目标 ${count} 处默认跳过 (${CROSS_DEVICE_TRAILER_ACTIONS[kind]})`
|
|
504
|
+
];
|
|
505
|
+
})
|
|
506
|
+
];
|
|
507
|
+
const hints = new Map;
|
|
508
|
+
for (const entry of suspectSkipped) {
|
|
509
|
+
if (entry.bytes !== undefined)
|
|
510
|
+
hints.set(entry.target, SUSPECT_HINT);
|
|
511
|
+
}
|
|
512
|
+
for (const entry of deviceSkipped) {
|
|
513
|
+
const kind = crossDevice.get(entry.target);
|
|
514
|
+
if (entry.bytes !== undefined && kind !== undefined) {
|
|
515
|
+
hints.set(entry.target, CROSS_DEVICE_HINTS[kind]);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
const book = [];
|
|
519
|
+
for (const entry of entries) {
|
|
520
|
+
const reason = skipReasonOf(entry, crossDevice, policy);
|
|
521
|
+
if (reason === null)
|
|
522
|
+
continue;
|
|
523
|
+
book.push({ target: entry.target, reason, note: noteOf(entry, reason) });
|
|
524
|
+
}
|
|
525
|
+
return { entries: book, trailer, hints };
|
|
526
|
+
}
|
|
527
|
+
// ../sweep-node-modules/src/summary.ts
|
|
528
|
+
var SUCCESS_KINDS = new Set([
|
|
529
|
+
"removed",
|
|
530
|
+
"missing",
|
|
531
|
+
"stale"
|
|
532
|
+
]);
|
|
533
|
+
function isSuccessOutcome(outcome) {
|
|
534
|
+
return SUCCESS_KINDS.has(outcome.kind);
|
|
535
|
+
}
|
|
536
|
+
function summarizeReport(report) {
|
|
537
|
+
const counts = {
|
|
538
|
+
removed: 0,
|
|
539
|
+
missing: 0,
|
|
540
|
+
stale: 0,
|
|
541
|
+
failed: 0,
|
|
542
|
+
rejected: 0,
|
|
543
|
+
"not-attempted": 0,
|
|
544
|
+
"not-expected": 0,
|
|
545
|
+
skipped: 0
|
|
546
|
+
};
|
|
547
|
+
for (const entry of report.entries)
|
|
548
|
+
counts[entry.outcome.kind] += 1;
|
|
549
|
+
return {
|
|
550
|
+
counts,
|
|
551
|
+
succeeded: counts.removed + counts.missing + counts.stale,
|
|
552
|
+
unprocessed: counts.skipped + counts.rejected + counts["not-attempted"] + counts["not-expected"],
|
|
553
|
+
failed: counts.failed,
|
|
554
|
+
aborted: report.removal?.aborted !== undefined
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
// ../sweep-node-modules/src/sweep.ts
|
|
558
|
+
import { homedir as homedir4 } from "node:os";
|
|
559
|
+
|
|
354
560
|
// ../sweep-node-modules/src/delete.ts
|
|
355
|
-
import { lstat as lstat2, rm } from "node:fs/promises";
|
|
561
|
+
import { lstat as lstat2, realpath as realpath2, rm } from "node:fs/promises";
|
|
356
562
|
import { isAbsolute, join, relative, sep } from "node:path";
|
|
357
563
|
var ERROR_HINTS = {
|
|
358
564
|
EACCES: "权限不足, 拒绝删除",
|
|
@@ -428,86 +634,209 @@ async function reviewComponents(chain) {
|
|
|
428
634
|
}
|
|
429
635
|
return null;
|
|
430
636
|
}
|
|
637
|
+
var REMOVAL_CONCURRENCY = 4;
|
|
431
638
|
async function removeTargets(targets, options) {
|
|
432
|
-
const result = { removed: [], missing: [], failed: [] };
|
|
433
639
|
const roots = options?.roots ?? [];
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
640
|
+
const signal = options?.signal;
|
|
641
|
+
const emit = options?.onProgress;
|
|
642
|
+
const slots = Array.from({
|
|
643
|
+
length: targets.length
|
|
644
|
+
});
|
|
645
|
+
let aborted;
|
|
646
|
+
let abortedIndex = Number.POSITIVE_INFINITY;
|
|
647
|
+
const recordAbort = (index, info) => {
|
|
648
|
+
if (index >= abortedIndex)
|
|
649
|
+
return;
|
|
650
|
+
aborted = info;
|
|
651
|
+
abortedIndex = index;
|
|
652
|
+
};
|
|
653
|
+
let cancelled = false;
|
|
654
|
+
const failures = [];
|
|
655
|
+
let next = 0;
|
|
656
|
+
let active = 0;
|
|
657
|
+
let resolveDrained = null;
|
|
658
|
+
const drained = new Promise((resolve) => {
|
|
659
|
+
resolveDrained = resolve;
|
|
660
|
+
});
|
|
661
|
+
const halted = () => cancelled || aborted !== undefined;
|
|
662
|
+
function pump() {
|
|
663
|
+
while (active < REMOVAL_CONCURRENCY && next < targets.length && !halted()) {
|
|
664
|
+
const index = next;
|
|
665
|
+
next += 1;
|
|
666
|
+
active += 1;
|
|
667
|
+
removeOne(index);
|
|
442
668
|
}
|
|
443
|
-
if (
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
};
|
|
448
|
-
break;
|
|
669
|
+
if (active === 0 && resolveDrained !== null) {
|
|
670
|
+
const resolve = resolveDrained;
|
|
671
|
+
resolveDrained = null;
|
|
672
|
+
resolve();
|
|
449
673
|
}
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
674
|
+
}
|
|
675
|
+
async function removeOne(index) {
|
|
676
|
+
try {
|
|
677
|
+
const target = targets[index];
|
|
678
|
+
if (target === undefined)
|
|
679
|
+
return;
|
|
680
|
+
if (signal?.aborted) {
|
|
681
|
+
cancelled = true;
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
const root = roots.find((candidate) => isUnder(candidate.real, target));
|
|
685
|
+
if (root === undefined) {
|
|
686
|
+
const info = {
|
|
454
687
|
target,
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
688
|
+
code: "REVIEW_NOT_UNDER_ANY_ROOT",
|
|
689
|
+
message: `安全复核失败 (目标不在任何 roots 之下): ${target}`,
|
|
690
|
+
path: target
|
|
691
|
+
};
|
|
692
|
+
recordAbort(index, info);
|
|
693
|
+
slots[index] = { kind: "aborted" };
|
|
694
|
+
emit?.({ kind: "aborted", aborted: info });
|
|
695
|
+
return;
|
|
458
696
|
}
|
|
459
|
-
if (
|
|
460
|
-
|
|
697
|
+
if (await isSymlinkHead(root.configured)) {
|
|
698
|
+
const info = {
|
|
461
699
|
target,
|
|
462
|
-
|
|
700
|
+
code: "REVIEW_HEAD_SYMLINK",
|
|
701
|
+
message: `安全复核失败 (根被替换为符号链接): ${root.configured}`,
|
|
702
|
+
path: root.configured
|
|
463
703
|
};
|
|
464
|
-
|
|
704
|
+
recordAbort(index, info);
|
|
705
|
+
slots[index] = { kind: "aborted" };
|
|
706
|
+
emit?.({ kind: "aborted", aborted: info });
|
|
707
|
+
return;
|
|
465
708
|
}
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
709
|
+
const finding = await reviewComponents(componentChain(root.real, target));
|
|
710
|
+
if (finding !== null) {
|
|
711
|
+
if (finding.kind === "vanished") {
|
|
712
|
+
const vanished = {
|
|
713
|
+
target,
|
|
714
|
+
code: "REVIEW_COMPONENT_VANISHED",
|
|
715
|
+
message: describeVanishedReview(target, finding.path),
|
|
716
|
+
partialRisk: false
|
|
717
|
+
};
|
|
718
|
+
slots[index] = { kind: "failed", failure: vanished };
|
|
719
|
+
emit?.({ kind: "failed", failure: vanished });
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
if (finding.kind === "unsafe") {
|
|
723
|
+
const info = {
|
|
724
|
+
target,
|
|
725
|
+
code: "REVIEW_COMPONENT_REPLACED",
|
|
726
|
+
message: `安全复核失败 (路径组件被替换): ${finding.path}`,
|
|
727
|
+
path: finding.path
|
|
728
|
+
};
|
|
729
|
+
recordAbort(index, info);
|
|
730
|
+
slots[index] = { kind: "aborted" };
|
|
731
|
+
emit?.({ kind: "aborted", aborted: info });
|
|
732
|
+
return;
|
|
481
733
|
}
|
|
482
|
-
|
|
734
|
+
const unverified = {
|
|
483
735
|
target,
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
736
|
+
code: "REVIEW_UNVERIFIED",
|
|
737
|
+
message: describeReviewError(target, finding.path, finding.error),
|
|
738
|
+
partialRisk: false
|
|
739
|
+
};
|
|
740
|
+
slots[index] = { kind: "failed", failure: unverified };
|
|
741
|
+
emit?.({ kind: "failed", failure: unverified });
|
|
742
|
+
return;
|
|
487
743
|
}
|
|
488
|
-
|
|
489
|
-
target,
|
|
490
|
-
|
|
491
|
-
|
|
744
|
+
try {
|
|
745
|
+
await rm(target, { recursive: true, force: false });
|
|
746
|
+
slots[index] = { kind: "removed", target };
|
|
747
|
+
emit?.({ kind: "removed", target });
|
|
748
|
+
} catch (error) {
|
|
749
|
+
if (error?.code === "ENOENT") {
|
|
750
|
+
const state = await checkGone(target);
|
|
751
|
+
if (state === "gone") {
|
|
752
|
+
slots[index] = { kind: "missing", target };
|
|
753
|
+
emit?.({ kind: "missing", target });
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
const survivor = {
|
|
757
|
+
target,
|
|
758
|
+
code: "REMOVE_ENOENT_SURVIVOR",
|
|
759
|
+
message: describeSurvivor(target, state),
|
|
760
|
+
partialRisk: true
|
|
761
|
+
};
|
|
762
|
+
slots[index] = { kind: "failed", failure: survivor };
|
|
763
|
+
emit?.({ kind: "failed", failure: survivor });
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
const failure = {
|
|
767
|
+
target,
|
|
768
|
+
code: "REMOVE_FAILED",
|
|
769
|
+
errno: error?.code,
|
|
770
|
+
message: describeRemovalError(target, error),
|
|
771
|
+
partialRisk: true
|
|
772
|
+
};
|
|
773
|
+
slots[index] = { kind: "failed", failure };
|
|
774
|
+
emit?.({ kind: "failed", failure });
|
|
775
|
+
}
|
|
776
|
+
} catch (error) {
|
|
777
|
+
if (failures.length === 0)
|
|
778
|
+
failures.push(error);
|
|
779
|
+
} finally {
|
|
780
|
+
if (signal?.aborted)
|
|
781
|
+
cancelled = true;
|
|
782
|
+
active -= 1;
|
|
783
|
+
pump();
|
|
492
784
|
}
|
|
493
785
|
}
|
|
786
|
+
pump();
|
|
787
|
+
await drained;
|
|
788
|
+
if (failures.length > 0)
|
|
789
|
+
throw failures[0];
|
|
790
|
+
const result = { removed: [], missing: [], failed: [] };
|
|
791
|
+
for (const slot of slots) {
|
|
792
|
+
if (slot === undefined)
|
|
793
|
+
continue;
|
|
794
|
+
switch (slot.kind) {
|
|
795
|
+
case "removed":
|
|
796
|
+
result.removed.push(slot.target);
|
|
797
|
+
break;
|
|
798
|
+
case "missing":
|
|
799
|
+
result.missing.push(slot.target);
|
|
800
|
+
break;
|
|
801
|
+
case "failed":
|
|
802
|
+
result.failed.push(slot.failure);
|
|
803
|
+
break;
|
|
804
|
+
case "aborted":
|
|
805
|
+
break;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
if (aborted !== undefined)
|
|
809
|
+
result.aborted = aborted;
|
|
810
|
+
if (cancelled) {
|
|
811
|
+
throw new SweepError("CANCELLED", "删除在条目间检查点被取消", {
|
|
812
|
+
phase: "remove",
|
|
813
|
+
partial: result
|
|
814
|
+
});
|
|
815
|
+
}
|
|
494
816
|
return result;
|
|
495
817
|
}
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
if (
|
|
504
|
-
|
|
505
|
-
|
|
818
|
+
async function toTrustRoots(roots) {
|
|
819
|
+
return Promise.all(roots.map(async (root) => ({
|
|
820
|
+
configured: root,
|
|
821
|
+
real: await realpath2(root).catch(() => null) ?? root
|
|
822
|
+
})));
|
|
823
|
+
}
|
|
824
|
+
function splitStaleRejections(rejected, staleTargets) {
|
|
825
|
+
if (staleTargets !== "missing")
|
|
826
|
+
return { rejected, stale: [] };
|
|
827
|
+
const rest = [];
|
|
828
|
+
const stale = [];
|
|
829
|
+
for (const item of rejected) {
|
|
830
|
+
if (item.code === "GUARD_TARGET_MISSING")
|
|
831
|
+
stale.push(item.target);
|
|
832
|
+
else
|
|
833
|
+
rest.push(item);
|
|
506
834
|
}
|
|
507
|
-
|
|
835
|
+
return { rejected: rest, stale };
|
|
508
836
|
}
|
|
837
|
+
|
|
509
838
|
// ../sweep-node-modules/src/scan-parallel.ts
|
|
510
|
-
import { readdir, realpath as
|
|
839
|
+
import { readdir, realpath as realpath3, stat as stat2 } from "node:fs/promises";
|
|
511
840
|
import { join as join2 } from "node:path";
|
|
512
841
|
var NODE_MODULES = "node_modules";
|
|
513
842
|
var GIT_DIR = ".git";
|
|
@@ -519,18 +848,36 @@ function compareTarget(a, b) {
|
|
|
519
848
|
return 1;
|
|
520
849
|
return 0;
|
|
521
850
|
}
|
|
522
|
-
function
|
|
851
|
+
function rootFailureWarning(error, root) {
|
|
523
852
|
const { code } = error;
|
|
524
853
|
switch (code) {
|
|
525
854
|
case "ENOENT":
|
|
526
|
-
return
|
|
855
|
+
return {
|
|
856
|
+
code: "SCAN_ROOT_MISSING",
|
|
857
|
+
message: `根不存在, 已跳过: ${root}`,
|
|
858
|
+
path: root
|
|
859
|
+
};
|
|
527
860
|
case "EACCES":
|
|
528
861
|
case "EPERM":
|
|
529
|
-
return
|
|
862
|
+
return {
|
|
863
|
+
code: "SCAN_ROOT_UNREADABLE",
|
|
864
|
+
message: `根不可读 (权限不足), 已跳过: ${root}`,
|
|
865
|
+
path: root,
|
|
866
|
+
errno: code
|
|
867
|
+
};
|
|
530
868
|
case "ENOTDIR":
|
|
531
|
-
return
|
|
869
|
+
return {
|
|
870
|
+
code: "SCAN_ROOT_NOT_DIR",
|
|
871
|
+
message: `根不是目录, 已跳过: ${root}`,
|
|
872
|
+
path: root
|
|
873
|
+
};
|
|
532
874
|
default:
|
|
533
|
-
return
|
|
875
|
+
return {
|
|
876
|
+
code: "SCAN_ROOT_UNAVAILABLE",
|
|
877
|
+
message: `根不可用 (${code ?? "UNKNOWN"}), 已跳过: ${root}`,
|
|
878
|
+
path: root,
|
|
879
|
+
errno: code
|
|
880
|
+
};
|
|
534
881
|
}
|
|
535
882
|
}
|
|
536
883
|
async function walkRoot(root, ctx) {
|
|
@@ -541,7 +888,9 @@ async function walkRoot(root, ctx) {
|
|
|
541
888
|
include,
|
|
542
889
|
includeCounts,
|
|
543
890
|
hits,
|
|
544
|
-
warnings
|
|
891
|
+
warnings,
|
|
892
|
+
signal,
|
|
893
|
+
onProgress
|
|
545
894
|
} = ctx;
|
|
546
895
|
const stack = [{ dir: root, included: include.size === 0 }];
|
|
547
896
|
let outstanding = 1;
|
|
@@ -565,11 +914,20 @@ async function walkRoot(root, ctx) {
|
|
|
565
914
|
}
|
|
566
915
|
async function visit(dir, included) {
|
|
567
916
|
try {
|
|
917
|
+
if (signal?.aborted) {
|
|
918
|
+
throw new SweepError("CANCELLED", "扫描在遍历任务检查点被取消", {
|
|
919
|
+
phase: "scan"
|
|
920
|
+
});
|
|
921
|
+
}
|
|
568
922
|
let entries;
|
|
569
923
|
try {
|
|
570
924
|
entries = await readdir(dir, { withFileTypes: true });
|
|
571
925
|
} catch {
|
|
572
|
-
warnings.push(
|
|
926
|
+
warnings.push({
|
|
927
|
+
code: "SCAN_DIR_UNREADABLE",
|
|
928
|
+
message: `目录不可读, 已跳过: ${dir}`,
|
|
929
|
+
path: dir
|
|
930
|
+
});
|
|
573
931
|
return;
|
|
574
932
|
}
|
|
575
933
|
for (const entry of entries) {
|
|
@@ -580,9 +938,12 @@ async function walkRoot(root, ctx) {
|
|
|
580
938
|
if (!included)
|
|
581
939
|
continue;
|
|
582
940
|
const target = join2(dir, name);
|
|
583
|
-
const key = dedupeKey(await
|
|
584
|
-
if (!hits.has(key))
|
|
585
|
-
|
|
941
|
+
const key = dedupeKey(await realpath3(target).catch(() => target), style);
|
|
942
|
+
if (!hits.has(key)) {
|
|
943
|
+
const hit = { project: dir, target, root };
|
|
944
|
+
hits.set(key, hit);
|
|
945
|
+
onProgress?.({ kind: "hit", hit });
|
|
946
|
+
}
|
|
586
947
|
continue;
|
|
587
948
|
}
|
|
588
949
|
if (name === GIT_DIR)
|
|
@@ -636,14 +997,18 @@ function createParallelScanner() {
|
|
|
636
997
|
for (const root of options.roots) {
|
|
637
998
|
let key;
|
|
638
999
|
try {
|
|
639
|
-
const resolved = await
|
|
1000
|
+
const resolved = await realpath3(root);
|
|
640
1001
|
if (!(await stat2(resolved)).isDirectory()) {
|
|
641
|
-
warnings.push(
|
|
1002
|
+
warnings.push({
|
|
1003
|
+
code: "SCAN_ROOT_NOT_DIR",
|
|
1004
|
+
message: `根不是目录, 已跳过: ${root}`,
|
|
1005
|
+
path: root
|
|
1006
|
+
});
|
|
642
1007
|
continue;
|
|
643
1008
|
}
|
|
644
1009
|
key = dedupeKey(resolved, style);
|
|
645
1010
|
} catch (error) {
|
|
646
|
-
warnings.push(
|
|
1011
|
+
warnings.push(rootFailureWarning(error, root));
|
|
647
1012
|
continue;
|
|
648
1013
|
}
|
|
649
1014
|
if (seenRoots.has(key))
|
|
@@ -658,7 +1023,9 @@ function createParallelScanner() {
|
|
|
658
1023
|
include,
|
|
659
1024
|
includeCounts,
|
|
660
1025
|
hits: hitsByRealTarget,
|
|
661
|
-
warnings
|
|
1026
|
+
warnings,
|
|
1027
|
+
signal: options.signal,
|
|
1028
|
+
onProgress: options.onProgress
|
|
662
1029
|
};
|
|
663
1030
|
for (const root of roots) {
|
|
664
1031
|
await walkRoot(root, context);
|
|
@@ -759,15 +1126,31 @@ function describeAnomaly(assessment) {
|
|
|
759
1126
|
}
|
|
760
1127
|
function describeDuFailure(detail) {
|
|
761
1128
|
if (/no such file or directory/i.test(detail))
|
|
762
|
-
return { reason: "不存在"
|
|
1129
|
+
return { missing: true, reason: "不存在" };
|
|
763
1130
|
if (/permission denied/i.test(detail))
|
|
764
|
-
return {
|
|
1131
|
+
return {
|
|
1132
|
+
missing: false,
|
|
1133
|
+
code: "SIZE_UNMEASURED_PERMISSION",
|
|
1134
|
+
reason: "权限不足, 无法读取"
|
|
1135
|
+
};
|
|
765
1136
|
if (/not a directory/i.test(detail))
|
|
766
|
-
return {
|
|
1137
|
+
return {
|
|
1138
|
+
missing: false,
|
|
1139
|
+
code: "SIZE_UNMEASURED_NOT_DIR",
|
|
1140
|
+
reason: "不是目录"
|
|
1141
|
+
};
|
|
767
1142
|
if (/too many levels of symbolic links/i.test(detail)) {
|
|
768
|
-
return {
|
|
1143
|
+
return {
|
|
1144
|
+
missing: false,
|
|
1145
|
+
code: "SIZE_UNMEASURED_LOOP",
|
|
1146
|
+
reason: "符号链接层级过深"
|
|
1147
|
+
};
|
|
769
1148
|
}
|
|
770
|
-
return {
|
|
1149
|
+
return {
|
|
1150
|
+
missing: false,
|
|
1151
|
+
code: "SIZE_UNMEASURED_OTHER",
|
|
1152
|
+
reason: `读取失败 (${detail})`
|
|
1153
|
+
};
|
|
771
1154
|
}
|
|
772
1155
|
function parseDuErrorLine(line) {
|
|
773
1156
|
const body = line.replace(PROG_PREFIX_RE, "");
|
|
@@ -790,23 +1173,37 @@ function parseDuErrorLine(line) {
|
|
|
790
1173
|
function createDuSizer(bin = findDu()) {
|
|
791
1174
|
return {
|
|
792
1175
|
name: "du",
|
|
793
|
-
|
|
1176
|
+
basis: "disk-usage",
|
|
1177
|
+
async measure(targets, options) {
|
|
794
1178
|
if (bin === null) {
|
|
795
1179
|
return {
|
|
796
1180
|
entries: [],
|
|
1181
|
+
basis: "disk-usage",
|
|
797
1182
|
warnings: [
|
|
798
|
-
|
|
1183
|
+
{
|
|
1184
|
+
code: "SIZE_DU_UNAVAILABLE",
|
|
1185
|
+
message: "du 候选不可用: /usr/bin/du 与 /bin/du 均不存在, 本候选跳过体积统计"
|
|
1186
|
+
}
|
|
799
1187
|
],
|
|
800
|
-
unmeasured: []
|
|
1188
|
+
unmeasured: [],
|
|
1189
|
+
gone: []
|
|
801
1190
|
};
|
|
802
1191
|
}
|
|
803
1192
|
if (targets.length === 0) {
|
|
804
|
-
return {
|
|
1193
|
+
return {
|
|
1194
|
+
entries: [],
|
|
1195
|
+
basis: "disk-usage",
|
|
1196
|
+
warnings: [],
|
|
1197
|
+
unmeasured: [],
|
|
1198
|
+
gone: []
|
|
1199
|
+
};
|
|
805
1200
|
}
|
|
806
1201
|
const sorted = [...targets].sort();
|
|
807
1202
|
const warnings = [];
|
|
808
1203
|
const entries = [];
|
|
809
1204
|
const unmeasured = [];
|
|
1205
|
+
const gone = [];
|
|
1206
|
+
const emit = options?.onProgress;
|
|
810
1207
|
const safeTargets = sorted.filter((target) => !hasControlChar(target));
|
|
811
1208
|
const safeSet = new Set(safeTargets);
|
|
812
1209
|
const sizes = new Map;
|
|
@@ -817,7 +1214,10 @@ function createDuSizer(bin = findDu()) {
|
|
|
817
1214
|
const assessment = assessDuOutput(stdout, safeTargets);
|
|
818
1215
|
intact = assessment.intact;
|
|
819
1216
|
if (!intact) {
|
|
820
|
-
warnings.push(
|
|
1217
|
+
warnings.push({
|
|
1218
|
+
code: "SIZE_DU_OUTPUT_MISMATCH",
|
|
1219
|
+
message: `du 输出与输入集合不符 (${describeAnomaly(assessment)}): 本批 ${safeTargets.length} 个目标的体积均未采信`
|
|
1220
|
+
});
|
|
821
1221
|
}
|
|
822
1222
|
for (const [path, bytes] of assessment.sizes)
|
|
823
1223
|
sizes.set(path, bytes);
|
|
@@ -827,12 +1227,19 @@ function createDuSizer(bin = findDu()) {
|
|
|
827
1227
|
continue;
|
|
828
1228
|
const errorLine = parseDuErrorLine(line);
|
|
829
1229
|
if (errorLine === null) {
|
|
830
|
-
warnings.push(
|
|
1230
|
+
warnings.push({
|
|
1231
|
+
code: "SIZE_DU_LINE_UNATTRIBUTED",
|
|
1232
|
+
message: `体积统计失败 (未归因): ${line.replace(PROG_PREFIX_RE, "").trim()}`
|
|
1233
|
+
});
|
|
831
1234
|
continue;
|
|
832
1235
|
}
|
|
833
1236
|
const failure = describeDuFailure(errorLine.detail);
|
|
834
1237
|
if (!safeSet.has(errorLine.path)) {
|
|
835
|
-
warnings.push(
|
|
1238
|
+
warnings.push({
|
|
1239
|
+
code: "SIZE_SUBPATH_FAILED",
|
|
1240
|
+
message: `体积统计失败 (${failure.reason}): ${errorLine.path}`,
|
|
1241
|
+
path: errorLine.path
|
|
1242
|
+
});
|
|
836
1243
|
continue;
|
|
837
1244
|
}
|
|
838
1245
|
failures.set(errorLine.path, failure);
|
|
@@ -840,32 +1247,48 @@ function createDuSizer(bin = findDu()) {
|
|
|
840
1247
|
for (const path of failures.keys())
|
|
841
1248
|
sizes.delete(path);
|
|
842
1249
|
}
|
|
1250
|
+
const pushUnmeasured = (target, code, reason) => {
|
|
1251
|
+
unmeasured.push({ target, code, reason });
|
|
1252
|
+
emit?.({ kind: "unmeasured", target, code, reason });
|
|
1253
|
+
};
|
|
843
1254
|
for (const target of sorted) {
|
|
1255
|
+
if (options?.signal?.aborted) {
|
|
1256
|
+
throw new SweepError("CANCELLED", "体积统计在逐目标检查点被取消", {
|
|
1257
|
+
phase: "measure"
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
844
1260
|
if (hasControlChar(target)) {
|
|
845
|
-
|
|
1261
|
+
pushUnmeasured(target, "SIZE_UNMEASURED_CONTROL_CHAR", "路径含控制字符");
|
|
846
1262
|
continue;
|
|
847
1263
|
}
|
|
848
1264
|
if (!intact) {
|
|
849
|
-
|
|
1265
|
+
pushUnmeasured(target, "SIZE_UNMEASURED_UNPARSEABLE", "输出不可解析");
|
|
850
1266
|
continue;
|
|
851
1267
|
}
|
|
852
1268
|
const bytes = sizes.get(target);
|
|
853
1269
|
if (bytes !== undefined) {
|
|
854
1270
|
entries.push({ target, bytes });
|
|
1271
|
+
emit?.({ kind: "measured", target, bytes, basis: "disk-usage" });
|
|
855
1272
|
continue;
|
|
856
1273
|
}
|
|
857
1274
|
const failure = failures.get(target);
|
|
858
1275
|
if (failure === undefined) {
|
|
859
|
-
|
|
1276
|
+
pushUnmeasured(target, "SIZE_UNMEASURED_UNPARSEABLE", "输出不可解析");
|
|
860
1277
|
continue;
|
|
861
1278
|
}
|
|
862
1279
|
if (failure.missing) {
|
|
863
|
-
|
|
1280
|
+
gone.push(target);
|
|
1281
|
+
warnings.push({
|
|
1282
|
+
code: "SIZE_TARGET_VANISHED",
|
|
1283
|
+
message: `体积统计失败 (不存在): ${target}`,
|
|
1284
|
+
path: target
|
|
1285
|
+
});
|
|
1286
|
+
emit?.({ kind: "gone", target });
|
|
864
1287
|
continue;
|
|
865
1288
|
}
|
|
866
|
-
|
|
1289
|
+
pushUnmeasured(target, failure.code, failure.reason);
|
|
867
1290
|
}
|
|
868
|
-
return { entries, warnings, unmeasured };
|
|
1291
|
+
return { entries, basis: "disk-usage", warnings, unmeasured, gone };
|
|
869
1292
|
}
|
|
870
1293
|
};
|
|
871
1294
|
}
|
|
@@ -876,16 +1299,32 @@ import { join as join3 } from "node:path";
|
|
|
876
1299
|
function describeFailure(code) {
|
|
877
1300
|
switch (code) {
|
|
878
1301
|
case "ENOENT":
|
|
879
|
-
return "不存在";
|
|
1302
|
+
return { missing: true, reason: "不存在" };
|
|
880
1303
|
case "EACCES":
|
|
881
1304
|
case "EPERM":
|
|
882
|
-
return
|
|
1305
|
+
return {
|
|
1306
|
+
missing: false,
|
|
1307
|
+
code: "SIZE_UNMEASURED_PERMISSION",
|
|
1308
|
+
reason: "权限不足, 无法读取"
|
|
1309
|
+
};
|
|
883
1310
|
case "ENOTDIR":
|
|
884
|
-
return
|
|
1311
|
+
return {
|
|
1312
|
+
missing: false,
|
|
1313
|
+
code: "SIZE_UNMEASURED_NOT_DIR",
|
|
1314
|
+
reason: "不是目录"
|
|
1315
|
+
};
|
|
885
1316
|
case "ELOOP":
|
|
886
|
-
return
|
|
1317
|
+
return {
|
|
1318
|
+
missing: false,
|
|
1319
|
+
code: "SIZE_UNMEASURED_LOOP",
|
|
1320
|
+
reason: "符号链接层级过深"
|
|
1321
|
+
};
|
|
887
1322
|
default:
|
|
888
|
-
return
|
|
1323
|
+
return {
|
|
1324
|
+
missing: false,
|
|
1325
|
+
code: "SIZE_UNMEASURED_OTHER",
|
|
1326
|
+
reason: code === undefined ? "读取失败" : `读取失败 (${code})`
|
|
1327
|
+
};
|
|
889
1328
|
}
|
|
890
1329
|
}
|
|
891
1330
|
function errorCode(error) {
|
|
@@ -901,13 +1340,21 @@ async function sumEntries(dirents, dir, warnings) {
|
|
|
901
1340
|
try {
|
|
902
1341
|
total += await sumEntries(await readdir2(path, { withFileTypes: true }), path, warnings);
|
|
903
1342
|
} catch (error) {
|
|
904
|
-
warnings.push(
|
|
1343
|
+
warnings.push({
|
|
1344
|
+
code: "SIZE_SUBPATH_FAILED",
|
|
1345
|
+
message: `体积统计失败 (${describeFailure(errorCode(error)).reason}): ${path}`,
|
|
1346
|
+
path
|
|
1347
|
+
});
|
|
905
1348
|
}
|
|
906
1349
|
} else if (dirent.isFile()) {
|
|
907
1350
|
try {
|
|
908
1351
|
total += (await stat3(path)).size;
|
|
909
1352
|
} catch (error) {
|
|
910
|
-
warnings.push(
|
|
1353
|
+
warnings.push({
|
|
1354
|
+
code: "SIZE_SUBPATH_FAILED",
|
|
1355
|
+
message: `体积统计失败 (${describeFailure(errorCode(error)).reason}): ${path}`,
|
|
1356
|
+
path
|
|
1357
|
+
});
|
|
911
1358
|
}
|
|
912
1359
|
}
|
|
913
1360
|
}
|
|
@@ -916,29 +1363,46 @@ async function sumEntries(dirents, dir, warnings) {
|
|
|
916
1363
|
function createJsSizer() {
|
|
917
1364
|
return {
|
|
918
1365
|
name: "js",
|
|
919
|
-
|
|
1366
|
+
basis: "logical-bytes",
|
|
1367
|
+
async measure(targets, options) {
|
|
920
1368
|
const warnings = [];
|
|
921
1369
|
const entries = [];
|
|
922
1370
|
const unmeasured = [];
|
|
1371
|
+
const gone = [];
|
|
1372
|
+
const emit = options?.onProgress;
|
|
1373
|
+
const pushUnmeasured = (target, code, reason) => {
|
|
1374
|
+
unmeasured.push({ target, code, reason });
|
|
1375
|
+
emit?.({ kind: "unmeasured", target, code, reason });
|
|
1376
|
+
};
|
|
923
1377
|
for (const target of [...targets].sort()) {
|
|
1378
|
+
if (options?.signal?.aborted) {
|
|
1379
|
+
throw new SweepError("CANCELLED", "体积统计在逐目标检查点被取消", {
|
|
1380
|
+
phase: "measure"
|
|
1381
|
+
});
|
|
1382
|
+
}
|
|
924
1383
|
let dirents;
|
|
925
1384
|
try {
|
|
926
1385
|
dirents = await readdir2(target, { withFileTypes: true });
|
|
927
1386
|
} catch (error) {
|
|
928
|
-
const
|
|
929
|
-
if (
|
|
930
|
-
|
|
1387
|
+
const failure = describeFailure(errorCode(error));
|
|
1388
|
+
if (failure.missing) {
|
|
1389
|
+
gone.push(target);
|
|
1390
|
+
warnings.push({
|
|
1391
|
+
code: "SIZE_TARGET_VANISHED",
|
|
1392
|
+
message: `体积统计失败 (${failure.reason}): ${target}`,
|
|
1393
|
+
path: target
|
|
1394
|
+
});
|
|
1395
|
+
emit?.({ kind: "gone", target });
|
|
931
1396
|
} else {
|
|
932
|
-
|
|
1397
|
+
pushUnmeasured(target, failure.code, failure.reason);
|
|
933
1398
|
}
|
|
934
1399
|
continue;
|
|
935
1400
|
}
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
});
|
|
1401
|
+
const bytes = await sumEntries(dirents, target, warnings);
|
|
1402
|
+
entries.push({ target, bytes });
|
|
1403
|
+
emit?.({ kind: "measured", target, bytes, basis: "logical-bytes" });
|
|
940
1404
|
}
|
|
941
|
-
return { entries, warnings, unmeasured };
|
|
1405
|
+
return { entries, basis: "logical-bytes", warnings, unmeasured, gone };
|
|
942
1406
|
}
|
|
943
1407
|
};
|
|
944
1408
|
}
|
|
@@ -947,55 +1411,286 @@ function createJsSizer() {
|
|
|
947
1411
|
function createSizer() {
|
|
948
1412
|
return findDu() !== null ? createDuSizer() : createJsSizer();
|
|
949
1413
|
}
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
var
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
}
|
|
964
|
-
function
|
|
965
|
-
|
|
1414
|
+
|
|
1415
|
+
// ../sweep-node-modules/src/sweep.ts
|
|
1416
|
+
var invalidArgument = (field, message) => new SweepError("INVALID_ARGUMENT", `${message} (字段: ${field})`, { field });
|
|
1417
|
+
function assertNameArray(value, field, required) {
|
|
1418
|
+
if (value === undefined) {
|
|
1419
|
+
if (required)
|
|
1420
|
+
throw invalidArgument(field, "为必填项");
|
|
1421
|
+
return;
|
|
1422
|
+
}
|
|
1423
|
+
if (!Array.isArray(value) || value.some((item) => typeof item !== "string" || item === ""))
|
|
1424
|
+
throw invalidArgument(field, "必须是非空字符串数组");
|
|
1425
|
+
if (required && value.length === 0)
|
|
1426
|
+
throw invalidArgument(field, "不能为空数组");
|
|
1427
|
+
}
|
|
1428
|
+
function assertShape(options) {
|
|
1429
|
+
if (typeof options !== "object" || options === null)
|
|
1430
|
+
throw invalidArgument("options", "构造选项必须是对象");
|
|
1431
|
+
assertNameArray(options.roots, "roots", true);
|
|
1432
|
+
assertNameArray(options.exclude, "exclude", false);
|
|
1433
|
+
assertNameArray(options.include, "include", false);
|
|
1434
|
+
if (options.home !== undefined && options.home !== null && typeof options.home !== "string")
|
|
1435
|
+
throw invalidArgument("home", "必须是字符串或 null");
|
|
1436
|
+
if (options.policy !== undefined && (typeof options.policy !== "object" || options.policy === null || typeof options.policy.releaseSuspects !== "boolean"))
|
|
1437
|
+
throw invalidArgument("policy", "releaseSuspects 必须是布尔值");
|
|
1438
|
+
}
|
|
1439
|
+
function resolveOptions(options) {
|
|
1440
|
+
assertShape(options);
|
|
1441
|
+
return Object.freeze({
|
|
1442
|
+
roots: [...options.roots],
|
|
1443
|
+
exclude: mergeNames(options.exclude ?? [...DEFAULT_EXCLUDE], []),
|
|
1444
|
+
include: mergeNames(options.include ?? [], []),
|
|
1445
|
+
home: options.home === undefined ? homedir4() : options.home,
|
|
1446
|
+
style: options.style ?? nativeStyle(),
|
|
1447
|
+
policy: Object.freeze({
|
|
1448
|
+
releaseSuspects: options.policy?.releaseSuspects ?? false
|
|
1449
|
+
})
|
|
1450
|
+
});
|
|
966
1451
|
}
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
1452
|
+
var cancelledAt = (phase) => new SweepError("CANCELLED", `清理在 ${phase} 阶段被取消`, { phase });
|
|
1453
|
+
async function withPhase(phase, emit, signal, work) {
|
|
1454
|
+
if (signal?.aborted)
|
|
1455
|
+
throw cancelledAt(phase);
|
|
1456
|
+
const startedAt = Date.now();
|
|
1457
|
+
emit?.({ kind: "phase", phase, status: "start" });
|
|
1458
|
+
const value = await work();
|
|
1459
|
+
emit?.({
|
|
1460
|
+
kind: "phase",
|
|
1461
|
+
phase,
|
|
1462
|
+
status: "done",
|
|
1463
|
+
elapsedMs: Date.now() - startedAt
|
|
1464
|
+
});
|
|
1465
|
+
return value;
|
|
971
1466
|
}
|
|
972
|
-
function
|
|
973
|
-
|
|
1467
|
+
async function executePlan(resolved, options, signal) {
|
|
1468
|
+
const emit = options?.onProgress;
|
|
1469
|
+
const roots = resolved.roots;
|
|
1470
|
+
const scanResult = await withPhase("scan", emit, signal, async () => {
|
|
1471
|
+
const result = await createParallelScanner().scan({
|
|
1472
|
+
roots,
|
|
1473
|
+
exclude: resolved.exclude,
|
|
1474
|
+
include: resolved.include,
|
|
1475
|
+
signal,
|
|
1476
|
+
onProgress: (event) => emit?.(event)
|
|
1477
|
+
});
|
|
1478
|
+
for (const warning of result.warnings)
|
|
1479
|
+
emit?.({ kind: "warning", warning });
|
|
1480
|
+
return result;
|
|
1481
|
+
});
|
|
1482
|
+
const targets = scanResult.hits.map((hit) => hit.target);
|
|
1483
|
+
const sizeResult = await withPhase("measure", emit, signal, async () => {
|
|
1484
|
+
const result = await createSizer().measure(targets, {
|
|
1485
|
+
signal,
|
|
1486
|
+
onProgress: (event) => {
|
|
1487
|
+
if (event.kind === "gone")
|
|
1488
|
+
return;
|
|
1489
|
+
emit?.(event);
|
|
1490
|
+
}
|
|
1491
|
+
});
|
|
1492
|
+
for (const warning of result.warnings)
|
|
1493
|
+
emit?.({ kind: "warning", warning });
|
|
1494
|
+
return result;
|
|
1495
|
+
});
|
|
1496
|
+
const classifications = await withPhase("classify", emit, signal, () => scanResult.hits.map((hit) => classifyTarget(hit.target, {
|
|
1497
|
+
home: resolved.home,
|
|
1498
|
+
style: resolved.style
|
|
1499
|
+
})));
|
|
1500
|
+
const crossDevice = await withPhase("device", emit, signal, async () => crossDeviceIndex(await findCrossDeviceTargets(targets, {
|
|
1501
|
+
roots,
|
|
1502
|
+
style: resolved.style
|
|
1503
|
+
})));
|
|
1504
|
+
return withPhase("plan", emit, signal, () => {
|
|
1505
|
+
const policy = resolved.policy;
|
|
1506
|
+
const bytesOf = new Map(sizeResult.entries.map((entry) => [
|
|
1507
|
+
entry.target,
|
|
1508
|
+
entry.bytes
|
|
1509
|
+
]));
|
|
1510
|
+
const unmeasuredOf = new Map(sizeResult.unmeasured.map((item) => [item.target, item]));
|
|
1511
|
+
const goneSet = new Set(sizeResult.gone);
|
|
1512
|
+
const prepared = [];
|
|
1513
|
+
for (let index = 0;index < scanResult.hits.length; index += 1) {
|
|
1514
|
+
const hit = scanResult.hits[index];
|
|
1515
|
+
const classification = classifications[index];
|
|
1516
|
+
if (hit === undefined || classification === undefined)
|
|
1517
|
+
continue;
|
|
1518
|
+
if (goneSet.has(hit.target))
|
|
1519
|
+
continue;
|
|
1520
|
+
const bytes = bytesOf.get(hit.target);
|
|
1521
|
+
prepared.push({
|
|
1522
|
+
hit,
|
|
1523
|
+
classification,
|
|
1524
|
+
candidate: {
|
|
1525
|
+
target: hit.target,
|
|
1526
|
+
bytes,
|
|
1527
|
+
unmeasuredReason: bytes === undefined ? unmeasuredOf.get(hit.target)?.reason : undefined,
|
|
1528
|
+
suspect: classification.kind === "suspect-install-tree"
|
|
1529
|
+
}
|
|
1530
|
+
});
|
|
1531
|
+
}
|
|
1532
|
+
const candidates = prepared.map((item) => item.candidate);
|
|
1533
|
+
const batch = deletionBatch(candidates, crossDevice, policy);
|
|
1534
|
+
const book = collectSkips(candidates, crossDevice, policy);
|
|
1535
|
+
const noteOf = new Map(book.entries.map((item) => [item.target, item.note]));
|
|
1536
|
+
const entries = [];
|
|
1537
|
+
for (const { hit, classification, candidate } of prepared) {
|
|
1538
|
+
const reason = skipReasonOf(candidate, crossDevice, policy);
|
|
1539
|
+
const deviceKind = crossDevice.get(hit.target);
|
|
1540
|
+
const unmeasured = unmeasuredOf.get(hit.target);
|
|
1541
|
+
entries.push({
|
|
1542
|
+
target: hit.target,
|
|
1543
|
+
project: hit.project,
|
|
1544
|
+
root: hit.root,
|
|
1545
|
+
bytes: candidate.bytes,
|
|
1546
|
+
basis: candidate.bytes === undefined ? undefined : sizeResult.basis,
|
|
1547
|
+
kind: classification.kind,
|
|
1548
|
+
kindReason: classification.reason,
|
|
1549
|
+
crossDevice: deviceKind,
|
|
1550
|
+
unmeasuredCode: unmeasured?.code,
|
|
1551
|
+
unmeasuredReason: unmeasured?.reason,
|
|
1552
|
+
inBatch: reason === null,
|
|
1553
|
+
skipReason: reason ?? undefined,
|
|
1554
|
+
skipNote: reason === null ? undefined : noteOf.get(hit.target)
|
|
1555
|
+
});
|
|
1556
|
+
if (reason !== null)
|
|
1557
|
+
emit?.({ kind: "skipped", target: hit.target, reason });
|
|
1558
|
+
}
|
|
1559
|
+
return {
|
|
1560
|
+
roots: [...resolved.roots],
|
|
1561
|
+
exclude: [...resolved.exclude],
|
|
1562
|
+
include: [...resolved.include],
|
|
1563
|
+
policy,
|
|
1564
|
+
basis: entries.length > 0 ? sizeResult.basis : undefined,
|
|
1565
|
+
entries,
|
|
1566
|
+
batch,
|
|
1567
|
+
skipped: [...book.entries],
|
|
1568
|
+
warnings: [...scanResult.warnings, ...sizeResult.warnings],
|
|
1569
|
+
nameMatches: {
|
|
1570
|
+
exclude: scanResult.excludeMatches,
|
|
1571
|
+
include: scanResult.includeMatches
|
|
1572
|
+
}
|
|
1573
|
+
};
|
|
1574
|
+
});
|
|
974
1575
|
}
|
|
975
|
-
function
|
|
976
|
-
const
|
|
977
|
-
const
|
|
978
|
-
const
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
if (entry.
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
1576
|
+
function buildOutcomeEntries(plan, expectedSet, stale, rejected, removal) {
|
|
1577
|
+
const staleSet = new Set(stale);
|
|
1578
|
+
const rejectedMap = rejected.length > 0 ? new Map(rejected.map((item) => [item.target, item])) : undefined;
|
|
1579
|
+
const removedSet = new Set(removal?.removed ?? []);
|
|
1580
|
+
const missingSet = new Set(removal?.missing ?? []);
|
|
1581
|
+
const failedMap = new Map((removal?.failed ?? []).map((item) => [
|
|
1582
|
+
item.target,
|
|
1583
|
+
item
|
|
1584
|
+
]));
|
|
1585
|
+
const outcomeOf = (entry) => {
|
|
1586
|
+
if (!entry.inBatch)
|
|
1587
|
+
return { kind: "skipped", reason: entry.skipReason };
|
|
1588
|
+
if (expectedSet !== undefined && !expectedSet.has(entry.target))
|
|
1589
|
+
return { kind: "not-expected" };
|
|
1590
|
+
if (staleSet.has(entry.target))
|
|
1591
|
+
return { kind: "stale" };
|
|
1592
|
+
if (rejectedMap !== undefined)
|
|
1593
|
+
return { kind: "rejected", rejection: rejectedMap.get(entry.target) };
|
|
1594
|
+
if (removedSet.has(entry.target))
|
|
1595
|
+
return { kind: "removed" };
|
|
1596
|
+
if (missingSet.has(entry.target))
|
|
1597
|
+
return { kind: "missing" };
|
|
1598
|
+
const failure = failedMap.get(entry.target);
|
|
1599
|
+
if (failure !== undefined)
|
|
1600
|
+
return { kind: "failed", failure };
|
|
1601
|
+
return { kind: "not-attempted", code: removal.aborted.code };
|
|
1602
|
+
};
|
|
1603
|
+
return plan.entries.map((entry) => ({ ...entry, outcome: outcomeOf(entry) }));
|
|
1604
|
+
}
|
|
1605
|
+
async function executeRun(resolved, options, signal) {
|
|
1606
|
+
const emit = options?.onProgress;
|
|
1607
|
+
const startedAt = Date.now();
|
|
1608
|
+
const plan = await executePlan(resolved, options, signal);
|
|
1609
|
+
const expected = options?.expectedBatch;
|
|
1610
|
+
const expectedSet = expected === undefined ? undefined : new Set(expected);
|
|
1611
|
+
const face = expectedSet === undefined ? plan.batch : plan.batch.filter((target) => expectedSet.has(target));
|
|
1612
|
+
const liveSet = new Set(plan.batch);
|
|
1613
|
+
const drift = expected === undefined || expectedSet === undefined ? undefined : {
|
|
1614
|
+
added: plan.batch.filter((target) => !expectedSet.has(target)),
|
|
1615
|
+
removed: expected.filter((target) => !liveSet.has(target))
|
|
1616
|
+
};
|
|
1617
|
+
let validation;
|
|
1618
|
+
let removal;
|
|
1619
|
+
let stale = [];
|
|
1620
|
+
let rejected = [];
|
|
1621
|
+
if (face.length > 0) {
|
|
1622
|
+
const raw = await withPhase("validate", emit, signal, () => validateTargets(face, {
|
|
1623
|
+
roots: resolved.roots,
|
|
1624
|
+
home: resolved.home,
|
|
1625
|
+
style: resolved.style,
|
|
1626
|
+
signal
|
|
1627
|
+
}));
|
|
1628
|
+
const split = splitStaleRejections(raw.rejected, options?.staleTargets);
|
|
1629
|
+
stale = split.stale;
|
|
1630
|
+
rejected = split.rejected;
|
|
1631
|
+
validation = {
|
|
1632
|
+
accepted: raw.accepted,
|
|
1633
|
+
rejected,
|
|
1634
|
+
mappings: raw.mappings
|
|
1635
|
+
};
|
|
1636
|
+
if (rejected.length === 0) {
|
|
1637
|
+
removal = await withPhase("remove", emit, signal, async () => removeTargets(raw.accepted, {
|
|
1638
|
+
roots: await toTrustRoots(resolved.roots),
|
|
1639
|
+
signal,
|
|
1640
|
+
onProgress: (event) => {
|
|
1641
|
+
if (event.kind === "removed" || event.kind === "missing") {
|
|
1642
|
+
emit?.({
|
|
1643
|
+
kind: "removed",
|
|
1644
|
+
target: event.target,
|
|
1645
|
+
outcome: event.kind
|
|
1646
|
+
});
|
|
1647
|
+
return;
|
|
1648
|
+
}
|
|
1649
|
+
emit?.(event);
|
|
1650
|
+
}
|
|
1651
|
+
}));
|
|
996
1652
|
}
|
|
997
1653
|
}
|
|
998
|
-
|
|
1654
|
+
let status;
|
|
1655
|
+
if (face.length === 0)
|
|
1656
|
+
status = "nothing-to-do";
|
|
1657
|
+
else if (rejected.length > 0)
|
|
1658
|
+
status = "rejected";
|
|
1659
|
+
else
|
|
1660
|
+
status = "executed";
|
|
1661
|
+
const entries = buildOutcomeEntries(plan, expectedSet, stale, rejected, removal);
|
|
1662
|
+
const releasedBytes = entries.reduce((sum, entry) => isSuccessOutcome(entry.outcome) ? sum + (entry.bytes ?? 0) : sum, 0);
|
|
1663
|
+
const report = {
|
|
1664
|
+
status,
|
|
1665
|
+
plan,
|
|
1666
|
+
validation,
|
|
1667
|
+
removal,
|
|
1668
|
+
entries,
|
|
1669
|
+
stale,
|
|
1670
|
+
releasedBytes,
|
|
1671
|
+
drift
|
|
1672
|
+
};
|
|
1673
|
+
emit?.({ kind: "done", status, elapsedMs: Date.now() - startedAt });
|
|
1674
|
+
return report;
|
|
1675
|
+
}
|
|
1676
|
+
function createSweeper(options) {
|
|
1677
|
+
const resolved = resolveOptions(options);
|
|
1678
|
+
return {
|
|
1679
|
+
options: resolved,
|
|
1680
|
+
async plan(planOptions) {
|
|
1681
|
+
const startedAt = Date.now();
|
|
1682
|
+
const plan = await executePlan(resolved, planOptions, planOptions?.signal);
|
|
1683
|
+
planOptions?.onProgress?.({
|
|
1684
|
+
kind: "plan-done",
|
|
1685
|
+
plan,
|
|
1686
|
+
elapsedMs: Date.now() - startedAt
|
|
1687
|
+
});
|
|
1688
|
+
return plan;
|
|
1689
|
+
},
|
|
1690
|
+
run(runOptions) {
|
|
1691
|
+
return executeRun(resolved, runOptions, runOptions?.signal);
|
|
1692
|
+
}
|
|
1693
|
+
};
|
|
999
1694
|
}
|
|
1000
1695
|
// src/render.ts
|
|
1001
1696
|
var BANNER = "SWEEP-NM";
|
|
@@ -1009,18 +1704,6 @@ var bannerLine = (suffix, color) => paint(`${BAR_BLOCK} ${BANNER} ${suffix}`, "
|
|
|
1009
1704
|
var neutralLine = (text, color) => ` ${paint(`${NEUTRAL_BLOCK} ${text}`, "2", color)}`;
|
|
1010
1705
|
var TIER_BIG = 512 * 1024 ** 2;
|
|
1011
1706
|
var TIER_MID = 100 * 1024 ** 2;
|
|
1012
|
-
function formatBytes(bytes) {
|
|
1013
|
-
if (bytes < 1024)
|
|
1014
|
-
return `${Math.round(bytes)} B`;
|
|
1015
|
-
const units = ["KB", "MB", "GB", "TB"];
|
|
1016
|
-
let value = bytes;
|
|
1017
|
-
let index = -1;
|
|
1018
|
-
do {
|
|
1019
|
-
value /= 1024;
|
|
1020
|
-
index += 1;
|
|
1021
|
-
} while (value >= 1024 && index < units.length - 1);
|
|
1022
|
-
return `${Math.round(value * 10) / 10} ${units[index]}`;
|
|
1023
|
-
}
|
|
1024
1707
|
function render(options) {
|
|
1025
1708
|
const { mode, roots, entries, color, home, releasedBytes, pathStyle } = options;
|
|
1026
1709
|
const style = pathStyle ?? PLATFORM_STYLE;
|
|
@@ -1106,11 +1789,6 @@ function displayPath(target, style, home, keepSuffix = false) {
|
|
|
1106
1789
|
const dir = keepSuffix || !fold3(target, style).endsWith(fold3(suffix, style)) ? target : target.slice(0, -suffix.length);
|
|
1107
1790
|
return shortenPath(dir, style, home);
|
|
1108
1791
|
}
|
|
1109
|
-
var sanitizeLine = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "").replace(/\s+/g, " ").trim();
|
|
1110
|
-
var sanitizeOutputLine = (text) => {
|
|
1111
|
-
const indent = /^[ \t]*/.exec(text)?.[0] ?? "";
|
|
1112
|
-
return `${indent}${sanitizeLine(text)}`;
|
|
1113
|
-
};
|
|
1114
1792
|
var padEnd = (text, width) => text + " ".repeat(Math.max(0, width - displayWidth(text)));
|
|
1115
1793
|
var padStart = (text, width) => " ".repeat(Math.max(0, width - displayWidth(text))) + text;
|
|
1116
1794
|
function displayWidth(text) {
|
|
@@ -1160,15 +1838,15 @@ function helpText(color) {
|
|
|
1160
1838
|
}
|
|
1161
1839
|
|
|
1162
1840
|
// src/init.ts
|
|
1163
|
-
import { homedir as
|
|
1841
|
+
import { homedir as homedir5 } from "node:os";
|
|
1164
1842
|
import { join as join4 } from "node:path";
|
|
1165
1843
|
import { createInterface } from "node:readline/promises";
|
|
1166
1844
|
var WHITESPACE = /\s/;
|
|
1167
1845
|
function expandHome(token) {
|
|
1168
1846
|
if (token === "~")
|
|
1169
|
-
return
|
|
1847
|
+
return homedir5();
|
|
1170
1848
|
if (token.startsWith("~/") || token.startsWith("~\\"))
|
|
1171
|
-
return join4(
|
|
1849
|
+
return join4(homedir5(), token.slice(2));
|
|
1172
1850
|
return token;
|
|
1173
1851
|
}
|
|
1174
1852
|
function splitAnswer(answer) {
|
|
@@ -1232,7 +1910,7 @@ async function runInit(deps) {
|
|
|
1232
1910
|
return { state: "declined-overwrite" };
|
|
1233
1911
|
}
|
|
1234
1912
|
io.print(neutralLine("首次使用, 先确定扫描范围", color));
|
|
1235
|
-
const home =
|
|
1913
|
+
const home = homedir5();
|
|
1236
1914
|
let roots = [];
|
|
1237
1915
|
for (;; ) {
|
|
1238
1916
|
const rootsAnswer = await io.ask("扫描根 (逗号或空白分隔多个)", `默认: ${sanitizeLine(shortenHome(home, home))}`);
|
|
@@ -1278,7 +1956,7 @@ async function runInit(deps) {
|
|
|
1278
1956
|
const text = `${JSON.stringify(config, null, 2)}
|
|
1279
1957
|
`;
|
|
1280
1958
|
await writeFile(configPath, text);
|
|
1281
|
-
io.print(` 配置已写入: ${sanitizeLine(shortenHome(configPath,
|
|
1959
|
+
io.print(` 配置已写入: ${sanitizeLine(shortenHome(configPath, homedir5()))} ${paint("✓", "32", color)}`);
|
|
1282
1960
|
io.print("");
|
|
1283
1961
|
io.print(text.trimEnd().split(`
|
|
1284
1962
|
`).map((line) => ` ${line}`).join(`
|
|
@@ -1421,6 +2099,8 @@ function parseArgs(argv) {
|
|
|
1421
2099
|
options.command = only;
|
|
1422
2100
|
return { ok: true, options };
|
|
1423
2101
|
}
|
|
2102
|
+
var RUNTIME_NAME = typeof Bun === "undefined" ? "node" : "bun";
|
|
2103
|
+
var runtimeLabel = `${RUNTIME_NAME} ${process.versions[RUNTIME_NAME] ?? "unknown"}`;
|
|
1424
2104
|
function colorEnabled() {
|
|
1425
2105
|
return process.stdout.isTTY === true && !process.env.NO_COLOR;
|
|
1426
2106
|
}
|
|
@@ -1457,7 +2137,7 @@ function runWizard(configPath, color) {
|
|
|
1457
2137
|
firstSymlinkOnTarget,
|
|
1458
2138
|
async writeFile(path, text) {
|
|
1459
2139
|
await mkdir(dirname(path), { recursive: true });
|
|
1460
|
-
await
|
|
2140
|
+
await writeFile(path, text, "utf8");
|
|
1461
2141
|
},
|
|
1462
2142
|
io: createReadlineIO(color)
|
|
1463
2143
|
});
|
|
@@ -1495,39 +2175,57 @@ async function resolveConfig(resolved, color) {
|
|
|
1495
2175
|
return null;
|
|
1496
2176
|
}
|
|
1497
2177
|
var ABORTED_HINT = "整批中止, 未执行删除";
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
2178
|
+
function toRenderEntry(entry) {
|
|
2179
|
+
const notes = [];
|
|
2180
|
+
if (entry.kind === "suspect-install-tree")
|
|
2181
|
+
notes.push(`疑似安装树: ${entry.kindReason}`);
|
|
2182
|
+
if (entry.crossDevice !== undefined)
|
|
2183
|
+
notes.push(crossDeviceNote(entry.crossDevice));
|
|
2184
|
+
if (entry.bytes === undefined && entry.unmeasuredReason !== undefined)
|
|
2185
|
+
notes.push(`体积统计失败: ${entry.unmeasuredReason}`);
|
|
2186
|
+
return {
|
|
2187
|
+
target: entry.target,
|
|
2188
|
+
bytes: entry.bytes,
|
|
2189
|
+
project: basename(entry.project),
|
|
2190
|
+
suspect: entry.kind === "suspect-install-tree",
|
|
2191
|
+
...notes.length > 0 ? { note: notes.join(" ") } : {}
|
|
2192
|
+
};
|
|
1503
2193
|
}
|
|
1504
|
-
function
|
|
1505
|
-
const
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
if (outcome !== undefined)
|
|
1517
|
-
byTarget.set(target, outcome);
|
|
1518
|
-
}
|
|
1519
|
-
const fallbackOf = (entry) => {
|
|
1520
|
-
if (removal.aborted !== undefined)
|
|
2194
|
+
function outcomeResult(entry) {
|
|
2195
|
+
const { outcome } = entry;
|
|
2196
|
+
switch (outcome.kind) {
|
|
2197
|
+
case "removed":
|
|
2198
|
+
case "missing":
|
|
2199
|
+
case "stale":
|
|
2200
|
+
return { ok: true };
|
|
2201
|
+
case "failed":
|
|
2202
|
+
return { ok: false, error: outcome.failure.message };
|
|
2203
|
+
case "skipped":
|
|
2204
|
+
return outcome.reason === "unmeasured" ? { ok: false } : { ok: false, error: entry.skipNote };
|
|
2205
|
+
case "not-attempted":
|
|
1521
2206
|
return { ok: false, error: ABORTED_HINT };
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
return { ok: false
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
2207
|
+
case "rejected":
|
|
2208
|
+
case "not-expected":
|
|
2209
|
+
return { ok: false };
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
var toExecuteEntry = (entry) => ({
|
|
2213
|
+
...toRenderEntry(entry),
|
|
2214
|
+
...outcomeResult(entry)
|
|
2215
|
+
});
|
|
2216
|
+
function planTrailer(plan) {
|
|
2217
|
+
const candidates = plan.entries.map((entry) => ({
|
|
2218
|
+
target: entry.target,
|
|
2219
|
+
bytes: entry.bytes,
|
|
2220
|
+
unmeasuredReason: entry.unmeasuredReason,
|
|
2221
|
+
suspect: entry.kind === "suspect-install-tree"
|
|
1530
2222
|
}));
|
|
2223
|
+
const device = new Map;
|
|
2224
|
+
for (const entry of plan.entries) {
|
|
2225
|
+
if (entry.crossDevice !== undefined)
|
|
2226
|
+
device.set(entry.target, entry.crossDevice);
|
|
2227
|
+
}
|
|
2228
|
+
return [...collectSkips(candidates, device, plan.policy).trailer];
|
|
1531
2229
|
}
|
|
1532
2230
|
var BUILTIN_EXCLUDE_NAMES = new Set(DEFAULT_EXCLUDE);
|
|
1533
2231
|
function collectNameNotes(excludeMatches, includeMatches, color) {
|
|
@@ -1552,103 +2250,59 @@ function collectNameNotes(excludeMatches, includeMatches, color) {
|
|
|
1552
2250
|
warn("包含名单无一条命中, 本次扫描必为空结果 (请核对名字与大小写; 若名字位于被排除的目录之下则属预期)", color);
|
|
1553
2251
|
return notes;
|
|
1554
2252
|
}
|
|
1555
|
-
function toEntries(hits, sizeResult, home, crossDevice) {
|
|
1556
|
-
const bytesOf = new Map(sizeResult.entries.map((entry) => [
|
|
1557
|
-
entry.target,
|
|
1558
|
-
entry.bytes
|
|
1559
|
-
]));
|
|
1560
|
-
const reasonOf = new Map(sizeResult.unmeasured.map((item) => [
|
|
1561
|
-
item.target,
|
|
1562
|
-
item.reason
|
|
1563
|
-
]));
|
|
1564
|
-
const entries = [];
|
|
1565
|
-
for (const hit of hits) {
|
|
1566
|
-
const project = basename(hit.project);
|
|
1567
|
-
const classification = classifyTarget(hit.target, { home });
|
|
1568
|
-
const suspect = classification.kind === "suspect-install-tree";
|
|
1569
|
-
const notes = [];
|
|
1570
|
-
if (suspect)
|
|
1571
|
-
notes.push(`疑似安装树: ${classification.reason}`);
|
|
1572
|
-
const deviceKind = crossDevice.get(hit.target);
|
|
1573
|
-
if (deviceKind !== undefined)
|
|
1574
|
-
notes.push(crossDeviceNote(deviceKind));
|
|
1575
|
-
const note = notes.length > 0 ? notes.join(" ") : undefined;
|
|
1576
|
-
const bytes = bytesOf.get(hit.target);
|
|
1577
|
-
if (bytes !== undefined) {
|
|
1578
|
-
entries.push({ project, target: hit.target, bytes, suspect, note });
|
|
1579
|
-
continue;
|
|
1580
|
-
}
|
|
1581
|
-
const reason = reasonOf.get(hit.target);
|
|
1582
|
-
if (reason !== undefined) {
|
|
1583
|
-
entries.push({
|
|
1584
|
-
project,
|
|
1585
|
-
target: hit.target,
|
|
1586
|
-
suspect,
|
|
1587
|
-
note: note === undefined ? `体积统计失败: ${reason}` : `${note} 体积统计失败: ${reason}`
|
|
1588
|
-
});
|
|
1589
|
-
}
|
|
1590
|
-
}
|
|
1591
|
-
return entries;
|
|
1592
|
-
}
|
|
1593
2253
|
async function sweep(config, options, color) {
|
|
1594
|
-
const
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
const
|
|
1601
|
-
const
|
|
1602
|
-
const
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
const
|
|
1607
|
-
const crossDevice = await findCrossDeviceTargets(scanResult.hits.map((hit) => hit.target), { roots });
|
|
1608
|
-
const entries = toEntries(scanResult.hits, sizeResult, home, crossDevice);
|
|
1609
|
-
const { trailer, hints: skippedHints } = collectSkips(entries, crossDevice, options.force);
|
|
2254
|
+
const sweeper = createSweeper({
|
|
2255
|
+
roots: config.roots,
|
|
2256
|
+
exclude: mergeNames(config.exclude, options.exclude),
|
|
2257
|
+
include: mergeNames(config.include, options.include),
|
|
2258
|
+
policy: { releaseSuspects: options.force }
|
|
2259
|
+
});
|
|
2260
|
+
const runtime = process.stdout.isTTY === true ? runtimeLabel : undefined;
|
|
2261
|
+
const home = homedir6();
|
|
2262
|
+
const onProgress = (event) => {
|
|
2263
|
+
if (event.kind === "warning")
|
|
2264
|
+
warn(event.warning.message, color);
|
|
2265
|
+
};
|
|
2266
|
+
const nameNotesOf = (plan) => collectNameNotes(plan.nameMatches.exclude, plan.nameMatches.include, color);
|
|
1610
2267
|
if (!options.yes) {
|
|
2268
|
+
const plan = await sweeper.plan({ onProgress });
|
|
1611
2269
|
print(render({
|
|
1612
2270
|
mode: "preview",
|
|
1613
|
-
roots,
|
|
1614
|
-
entries,
|
|
2271
|
+
roots: plan.roots,
|
|
2272
|
+
entries: plan.entries.map(toRenderEntry),
|
|
1615
2273
|
color,
|
|
1616
2274
|
home,
|
|
1617
|
-
notes:
|
|
2275
|
+
notes: nameNotesOf(plan),
|
|
1618
2276
|
runtime,
|
|
1619
|
-
trailer
|
|
2277
|
+
trailer: planTrailer(plan)
|
|
1620
2278
|
}));
|
|
1621
2279
|
return 0;
|
|
1622
2280
|
}
|
|
1623
|
-
const
|
|
1624
|
-
|
|
1625
|
-
|
|
2281
|
+
const report = await sweeper.run({ onProgress });
|
|
2282
|
+
if (report.status === "rejected") {
|
|
2283
|
+
const rejected = report.validation?.rejected ?? [];
|
|
1626
2284
|
warn(`整批拒绝: ${rejected.length} 个目标未通过安全闸, 未执行任何删除`, color);
|
|
1627
2285
|
for (const item of rejected)
|
|
1628
|
-
notice(` ${item.target} (${item.
|
|
2286
|
+
notice(` ${item.target} (${item.message})`);
|
|
1629
2287
|
return 1;
|
|
1630
2288
|
}
|
|
1631
|
-
const removal = await removeTargets(accepted, {
|
|
1632
|
-
roots: await trustRoots(roots)
|
|
1633
|
-
});
|
|
1634
|
-
const report = withOutcomes(entries, batch, accepted, removal, skippedHints);
|
|
1635
|
-
const releasedBytes = report.reduce((total, entry) => entry.ok === false ? total : total + (entry.bytes ?? 0), 0);
|
|
1636
2289
|
print(render({
|
|
1637
2290
|
mode: "execute",
|
|
1638
|
-
roots,
|
|
1639
|
-
entries: report,
|
|
2291
|
+
roots: report.plan.roots,
|
|
2292
|
+
entries: report.entries.map(toExecuteEntry),
|
|
1640
2293
|
color,
|
|
1641
2294
|
home,
|
|
1642
|
-
releasedBytes,
|
|
1643
|
-
notes:
|
|
2295
|
+
releasedBytes: report.releasedBytes,
|
|
2296
|
+
notes: nameNotesOf(report.plan),
|
|
1644
2297
|
runtime,
|
|
1645
|
-
trailer
|
|
2298
|
+
trailer: planTrailer(report.plan)
|
|
1646
2299
|
}));
|
|
1647
|
-
if (removal
|
|
1648
|
-
warn(`整批中止: ${removal.aborted.
|
|
1649
|
-
notice(` 本轮未执行删除: ${batch.length} 处`);
|
|
2300
|
+
if (report.removal?.aborted !== undefined) {
|
|
2301
|
+
warn(`整批中止: ${report.removal.aborted.message}`, color);
|
|
2302
|
+
notice(` 本轮未执行删除: ${report.plan.batch.length} 处`);
|
|
1650
2303
|
}
|
|
1651
|
-
|
|
2304
|
+
const summary = summarizeReport(report);
|
|
2305
|
+
return summary.failed === 0 && summary.unprocessed === 0 && !summary.aborted ? 0 : 1;
|
|
1652
2306
|
}
|
|
1653
2307
|
async function main() {
|
|
1654
2308
|
const color = colorEnabled();
|