@iyowei/sweep-node-modules 0.4.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 +612 -93
- package/README.zh-CN.md +612 -93
- 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 +4 -3
- 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 +14 -52
- package/bin/sweep-nm.mjs +0 -190
- package/dist/cli.js +0 -1699
package/dist/cli.js
DELETED
|
@@ -1,1699 +0,0 @@
|
|
|
1
|
-
// src/cli.ts
|
|
2
|
-
import { lstat as lstat3, mkdir, realpath as realpath3 } from "node:fs/promises";
|
|
3
|
-
import { homedir as homedir5 } from "node:os";
|
|
4
|
-
import { basename, dirname } from "node:path";
|
|
5
|
-
|
|
6
|
-
// src/classify.ts
|
|
7
|
-
import { homedir as homedir3 } from "node:os";
|
|
8
|
-
|
|
9
|
-
// src/config.ts
|
|
10
|
-
import { readFile } from "node:fs/promises";
|
|
11
|
-
import { homedir } from "node:os";
|
|
12
|
-
import { posix, win32 } from "node:path";
|
|
13
|
-
var DEFAULT_EXCLUDE = [
|
|
14
|
-
".bun",
|
|
15
|
-
".npm",
|
|
16
|
-
".pnpm-store",
|
|
17
|
-
".yarn",
|
|
18
|
-
".nvm",
|
|
19
|
-
"nvm",
|
|
20
|
-
".fnm",
|
|
21
|
-
".volta",
|
|
22
|
-
".asdf",
|
|
23
|
-
".n",
|
|
24
|
-
".vscode",
|
|
25
|
-
".vscode-insiders",
|
|
26
|
-
".vscode-server",
|
|
27
|
-
".cursor",
|
|
28
|
-
".antigravity",
|
|
29
|
-
"Library",
|
|
30
|
-
".local",
|
|
31
|
-
".config",
|
|
32
|
-
".cache",
|
|
33
|
-
".claude"
|
|
34
|
-
];
|
|
35
|
-
function platformDefaultPath(platform, env, home) {
|
|
36
|
-
if (platform === "win32") {
|
|
37
|
-
const roaming = env.APPDATA || win32.join(env.USERPROFILE || home, "AppData", "Roaming");
|
|
38
|
-
return win32.join(roaming, "sweep-node-modules", "config.json");
|
|
39
|
-
}
|
|
40
|
-
return posix.join(home, ".config", "sweep-node-modules", "config.json");
|
|
41
|
-
}
|
|
42
|
-
function resolveConfigPath(options) {
|
|
43
|
-
if (options.flag) {
|
|
44
|
-
return { path: options.flag, source: "flag" };
|
|
45
|
-
}
|
|
46
|
-
const env = options.env ?? process.env;
|
|
47
|
-
if (env.SWEEP_NM_CONFIG) {
|
|
48
|
-
return { path: env.SWEEP_NM_CONFIG, source: "env" };
|
|
49
|
-
}
|
|
50
|
-
const platform = options.platform ?? process.platform;
|
|
51
|
-
const home = options.homedir ?? homedir();
|
|
52
|
-
return {
|
|
53
|
-
path: platformDefaultPath(platform, env, home),
|
|
54
|
-
source: "platform-default"
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
function describeActual(value) {
|
|
58
|
-
if (value === undefined)
|
|
59
|
-
return "缺失";
|
|
60
|
-
if (value === null)
|
|
61
|
-
return "null";
|
|
62
|
-
if (Array.isArray(value))
|
|
63
|
-
return "array";
|
|
64
|
-
return typeof value;
|
|
65
|
-
}
|
|
66
|
-
function fieldError(container, field, optional) {
|
|
67
|
-
const value = container[field];
|
|
68
|
-
if (value === undefined) {
|
|
69
|
-
return optional ? null : `${field} 应为字符串数组 (实际: 缺失)`;
|
|
70
|
-
}
|
|
71
|
-
if (!Array.isArray(value)) {
|
|
72
|
-
return `${field} 应为字符串数组 (实际: ${describeActual(value)})`;
|
|
73
|
-
}
|
|
74
|
-
const badIndex = value.findIndex((item) => typeof item !== "string");
|
|
75
|
-
if (badIndex !== -1) {
|
|
76
|
-
return `${field} 第 ${badIndex + 1} 项应为字符串 (实际: ${describeActual(value[badIndex])})`;
|
|
77
|
-
}
|
|
78
|
-
return null;
|
|
79
|
-
}
|
|
80
|
-
function shapeError(value) {
|
|
81
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
82
|
-
return `顶层应为对象 (实际: ${describeActual(value)})`;
|
|
83
|
-
}
|
|
84
|
-
const candidate = value;
|
|
85
|
-
const rootsError = fieldError(candidate, "roots", false);
|
|
86
|
-
if (rootsError !== null)
|
|
87
|
-
return rootsError;
|
|
88
|
-
const excludeError = fieldError(candidate, "exclude", true);
|
|
89
|
-
if (excludeError !== null)
|
|
90
|
-
return excludeError;
|
|
91
|
-
return fieldError(candidate, "include", true);
|
|
92
|
-
}
|
|
93
|
-
async function loadConfig(path) {
|
|
94
|
-
let text;
|
|
95
|
-
try {
|
|
96
|
-
text = await readFile(path, "utf8");
|
|
97
|
-
} catch (error) {
|
|
98
|
-
if (error.code === "ENOENT")
|
|
99
|
-
return { state: "absent" };
|
|
100
|
-
throw new Error(`配置读取失败 (${path}): ${error.message}`);
|
|
101
|
-
}
|
|
102
|
-
let data;
|
|
103
|
-
try {
|
|
104
|
-
data = JSON.parse(text);
|
|
105
|
-
} catch (error) {
|
|
106
|
-
throw new Error(`配置损坏 (${path}): JSON 解析失败: ${error.message}`);
|
|
107
|
-
}
|
|
108
|
-
const error = shapeError(data);
|
|
109
|
-
if (error !== null) {
|
|
110
|
-
throw new Error(`配置损坏 (${path}): ${error}`);
|
|
111
|
-
}
|
|
112
|
-
const raw = data;
|
|
113
|
-
return {
|
|
114
|
-
state: "ok",
|
|
115
|
-
config: {
|
|
116
|
-
roots: raw.roots,
|
|
117
|
-
exclude: raw.exclude ?? [...DEFAULT_EXCLUDE],
|
|
118
|
-
include: raw.include ?? []
|
|
119
|
-
}
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
async function loadResolvedConfig(resolved) {
|
|
123
|
-
const result = await loadConfig(resolved.path);
|
|
124
|
-
if (result.state === "absent" && resolved.source !== "platform-default") {
|
|
125
|
-
throw new Error(`配置不存在 (${resolved.path}), 请检查路径`);
|
|
126
|
-
}
|
|
127
|
-
return result;
|
|
128
|
-
}
|
|
129
|
-
function mergeNames(configNames, cliNames) {
|
|
130
|
-
return [...new Set([...configNames, ...cliNames])].filter((name) => name !== "node_modules" && name !== ".git");
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// src/guard.ts
|
|
134
|
-
import { lstat, realpath, stat } from "node:fs/promises";
|
|
135
|
-
import { homedir as homedir2 } from "node:os";
|
|
136
|
-
import { posix as posix2, win32 as win322 } from "node:path";
|
|
137
|
-
var POSIX_STYLE = {
|
|
138
|
-
name: "posix",
|
|
139
|
-
ops: posix2,
|
|
140
|
-
caseInsensitive: false
|
|
141
|
-
};
|
|
142
|
-
var WIN32_STYLE = {
|
|
143
|
-
name: "win32",
|
|
144
|
-
ops: win322,
|
|
145
|
-
caseInsensitive: true
|
|
146
|
-
};
|
|
147
|
-
function nativeStyle() {
|
|
148
|
-
return process.platform === "win32" ? WIN32_STYLE : POSIX_STYLE;
|
|
149
|
-
}
|
|
150
|
-
function fold(p, style) {
|
|
151
|
-
return style.caseInsensitive ? p.toLowerCase() : p;
|
|
152
|
-
}
|
|
153
|
-
function dedupeKey(realPath, style) {
|
|
154
|
-
return fold(realPath, style);
|
|
155
|
-
}
|
|
156
|
-
function hasNodeModulesLeaf(target, style) {
|
|
157
|
-
return fold(style.ops.basename(target), style) === "node_modules";
|
|
158
|
-
}
|
|
159
|
-
function insideAnyRoot(realPath, roots, style) {
|
|
160
|
-
return roots.some((root) => {
|
|
161
|
-
const rel = style.ops.relative(fold(root, style), fold(realPath, style));
|
|
162
|
-
if (rel === "" || style.ops.isAbsolute(rel))
|
|
163
|
-
return false;
|
|
164
|
-
return rel !== ".." && !rel.startsWith(`..${style.ops.sep}`);
|
|
165
|
-
});
|
|
166
|
-
}
|
|
167
|
-
function isFilesystemRootBody(realPath, style) {
|
|
168
|
-
return fold(style.ops.parse(realPath).root, style) === fold(realPath, style);
|
|
169
|
-
}
|
|
170
|
-
function isHomeBody(realPath, home, style) {
|
|
171
|
-
return home !== null && dedupeKey(realPath, style) === dedupeKey(home, style);
|
|
172
|
-
}
|
|
173
|
-
function firstSymlinkOnAnchor(links) {
|
|
174
|
-
for (const link of links) {
|
|
175
|
-
if (link.symlink)
|
|
176
|
-
return link.path;
|
|
177
|
-
}
|
|
178
|
-
return null;
|
|
179
|
-
}
|
|
180
|
-
function anchorChainPaths(root, style) {
|
|
181
|
-
const absolute = style.ops.isAbsolute(root) ? root : style.ops.resolve(root);
|
|
182
|
-
const prefix = style.ops.parse(absolute).root;
|
|
183
|
-
const chain = [];
|
|
184
|
-
let cursor = prefix;
|
|
185
|
-
for (const part of absolute.slice(prefix.length).split(style.ops.sep)) {
|
|
186
|
-
if (part === "")
|
|
187
|
-
continue;
|
|
188
|
-
cursor = style.ops.join(cursor, part);
|
|
189
|
-
chain.push(cursor);
|
|
190
|
-
}
|
|
191
|
-
return chain;
|
|
192
|
-
}
|
|
193
|
-
async function tryRealpath(p) {
|
|
194
|
-
try {
|
|
195
|
-
return await realpath(p);
|
|
196
|
-
} catch {
|
|
197
|
-
return null;
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
async function collectAnchorLinks(root, style) {
|
|
201
|
-
const links = [];
|
|
202
|
-
for (const path of anchorChainPaths(root, style)) {
|
|
203
|
-
try {
|
|
204
|
-
links.push({ path, symlink: (await lstat(path)).isSymbolicLink() });
|
|
205
|
-
} catch {}
|
|
206
|
-
}
|
|
207
|
-
return links;
|
|
208
|
-
}
|
|
209
|
-
async function firstSymlinkOnTarget(target) {
|
|
210
|
-
return firstSymlinkOnAnchor(await collectAnchorLinks(target, nativeStyle()));
|
|
211
|
-
}
|
|
212
|
-
async function firstSymlinkOnRoot(root) {
|
|
213
|
-
return firstSymlinkOnTarget(root);
|
|
214
|
-
}
|
|
215
|
-
async function validateTargets(targets, options) {
|
|
216
|
-
const style = options.style ?? nativeStyle();
|
|
217
|
-
const homeOption = options.home === undefined ? homedir2() : options.home;
|
|
218
|
-
const anchors = [];
|
|
219
|
-
for (const root of options.roots) {
|
|
220
|
-
anchors.push({
|
|
221
|
-
configured: root,
|
|
222
|
-
real: await tryRealpath(root),
|
|
223
|
-
link: firstSymlinkOnAnchor(await collectAnchorLinks(root, style))
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
const brokenAnchors = anchors.filter((anchor) => anchor.real !== null && anchor.link !== null);
|
|
227
|
-
const roots = [];
|
|
228
|
-
for (const anchor of anchors) {
|
|
229
|
-
if (anchor.real !== null)
|
|
230
|
-
roots.push(anchor.real);
|
|
231
|
-
}
|
|
232
|
-
const home = homeOption === null ? null : await tryRealpath(homeOption) ?? homeOption;
|
|
233
|
-
const accepted = [];
|
|
234
|
-
const rejected = [];
|
|
235
|
-
const seen = new Set;
|
|
236
|
-
for (const target of targets) {
|
|
237
|
-
if (!hasNodeModulesLeaf(target, style)) {
|
|
238
|
-
rejected.push({ target, reason: "路径末段不是 node_modules" });
|
|
239
|
-
continue;
|
|
240
|
-
}
|
|
241
|
-
const real = await tryRealpath(target);
|
|
242
|
-
if (real === null) {
|
|
243
|
-
rejected.push({ target, reason: "realpath 失败 (目标不存在或不可读)" });
|
|
244
|
-
continue;
|
|
245
|
-
}
|
|
246
|
-
const brokenAnchor = brokenAnchors.find((anchor) => insideAnyRoot(real, [anchor.real], style));
|
|
247
|
-
if (brokenAnchor !== undefined) {
|
|
248
|
-
rejected.push({
|
|
249
|
-
target,
|
|
250
|
-
reason: `根锚点被换位为符号链接 (根: ${brokenAnchor.configured}; 符号链接: ${brokenAnchor.link}), 请把配置根改为不含符号链接的真实路径`
|
|
251
|
-
});
|
|
252
|
-
continue;
|
|
253
|
-
}
|
|
254
|
-
if (isFilesystemRootBody(real, style)) {
|
|
255
|
-
rejected.push({ target, reason: "目标是文件系统根本体" });
|
|
256
|
-
continue;
|
|
257
|
-
}
|
|
258
|
-
if (isHomeBody(real, home, style)) {
|
|
259
|
-
rejected.push({ target, reason: "目标是 home 本体" });
|
|
260
|
-
continue;
|
|
261
|
-
}
|
|
262
|
-
if (!hasNodeModulesLeaf(real, style)) {
|
|
263
|
-
rejected.push({ target, reason: "realpath 后的末段不是 node_modules" });
|
|
264
|
-
continue;
|
|
265
|
-
}
|
|
266
|
-
if (!insideAnyRoot(real, roots, style)) {
|
|
267
|
-
rejected.push({ target, reason: "realpath 后不在任何 root 之下" });
|
|
268
|
-
continue;
|
|
269
|
-
}
|
|
270
|
-
const key = dedupeKey(real, style);
|
|
271
|
-
if (seen.has(key)) {
|
|
272
|
-
rejected.push({ target, reason: "重复目标 (realpath 去重)" });
|
|
273
|
-
continue;
|
|
274
|
-
}
|
|
275
|
-
seen.add(key);
|
|
276
|
-
accepted.push(real);
|
|
277
|
-
}
|
|
278
|
-
return { accepted, rejected };
|
|
279
|
-
}
|
|
280
|
-
var fsDeviceProbe = async (path, follow) => {
|
|
281
|
-
try {
|
|
282
|
-
return (await (follow ? stat : lstat)(path)).dev;
|
|
283
|
-
} catch {
|
|
284
|
-
return null;
|
|
285
|
-
}
|
|
286
|
-
};
|
|
287
|
-
function owningRoot(target, roots, style) {
|
|
288
|
-
let best = null;
|
|
289
|
-
for (const root of roots) {
|
|
290
|
-
if (!insideAnyRoot(target, [root], style))
|
|
291
|
-
continue;
|
|
292
|
-
if (best === null || root.length > best.length)
|
|
293
|
-
best = root;
|
|
294
|
-
}
|
|
295
|
-
return best;
|
|
296
|
-
}
|
|
297
|
-
async function findCrossDeviceTargets(targets, options) {
|
|
298
|
-
const style = options.style ?? nativeStyle();
|
|
299
|
-
const probe = options.probe ?? fsDeviceProbe;
|
|
300
|
-
const devices = new Map;
|
|
301
|
-
const found = new Map;
|
|
302
|
-
for (const target of targets) {
|
|
303
|
-
const root = owningRoot(target, options.roots, style);
|
|
304
|
-
if (root === null)
|
|
305
|
-
continue;
|
|
306
|
-
let rootDev = devices.get(root);
|
|
307
|
-
if (rootDev === undefined) {
|
|
308
|
-
rootDev = await probe(root, true);
|
|
309
|
-
devices.set(root, rootDev);
|
|
310
|
-
}
|
|
311
|
-
if (rootDev === null)
|
|
312
|
-
continue;
|
|
313
|
-
const targetDev = await probe(target, false);
|
|
314
|
-
if (targetDev === null || targetDev === rootDev)
|
|
315
|
-
continue;
|
|
316
|
-
const parentDev = await probe(style.ops.dirname(target), true);
|
|
317
|
-
found.set(target, parentDev !== null && parentDev !== targetDev ? "target-itself" : "on-path");
|
|
318
|
-
}
|
|
319
|
-
return found;
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
// src/classify.ts
|
|
323
|
-
var fold2 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
|
|
324
|
-
var INSTALL_TREE_SEGMENTS = new Set([...DEFAULT_EXCLUDE, "extensions", "_npx"].map((name) => name.toLowerCase()));
|
|
325
|
-
function classifyTarget(target, options = {}) {
|
|
326
|
-
const style = options.style ?? nativeStyle();
|
|
327
|
-
const homeOption = options.home === undefined ? homedir3() : options.home;
|
|
328
|
-
const parts = target.split(style.ops.sep).filter((part) => part !== "");
|
|
329
|
-
const ancestors = parts.slice(0, -1);
|
|
330
|
-
for (const segment of ancestors) {
|
|
331
|
-
if (INSTALL_TREE_SEGMENTS.has(segment.toLowerCase()))
|
|
332
|
-
return {
|
|
333
|
-
kind: "suspect-install-tree",
|
|
334
|
-
reason: `位于 ${segment} 安装树目录`
|
|
335
|
-
};
|
|
336
|
-
}
|
|
337
|
-
const parent = ancestors[ancestors.length - 1];
|
|
338
|
-
if (parent !== undefined && parent.toLowerCase() === "lib")
|
|
339
|
-
return {
|
|
340
|
-
kind: "suspect-install-tree",
|
|
341
|
-
reason: "父目录为 lib, 形如版本管理器的 node 安装树"
|
|
342
|
-
};
|
|
343
|
-
if (homeOption !== null) {
|
|
344
|
-
const relative = style.ops.relative(fold2(homeOption, style), fold2(target, style));
|
|
345
|
-
const [first] = relative.split(style.ops.sep);
|
|
346
|
-
if (first !== undefined && first !== ".." && first !== "." && first.startsWith(".") && !style.ops.isAbsolute(relative))
|
|
347
|
-
return {
|
|
348
|
-
kind: "suspect-install-tree",
|
|
349
|
-
reason: `位于 ${first} (家目录下的隐藏目录)`
|
|
350
|
-
};
|
|
351
|
-
}
|
|
352
|
-
return { kind: "project" };
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
// src/delete.ts
|
|
356
|
-
import { lstat as lstat2, rm } from "node:fs/promises";
|
|
357
|
-
import { isAbsolute, join, relative, sep } from "node:path";
|
|
358
|
-
var ERROR_HINTS = {
|
|
359
|
-
EACCES: "权限不足, 拒绝删除",
|
|
360
|
-
EPERM: "操作不被允许",
|
|
361
|
-
EBUSY: "目标被占用",
|
|
362
|
-
ENOTEMPTY: "目录非空",
|
|
363
|
-
EROFS: "目标位于只读文件系统"
|
|
364
|
-
};
|
|
365
|
-
var PARTIAL_DELETION_HINT = "注意: 目录内容可能已被部分或全部删除, 请复查";
|
|
366
|
-
function describeCode(error) {
|
|
367
|
-
const fsError = error;
|
|
368
|
-
const code = fsError?.code;
|
|
369
|
-
if (typeof code !== "string" || code === "") {
|
|
370
|
-
return `未知错误: ${fsError?.message ?? String(error)}`;
|
|
371
|
-
}
|
|
372
|
-
return `${code}: ${ERROR_HINTS[code] ?? "删除未成功"}`;
|
|
373
|
-
}
|
|
374
|
-
function describeRemovalError(target, error) {
|
|
375
|
-
return `${describeCode(error)} (目标: ${target}; ${PARTIAL_DELETION_HINT})`;
|
|
376
|
-
}
|
|
377
|
-
function describeReviewError(target, path, error) {
|
|
378
|
-
return `安全复核未完成 (${describeCode(error)}) (目标: ${target}; 组件: ${path}; 未执行删除)`;
|
|
379
|
-
}
|
|
380
|
-
function describeVanishedReview(target, path) {
|
|
381
|
-
return `安全复核未完成 (ENOENT: 路径组件消失) (目标: ${target}; 组件: ${path}; 请复查目标是否仍存在; 未执行删除; 若目标确已不存在, 可忽略此条)`;
|
|
382
|
-
}
|
|
383
|
-
async function checkGone(path) {
|
|
384
|
-
try {
|
|
385
|
-
await lstat2(path);
|
|
386
|
-
return "present";
|
|
387
|
-
} catch (error) {
|
|
388
|
-
return error?.code === "ENOENT" ? "gone" : "unknown";
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
function describeSurvivor(target, state) {
|
|
392
|
-
const review = state === "present" ? "复核确认目标仍存在" : "目标是否仍存在未能核验";
|
|
393
|
-
return `ENOENT: 删除中途失败 (${review}) (目标: ${target}; ${PARTIAL_DELETION_HINT})`;
|
|
394
|
-
}
|
|
395
|
-
function isUnder(root, target) {
|
|
396
|
-
const rel = relative(root, target);
|
|
397
|
-
if (rel === "" || isAbsolute(rel))
|
|
398
|
-
return false;
|
|
399
|
-
return rel !== ".." && !rel.startsWith(`..${sep}`);
|
|
400
|
-
}
|
|
401
|
-
function componentChain(root, target) {
|
|
402
|
-
const chain = [root];
|
|
403
|
-
let cursor = root;
|
|
404
|
-
for (const part of relative(root, target).split(sep).slice(0, -1)) {
|
|
405
|
-
cursor = join(cursor, part);
|
|
406
|
-
chain.push(cursor);
|
|
407
|
-
}
|
|
408
|
-
return chain;
|
|
409
|
-
}
|
|
410
|
-
async function isSymlinkHead(path) {
|
|
411
|
-
try {
|
|
412
|
-
return (await lstat2(path)).isSymbolicLink();
|
|
413
|
-
} catch {
|
|
414
|
-
return false;
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
async function reviewComponents(chain) {
|
|
418
|
-
for (const path of chain) {
|
|
419
|
-
try {
|
|
420
|
-
const stats = await lstat2(path);
|
|
421
|
-
if (!stats.isDirectory())
|
|
422
|
-
return { kind: "unsafe", path };
|
|
423
|
-
} catch (error) {
|
|
424
|
-
const code = error?.code;
|
|
425
|
-
if (code === "ENOENT")
|
|
426
|
-
return { kind: "vanished", path };
|
|
427
|
-
return { kind: "unverified", path, error };
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
return null;
|
|
431
|
-
}
|
|
432
|
-
async function removeTargets(targets, options) {
|
|
433
|
-
const result = { removed: [], missing: [], failed: [] };
|
|
434
|
-
const roots = options?.roots ?? [];
|
|
435
|
-
for (const target of targets) {
|
|
436
|
-
const root = roots.find((candidate) => isUnder(candidate.real, target));
|
|
437
|
-
if (root === undefined) {
|
|
438
|
-
result.aborted = {
|
|
439
|
-
target,
|
|
440
|
-
reason: `安全复核失败 (目标不在任何 roots 之下): ${target}`
|
|
441
|
-
};
|
|
442
|
-
break;
|
|
443
|
-
}
|
|
444
|
-
if (await isSymlinkHead(root.configured)) {
|
|
445
|
-
result.aborted = {
|
|
446
|
-
target,
|
|
447
|
-
reason: `安全复核失败 (根被替换为符号链接): ${root.configured}`
|
|
448
|
-
};
|
|
449
|
-
break;
|
|
450
|
-
}
|
|
451
|
-
const finding = await reviewComponents(componentChain(root.real, target));
|
|
452
|
-
if (finding !== null) {
|
|
453
|
-
if (finding.kind === "vanished") {
|
|
454
|
-
result.failed.push({
|
|
455
|
-
target,
|
|
456
|
-
error: describeVanishedReview(target, finding.path)
|
|
457
|
-
});
|
|
458
|
-
continue;
|
|
459
|
-
}
|
|
460
|
-
if (finding.kind === "unsafe") {
|
|
461
|
-
result.aborted = {
|
|
462
|
-
target,
|
|
463
|
-
reason: `安全复核失败 (路径组件被替换): ${finding.path}`
|
|
464
|
-
};
|
|
465
|
-
break;
|
|
466
|
-
}
|
|
467
|
-
result.failed.push({
|
|
468
|
-
target,
|
|
469
|
-
error: describeReviewError(target, finding.path, finding.error)
|
|
470
|
-
});
|
|
471
|
-
continue;
|
|
472
|
-
}
|
|
473
|
-
try {
|
|
474
|
-
await rm(target, { recursive: true, force: false });
|
|
475
|
-
result.removed.push(target);
|
|
476
|
-
} catch (error) {
|
|
477
|
-
if (error?.code === "ENOENT") {
|
|
478
|
-
const state = await checkGone(target);
|
|
479
|
-
if (state === "gone") {
|
|
480
|
-
result.missing.push(target);
|
|
481
|
-
continue;
|
|
482
|
-
}
|
|
483
|
-
result.failed.push({
|
|
484
|
-
target,
|
|
485
|
-
error: describeSurvivor(target, state)
|
|
486
|
-
});
|
|
487
|
-
continue;
|
|
488
|
-
}
|
|
489
|
-
result.failed.push({
|
|
490
|
-
target,
|
|
491
|
-
error: describeRemovalError(target, error)
|
|
492
|
-
});
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
return result;
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
// src/render.ts
|
|
499
|
-
var BANNER = "SWEEP-NM";
|
|
500
|
-
var BAR_BLOCK = "▍";
|
|
501
|
-
var TOTAL_BLOCK = "█";
|
|
502
|
-
var NEUTRAL_BLOCK = "░";
|
|
503
|
-
var PLATFORM_STYLE = nativeStyle();
|
|
504
|
-
var NEUTRAL_TIER = { block: NEUTRAL_BLOCK, sgr: "2" };
|
|
505
|
-
var ROOT_LIST_LIMIT = 3;
|
|
506
|
-
var bannerLine = (suffix, color) => paint(`${BAR_BLOCK} ${BANNER} ${suffix}`, "1;7", color);
|
|
507
|
-
var neutralLine = (text, color) => ` ${paint(`${NEUTRAL_BLOCK} ${text}`, "2", color)}`;
|
|
508
|
-
var TIER_BIG = 512 * 1024 ** 2;
|
|
509
|
-
var TIER_MID = 100 * 1024 ** 2;
|
|
510
|
-
function formatBytes(bytes) {
|
|
511
|
-
if (bytes < 1024)
|
|
512
|
-
return `${Math.round(bytes)} B`;
|
|
513
|
-
const units = ["KB", "MB", "GB", "TB"];
|
|
514
|
-
let value = bytes;
|
|
515
|
-
let index = -1;
|
|
516
|
-
do {
|
|
517
|
-
value /= 1024;
|
|
518
|
-
index += 1;
|
|
519
|
-
} while (value >= 1024 && index < units.length - 1);
|
|
520
|
-
return `${Math.round(value * 10) / 10} ${units[index]}`;
|
|
521
|
-
}
|
|
522
|
-
function render(options) {
|
|
523
|
-
const { mode, roots, entries, color, home, releasedBytes, pathStyle } = options;
|
|
524
|
-
const style = pathStyle ?? PLATFORM_STYLE;
|
|
525
|
-
const scope = roots.length > 0 && roots.length <= ROOT_LIST_LIMIT ? `${roots.length} 个根: ${roots.map((root) => sanitizeLine(shortenPath(root, style, home))).join(" · ")}` : `${roots.length} 个根`;
|
|
526
|
-
const runtime = options.runtime ? ` · ${sanitizeLine(options.runtime)}` : "";
|
|
527
|
-
const head = bannerLine(`${mode === "execute" ? "执行" : "预览"} · ${scope}${runtime}`, color);
|
|
528
|
-
const notes = (options.notes ?? []).map((note) => neutralLine(sanitizeLine(note), color));
|
|
529
|
-
const trailer = (options.trailer ?? []).map((line) => neutralLine(sanitizeLine(line), color));
|
|
530
|
-
if (entries.length === 0) {
|
|
531
|
-
return [
|
|
532
|
-
head,
|
|
533
|
-
...notes,
|
|
534
|
-
` ${paint(`${NEUTRAL_BLOCK} 未发现 node_modules`, "2", color)}`,
|
|
535
|
-
...trailer
|
|
536
|
-
].join(`
|
|
537
|
-
`);
|
|
538
|
-
}
|
|
539
|
-
const rows = [...entries].sort((a, b) => (b.bytes ?? -1) - (a.bytes ?? -1));
|
|
540
|
-
const volumeWidth = Math.max(...rows.map((row) => displayWidth(volumeOf(row))));
|
|
541
|
-
const nameWidth = Math.max(...rows.map((row) => displayWidth(sanitizeLine(row.project))));
|
|
542
|
-
const body = rows.map((row) => {
|
|
543
|
-
const fail = mode === "execute" && row.ok === false;
|
|
544
|
-
const tier = row.bytes === undefined ? NEUTRAL_TIER : tierOf(row.bytes);
|
|
545
|
-
const mark = mode === "execute" ? paint(fail ? "✗" : "✓", fail ? "31" : "32", color) : paint(tier.block, tier.sgr, color);
|
|
546
|
-
const volume = padStart(volumeOf(row), volumeWidth);
|
|
547
|
-
const name = sanitizeLine(row.project);
|
|
548
|
-
const rawPath = displayPath(row.target, style, home, row.suspect === true);
|
|
549
|
-
const path = sanitizeLine(rawPath);
|
|
550
|
-
const rewritten = name !== row.project || path !== rawPath;
|
|
551
|
-
const tail = tailsOf(row, fail, rewritten);
|
|
552
|
-
const shown = `${paint(padEnd(name, nameWidth), "1", color)} ${paint(path, "2", color)}`;
|
|
553
|
-
return ` ${mark} ${volume} ${shown}${tail ? ` ${paint(tail, "2", color)}` : ""}`;
|
|
554
|
-
});
|
|
555
|
-
const hint = [
|
|
556
|
-
paint("加", "2", color),
|
|
557
|
-
paint("--yes", "1", color),
|
|
558
|
-
paint("执行删除", "2", color)
|
|
559
|
-
].join(" ");
|
|
560
|
-
const foot = mode === "execute" ? footExecute(rows, color, releasedBytes) : ` ${paint(TOTAL_BLOCK, "7", color)} ${paint(`合计 ${rows.length} 处 · ${formatBytes(sum(rows))}`, "1", color)} ${hint}`;
|
|
561
|
-
return [head, ...notes, ...body, foot, ...trailer].join(`
|
|
562
|
-
`);
|
|
563
|
-
}
|
|
564
|
-
function footExecute(rows, color, releasedBytes) {
|
|
565
|
-
const failed = rows.filter((row) => row.ok === false).length;
|
|
566
|
-
const released = releasedBytes === undefined ? "" : ` · 释放 ${formatBytes(releasedBytes)}`;
|
|
567
|
-
return ` ${paint(TOTAL_BLOCK, "7", color)} ${paint(`汇总 成功 ${rows.length - failed} 处${released} · 失败 ${failed} 处`, "1", color)}`;
|
|
568
|
-
}
|
|
569
|
-
var volumeOf = (row) => row.bytes === undefined ? "?" : formatBytes(row.bytes);
|
|
570
|
-
var SANITIZED_NOTE = "名字已净化显示";
|
|
571
|
-
function tailsOf(row, fail, rewritten) {
|
|
572
|
-
const parts = [];
|
|
573
|
-
if (rewritten)
|
|
574
|
-
parts.push(SANITIZED_NOTE);
|
|
575
|
-
if (row.note)
|
|
576
|
-
parts.push(sanitizeLine(row.note));
|
|
577
|
-
if (fail && row.error)
|
|
578
|
-
parts.push(sanitizeLine(row.error));
|
|
579
|
-
return parts.join(" ");
|
|
580
|
-
}
|
|
581
|
-
function tierOf(bytes) {
|
|
582
|
-
if (bytes >= TIER_BIG)
|
|
583
|
-
return { block: "█", sgr: "31" };
|
|
584
|
-
if (bytes >= TIER_MID)
|
|
585
|
-
return { block: "▓", sgr: "33" };
|
|
586
|
-
return { block: "▒", sgr: "36" };
|
|
587
|
-
}
|
|
588
|
-
var paint = (text, sgr, color) => color ? `\x1B[${sgr}m${text}\x1B[0m` : text;
|
|
589
|
-
var sum = (rows) => rows.reduce((total, row) => total + (row.bytes ?? 0), 0);
|
|
590
|
-
var fold3 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
|
|
591
|
-
function shortenPath(path, style, home) {
|
|
592
|
-
if (!home)
|
|
593
|
-
return path;
|
|
594
|
-
if (fold3(path, style) === fold3(home, style))
|
|
595
|
-
return "~";
|
|
596
|
-
const prefix = `${home}${style.ops.sep}`;
|
|
597
|
-
return fold3(path, style).startsWith(fold3(prefix, style)) ? `~${path.slice(home.length)}` : path;
|
|
598
|
-
}
|
|
599
|
-
function shortenHome(path, home) {
|
|
600
|
-
return shortenPath(path, PLATFORM_STYLE, home);
|
|
601
|
-
}
|
|
602
|
-
function displayPath(target, style, home, keepSuffix = false) {
|
|
603
|
-
const suffix = `${style.ops.sep}node_modules`;
|
|
604
|
-
const dir = keepSuffix || !fold3(target, style).endsWith(fold3(suffix, style)) ? target : target.slice(0, -suffix.length);
|
|
605
|
-
return shortenPath(dir, style, home);
|
|
606
|
-
}
|
|
607
|
-
var sanitizeLine = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "").replace(/\s+/g, " ").trim();
|
|
608
|
-
var sanitizeOutputLine = (text) => {
|
|
609
|
-
const indent = /^[ \t]*/.exec(text)?.[0] ?? "";
|
|
610
|
-
return `${indent}${sanitizeLine(text)}`;
|
|
611
|
-
};
|
|
612
|
-
var padEnd = (text, width) => text + " ".repeat(Math.max(0, width - displayWidth(text)));
|
|
613
|
-
var padStart = (text, width) => " ".repeat(Math.max(0, width - displayWidth(text))) + text;
|
|
614
|
-
function displayWidth(text) {
|
|
615
|
-
let width = 0;
|
|
616
|
-
for (const char of text) {
|
|
617
|
-
const code = char.codePointAt(0) ?? 0;
|
|
618
|
-
width += isFullWidth(code) ? 2 : 1;
|
|
619
|
-
}
|
|
620
|
-
return width;
|
|
621
|
-
}
|
|
622
|
-
function isFullWidth(code) {
|
|
623
|
-
return code >= 4352 && code <= 4447 || code >= 11904 && code <= 42191 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65072 && code <= 65135 || code >= 65280 && code <= 65376 || code >= 65504 && code <= 65510;
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
// src/help.ts
|
|
627
|
-
var COMMAND_COLUMN = 25;
|
|
628
|
-
function defaultConfigPath() {
|
|
629
|
-
return resolveConfigPath({ env: {} }).path;
|
|
630
|
-
}
|
|
631
|
-
function helpText(color) {
|
|
632
|
-
const row = (command, desc) => ` ${command.padEnd(COMMAND_COLUMN)} ${desc}`;
|
|
633
|
-
return [
|
|
634
|
-
bannerLine("工作区 node_modules 清理", color),
|
|
635
|
-
"",
|
|
636
|
-
row("sweep-nm", "预览: 清单 + 体积 + 合计, 零副作用"),
|
|
637
|
-
row("sweep-nm --yes", "执行删除"),
|
|
638
|
-
row("sweep-nm --force", "连同疑似安装树一并删除 (默认跳过)"),
|
|
639
|
-
row("sweep-nm --exclude <name>", "临时追加排除 (可重复, 与配置合并)"),
|
|
640
|
-
row("sweep-nm --include <name>", "只清理命中名单的目录 (可重复, 与配置合并)"),
|
|
641
|
-
row("sweep-nm --config <path>", "指定配置文件 (优先于 SWEEP_NM_CONFIG)"),
|
|
642
|
-
row("sweep-nm config", "查看实际生效的配置: 来源 + 路径 + 文件状态"),
|
|
643
|
-
row("sweep-nm init", "初始化向导: 交互生成配置文件"),
|
|
644
|
-
row("sweep-nm --help", "帮助"),
|
|
645
|
-
"",
|
|
646
|
-
"说明:",
|
|
647
|
-
" --exclude 按目录名精确匹配 (区分大小写), 从根到命中点的任意一级命中即跳过",
|
|
648
|
-
" --include 同款匹配口径, 命中才纳入; 同时命中 exclude 的照旧跳过",
|
|
649
|
-
" 配置未写 exclude 字段时使用内置默认名单 (包管理器 / 版本管理器 / 编辑器扩展等安装树目录)",
|
|
650
|
-
" --force 只放行「疑似安装树」(安装树形态的目标), 不放宽删除安全闸",
|
|
651
|
-
" 删除侧要求扫描根为真实路径 (根及其祖先链不含符号链接): 命中 (如 /tmp、/var 形态) 则 --yes 整批拒绝, 改写为真实路径形态 (如 /private/tmp/x) 即放行",
|
|
652
|
-
` 默认配置位置 (平台自适应; 用了 --config 或 SWEEP_NM_CONFIG 时实际读的不是它): ${sanitizeLine(defaultConfigPath())}`,
|
|
653
|
-
" 查实际生效的路径: sweep-nm config",
|
|
654
|
-
"",
|
|
655
|
-
"退出码: 0 成功 (含预览与空结果); 1 删除失败或跳过 / 配置损坏 / 参数错误"
|
|
656
|
-
].join(`
|
|
657
|
-
`);
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
// src/init.ts
|
|
661
|
-
import { homedir as homedir4 } from "node:os";
|
|
662
|
-
import { join as join2 } from "node:path";
|
|
663
|
-
import { createInterface } from "node:readline/promises";
|
|
664
|
-
var WHITESPACE = /\s/;
|
|
665
|
-
function expandHome(token) {
|
|
666
|
-
if (token === "~")
|
|
667
|
-
return homedir4();
|
|
668
|
-
if (token.startsWith("~/") || token.startsWith("~\\"))
|
|
669
|
-
return join2(homedir4(), token.slice(2));
|
|
670
|
-
return token;
|
|
671
|
-
}
|
|
672
|
-
function splitAnswer(answer) {
|
|
673
|
-
const items = [];
|
|
674
|
-
let current = "";
|
|
675
|
-
let openQuote = null;
|
|
676
|
-
for (let index = 0;index < answer.length; index += 1) {
|
|
677
|
-
const char = answer[index];
|
|
678
|
-
if (openQuote !== null) {
|
|
679
|
-
if (char === openQuote) {
|
|
680
|
-
openQuote = null;
|
|
681
|
-
continue;
|
|
682
|
-
}
|
|
683
|
-
current += char;
|
|
684
|
-
continue;
|
|
685
|
-
}
|
|
686
|
-
if (char === '"' || char === "'") {
|
|
687
|
-
if (answer.indexOf(char, index + 1) !== -1) {
|
|
688
|
-
openQuote = char;
|
|
689
|
-
continue;
|
|
690
|
-
}
|
|
691
|
-
current += char;
|
|
692
|
-
continue;
|
|
693
|
-
}
|
|
694
|
-
if (char === "," || char === "," || WHITESPACE.test(char)) {
|
|
695
|
-
if (current.length > 0)
|
|
696
|
-
items.push(current);
|
|
697
|
-
current = "";
|
|
698
|
-
continue;
|
|
699
|
-
}
|
|
700
|
-
current += char;
|
|
701
|
-
}
|
|
702
|
-
if (current.length > 0)
|
|
703
|
-
items.push(current);
|
|
704
|
-
return items;
|
|
705
|
-
}
|
|
706
|
-
function parseList(answer, fallback) {
|
|
707
|
-
if (answer === null)
|
|
708
|
-
return [...fallback];
|
|
709
|
-
const items = splitAnswer(answer).map(expandHome);
|
|
710
|
-
return items.length > 0 ? items : [...fallback];
|
|
711
|
-
}
|
|
712
|
-
async function runInit(deps) {
|
|
713
|
-
const {
|
|
714
|
-
configPath,
|
|
715
|
-
fileExists,
|
|
716
|
-
firstSymlinkOnRoot,
|
|
717
|
-
firstSymlinkOnTarget,
|
|
718
|
-
writeFile,
|
|
719
|
-
io
|
|
720
|
-
} = deps;
|
|
721
|
-
const { color } = io;
|
|
722
|
-
function cancelled() {
|
|
723
|
-
io.print("已取消, 未写入配置");
|
|
724
|
-
return { state: "cancelled" };
|
|
725
|
-
}
|
|
726
|
-
io.print(bannerLine("初始化向导", color));
|
|
727
|
-
if (await fileExists(configPath)) {
|
|
728
|
-
const overwrite = await io.confirm(`配置已存在 (${sanitizeLine(configPath)}), 是否覆盖?`, false);
|
|
729
|
-
if (!overwrite)
|
|
730
|
-
return { state: "declined-overwrite" };
|
|
731
|
-
}
|
|
732
|
-
io.print(neutralLine("首次使用, 先确定扫描范围", color));
|
|
733
|
-
const home = homedir4();
|
|
734
|
-
let roots = [];
|
|
735
|
-
for (;; ) {
|
|
736
|
-
const rootsAnswer = await io.ask("扫描根 (逗号或空白分隔多个)", `默认: ${sanitizeLine(shortenHome(home, home))}`);
|
|
737
|
-
if (rootsAnswer === null)
|
|
738
|
-
return cancelled();
|
|
739
|
-
roots = parseList(rootsAnswer, [home]);
|
|
740
|
-
const missing = [];
|
|
741
|
-
const symlinked = [];
|
|
742
|
-
for (const root of roots) {
|
|
743
|
-
if (!await fileExists(root)) {
|
|
744
|
-
missing.push(root);
|
|
745
|
-
continue;
|
|
746
|
-
}
|
|
747
|
-
const link = await firstSymlinkOnRoot(root);
|
|
748
|
-
if (link !== null)
|
|
749
|
-
symlinked.push({ root, link });
|
|
750
|
-
}
|
|
751
|
-
if (missing.length === 0 && symlinked.length === 0)
|
|
752
|
-
break;
|
|
753
|
-
for (const path of missing)
|
|
754
|
-
io.print(` ${paint("✗", "31", color)} 根不存在: ${sanitizeLine(path)}`);
|
|
755
|
-
for (const item of symlinked)
|
|
756
|
-
io.print(` ${paint("✗", "31", color)} 根锚点链上有符号链接: ${sanitizeLine(item.link)} (根: ${sanitizeLine(item.root)}); 删除侧要求真实路径, 改写为不含符号链接的形态 (macOS 上如 /tmp/x 写成 /private/tmp/x)`);
|
|
757
|
-
}
|
|
758
|
-
const excludeAnswer = await io.ask("排除名单 (目录名)", `回车采用默认名单 (${DEFAULT_EXCLUDE.length} 条)`);
|
|
759
|
-
if (excludeAnswer === null)
|
|
760
|
-
return cancelled();
|
|
761
|
-
const exclude = parseList(excludeAnswer, [...DEFAULT_EXCLUDE]);
|
|
762
|
-
const includeAnswer = await io.ask("包含名单 (目录名, 可留空)", "回车跳过");
|
|
763
|
-
if (includeAnswer === null)
|
|
764
|
-
return cancelled();
|
|
765
|
-
const include = parseList(includeAnswer, []);
|
|
766
|
-
io.print(neutralLine(`将写入 ${roots.length} 个扫描根 · 排除 ${exclude.length} 条 · 包含 ${include.length} 条`, color));
|
|
767
|
-
for (;; ) {
|
|
768
|
-
if (!await io.confirm("确认写入?", true))
|
|
769
|
-
return cancelled();
|
|
770
|
-
const link = await firstSymlinkOnTarget(configPath);
|
|
771
|
-
if (link === null)
|
|
772
|
-
break;
|
|
773
|
-
io.print(` ${paint("✗", "31", color)} 配置路径锚点链上有符号链接: ${sanitizeLine(link)} (配置: ${sanitizeLine(configPath)}); 写入会跟随符号链接改写其目标, 改写为不含符号链接的形态 (macOS 上如 /tmp/x 写成 /private/tmp/x)`);
|
|
774
|
-
}
|
|
775
|
-
const config = { roots, exclude, include };
|
|
776
|
-
const text = `${JSON.stringify(config, null, 2)}
|
|
777
|
-
`;
|
|
778
|
-
await writeFile(configPath, text);
|
|
779
|
-
io.print(` 配置已写入: ${sanitizeLine(shortenHome(configPath, homedir4()))} ${paint("✓", "32", color)}`);
|
|
780
|
-
io.print("");
|
|
781
|
-
io.print(text.trimEnd().split(`
|
|
782
|
-
`).map((line) => ` ${line}`).join(`
|
|
783
|
-
`));
|
|
784
|
-
io.print("");
|
|
785
|
-
return { state: "written", config };
|
|
786
|
-
}
|
|
787
|
-
function setStdinRef(shouldRef) {
|
|
788
|
-
const fn = shouldRef ? process.stdin.ref : process.stdin.unref;
|
|
789
|
-
if (typeof fn === "function")
|
|
790
|
-
fn.call(process.stdin);
|
|
791
|
-
}
|
|
792
|
-
function createReadlineIO(color) {
|
|
793
|
-
const buffered = [];
|
|
794
|
-
let rl = null;
|
|
795
|
-
let ended = false;
|
|
796
|
-
let pending = null;
|
|
797
|
-
function ensure() {
|
|
798
|
-
if (rl !== null)
|
|
799
|
-
return rl;
|
|
800
|
-
const created = createInterface({
|
|
801
|
-
input: process.stdin,
|
|
802
|
-
output: process.stdout
|
|
803
|
-
});
|
|
804
|
-
created.on("line", (line) => {
|
|
805
|
-
if (pending === null) {
|
|
806
|
-
buffered.push(line);
|
|
807
|
-
return;
|
|
808
|
-
}
|
|
809
|
-
const resolve = pending;
|
|
810
|
-
pending = null;
|
|
811
|
-
setStdinRef(false);
|
|
812
|
-
resolve(line);
|
|
813
|
-
});
|
|
814
|
-
created.on("close", () => {
|
|
815
|
-
ended = true;
|
|
816
|
-
if (pending === null)
|
|
817
|
-
return;
|
|
818
|
-
const resolve = pending;
|
|
819
|
-
pending = null;
|
|
820
|
-
setStdinRef(false);
|
|
821
|
-
resolve(null);
|
|
822
|
-
});
|
|
823
|
-
created.on("SIGINT", () => created.close());
|
|
824
|
-
rl = created;
|
|
825
|
-
return created;
|
|
826
|
-
}
|
|
827
|
-
function readLine(prompt) {
|
|
828
|
-
if (ended) {
|
|
829
|
-
const bufferedLine = buffered.shift();
|
|
830
|
-
if (bufferedLine === undefined)
|
|
831
|
-
return Promise.resolve(null);
|
|
832
|
-
process.stdout.write(prompt);
|
|
833
|
-
return Promise.resolve(bufferedLine);
|
|
834
|
-
}
|
|
835
|
-
const created = ensure();
|
|
836
|
-
created.setPrompt(prompt);
|
|
837
|
-
created.prompt();
|
|
838
|
-
const ready = buffered.shift();
|
|
839
|
-
if (ready !== undefined)
|
|
840
|
-
return Promise.resolve(ready);
|
|
841
|
-
setStdinRef(true);
|
|
842
|
-
return new Promise((resolve) => {
|
|
843
|
-
pending = resolve;
|
|
844
|
-
});
|
|
845
|
-
}
|
|
846
|
-
return {
|
|
847
|
-
color,
|
|
848
|
-
ask(question, hint) {
|
|
849
|
-
const prompt = hint === undefined ? ` ${question} ` : ` ${question} [${paint(hint, "2", color)}] `;
|
|
850
|
-
return readLine(prompt);
|
|
851
|
-
},
|
|
852
|
-
async confirm(question, defaultYes) {
|
|
853
|
-
const mark = paint(defaultYes ? "(Y/n)" : "(y/N)", "2", color);
|
|
854
|
-
const answer = await readLine(` ${question} ${mark} `);
|
|
855
|
-
if (answer === null)
|
|
856
|
-
return false;
|
|
857
|
-
const normalized = answer.trim().toLowerCase();
|
|
858
|
-
if (normalized === "")
|
|
859
|
-
return defaultYes;
|
|
860
|
-
return normalized === "y" || normalized === "yes";
|
|
861
|
-
},
|
|
862
|
-
print(line) {
|
|
863
|
-
process.stdout.write(`${line}
|
|
864
|
-
`);
|
|
865
|
-
}
|
|
866
|
-
};
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
// src/runtime.ts
|
|
870
|
-
import { readFile as readFile2, writeFile } from "node:fs/promises";
|
|
871
|
-
var isBun = typeof Bun !== "undefined";
|
|
872
|
-
var versions = process.versions;
|
|
873
|
-
var runtimeName = isBun ? "bun" : "node";
|
|
874
|
-
var runtimeLabel = `${runtimeName} ${versions[runtimeName] ?? "unknown"}`;
|
|
875
|
-
async function writeTextFile(path, text) {
|
|
876
|
-
if (isBun) {
|
|
877
|
-
await Bun.write(path, text);
|
|
878
|
-
return;
|
|
879
|
-
}
|
|
880
|
-
await writeFile(path, text, "utf8");
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
// src/scan-parallel.ts
|
|
884
|
-
import { readdir, realpath as realpath2, stat as stat2 } from "node:fs/promises";
|
|
885
|
-
import { join as join3 } from "node:path";
|
|
886
|
-
var NODE_MODULES = "node_modules";
|
|
887
|
-
var GIT_DIR = ".git";
|
|
888
|
-
var CONCURRENCY = 32;
|
|
889
|
-
function compareTarget(a, b) {
|
|
890
|
-
if (a.target < b.target)
|
|
891
|
-
return -1;
|
|
892
|
-
if (a.target > b.target)
|
|
893
|
-
return 1;
|
|
894
|
-
return 0;
|
|
895
|
-
}
|
|
896
|
-
function describeRootFailure(error) {
|
|
897
|
-
const { code } = error;
|
|
898
|
-
switch (code) {
|
|
899
|
-
case "ENOENT":
|
|
900
|
-
return "根不存在";
|
|
901
|
-
case "EACCES":
|
|
902
|
-
case "EPERM":
|
|
903
|
-
return "根不可读 (权限不足)";
|
|
904
|
-
case "ENOTDIR":
|
|
905
|
-
return "根不是目录";
|
|
906
|
-
default:
|
|
907
|
-
return `根不可用 (${code ?? "UNKNOWN"})`;
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
async function walkRoot(root, ctx) {
|
|
911
|
-
const {
|
|
912
|
-
style,
|
|
913
|
-
exclude,
|
|
914
|
-
excludeCounts,
|
|
915
|
-
include,
|
|
916
|
-
includeCounts,
|
|
917
|
-
hits,
|
|
918
|
-
warnings
|
|
919
|
-
} = ctx;
|
|
920
|
-
const stack = [{ dir: root, included: include.size === 0 }];
|
|
921
|
-
let outstanding = 1;
|
|
922
|
-
let active = 0;
|
|
923
|
-
const failures = [];
|
|
924
|
-
let resolveDrained = null;
|
|
925
|
-
const drained = new Promise((resolve) => {
|
|
926
|
-
resolveDrained = resolve;
|
|
927
|
-
});
|
|
928
|
-
function pump() {
|
|
929
|
-
while (active < CONCURRENCY && stack.length > 0) {
|
|
930
|
-
const next = stack.pop();
|
|
931
|
-
active += 1;
|
|
932
|
-
visit(next.dir, next.included);
|
|
933
|
-
}
|
|
934
|
-
if (outstanding === 0 && resolveDrained !== null) {
|
|
935
|
-
const resolve = resolveDrained;
|
|
936
|
-
resolveDrained = null;
|
|
937
|
-
resolve();
|
|
938
|
-
}
|
|
939
|
-
}
|
|
940
|
-
async function visit(dir, included) {
|
|
941
|
-
try {
|
|
942
|
-
let entries;
|
|
943
|
-
try {
|
|
944
|
-
entries = await readdir(dir, { withFileTypes: true });
|
|
945
|
-
} catch {
|
|
946
|
-
warnings.push(`目录不可读, 已跳过: ${dir}`);
|
|
947
|
-
return;
|
|
948
|
-
}
|
|
949
|
-
for (const entry of entries) {
|
|
950
|
-
if (!entry.isDirectory())
|
|
951
|
-
continue;
|
|
952
|
-
const name = entry.name;
|
|
953
|
-
if (name === NODE_MODULES) {
|
|
954
|
-
if (!included)
|
|
955
|
-
continue;
|
|
956
|
-
const target = join3(dir, name);
|
|
957
|
-
const key = dedupeKey(await realpath2(target).catch(() => target), style);
|
|
958
|
-
if (!hits.has(key))
|
|
959
|
-
hits.set(key, { project: dir, target });
|
|
960
|
-
continue;
|
|
961
|
-
}
|
|
962
|
-
if (name === GIT_DIR)
|
|
963
|
-
continue;
|
|
964
|
-
const childIncluded = included || include.has(name);
|
|
965
|
-
if (!included && include.has(name)) {
|
|
966
|
-
includeCounts.set(name, (includeCounts.get(name) ?? 0) + 1);
|
|
967
|
-
}
|
|
968
|
-
if (exclude.has(name)) {
|
|
969
|
-
excludeCounts.set(name, (excludeCounts.get(name) ?? 0) + 1);
|
|
970
|
-
continue;
|
|
971
|
-
}
|
|
972
|
-
stack.push({ dir: join3(dir, name), included: childIncluded });
|
|
973
|
-
outstanding += 1;
|
|
974
|
-
}
|
|
975
|
-
} catch (error) {
|
|
976
|
-
if (failures.length === 0)
|
|
977
|
-
failures.push(error);
|
|
978
|
-
} finally {
|
|
979
|
-
active -= 1;
|
|
980
|
-
outstanding -= 1;
|
|
981
|
-
pump();
|
|
982
|
-
}
|
|
983
|
-
}
|
|
984
|
-
pump();
|
|
985
|
-
await drained;
|
|
986
|
-
if (failures.length > 0)
|
|
987
|
-
throw failures[0];
|
|
988
|
-
}
|
|
989
|
-
function createParallelScanner() {
|
|
990
|
-
return {
|
|
991
|
-
name: "parallel",
|
|
992
|
-
async scan(options) {
|
|
993
|
-
const warnings = [];
|
|
994
|
-
const exclude = new Set(options.exclude);
|
|
995
|
-
const excludeCounts = new Map;
|
|
996
|
-
for (const name of options.exclude) {
|
|
997
|
-
if (!excludeCounts.has(name))
|
|
998
|
-
excludeCounts.set(name, 0);
|
|
999
|
-
}
|
|
1000
|
-
const include = new Set(options.include);
|
|
1001
|
-
const includeCounts = new Map;
|
|
1002
|
-
for (const name of options.include) {
|
|
1003
|
-
if (!includeCounts.has(name))
|
|
1004
|
-
includeCounts.set(name, 0);
|
|
1005
|
-
}
|
|
1006
|
-
const hitsByRealTarget = new Map;
|
|
1007
|
-
const style = nativeStyle();
|
|
1008
|
-
const seenRoots = new Set;
|
|
1009
|
-
const roots = [];
|
|
1010
|
-
for (const root of options.roots) {
|
|
1011
|
-
let key;
|
|
1012
|
-
try {
|
|
1013
|
-
const resolved = await realpath2(root);
|
|
1014
|
-
if (!(await stat2(resolved)).isDirectory()) {
|
|
1015
|
-
warnings.push(`根不是目录, 已跳过: ${root}`);
|
|
1016
|
-
continue;
|
|
1017
|
-
}
|
|
1018
|
-
key = dedupeKey(resolved, style);
|
|
1019
|
-
} catch (error) {
|
|
1020
|
-
warnings.push(`${describeRootFailure(error)}, 已跳过: ${root}`);
|
|
1021
|
-
continue;
|
|
1022
|
-
}
|
|
1023
|
-
if (seenRoots.has(key))
|
|
1024
|
-
continue;
|
|
1025
|
-
seenRoots.add(key);
|
|
1026
|
-
roots.push(root);
|
|
1027
|
-
}
|
|
1028
|
-
const context = {
|
|
1029
|
-
style,
|
|
1030
|
-
exclude,
|
|
1031
|
-
excludeCounts,
|
|
1032
|
-
include,
|
|
1033
|
-
includeCounts,
|
|
1034
|
-
hits: hitsByRealTarget,
|
|
1035
|
-
warnings
|
|
1036
|
-
};
|
|
1037
|
-
for (const root of roots) {
|
|
1038
|
-
await walkRoot(root, context);
|
|
1039
|
-
}
|
|
1040
|
-
const hits = [...hitsByRealTarget.values()].sort(compareTarget);
|
|
1041
|
-
const excludeMatches = options.exclude.map((name) => ({
|
|
1042
|
-
name,
|
|
1043
|
-
hits: excludeCounts.get(name) ?? 0
|
|
1044
|
-
}));
|
|
1045
|
-
const includeMatches = options.include.map((name) => ({
|
|
1046
|
-
name,
|
|
1047
|
-
hits: includeCounts.get(name) ?? 0
|
|
1048
|
-
}));
|
|
1049
|
-
return { hits, warnings, excludeMatches, includeMatches };
|
|
1050
|
-
}
|
|
1051
|
-
};
|
|
1052
|
-
}
|
|
1053
|
-
// src/size-du.ts
|
|
1054
|
-
import { spawn } from "node:child_process";
|
|
1055
|
-
import { accessSync, constants } from "node:fs";
|
|
1056
|
-
var DU_PROBES = ["/usr/bin/du", "/bin/du"];
|
|
1057
|
-
var hasControlChar = (target) => target.includes(`
|
|
1058
|
-
`) || target.includes("\r");
|
|
1059
|
-
function findDu(platform = process.platform) {
|
|
1060
|
-
if (platform === "win32")
|
|
1061
|
-
return null;
|
|
1062
|
-
for (const probe of DU_PROBES) {
|
|
1063
|
-
try {
|
|
1064
|
-
accessSync(probe, constants.X_OK);
|
|
1065
|
-
return probe;
|
|
1066
|
-
} catch {}
|
|
1067
|
-
}
|
|
1068
|
-
return null;
|
|
1069
|
-
}
|
|
1070
|
-
function runDu(bin, targets) {
|
|
1071
|
-
return new Promise((resolve) => {
|
|
1072
|
-
const child = spawn(bin, ["-sk", "--", ...targets], {
|
|
1073
|
-
stdio: ["ignore", "pipe", "pipe"]
|
|
1074
|
-
});
|
|
1075
|
-
let stdout = "";
|
|
1076
|
-
let stderr = "";
|
|
1077
|
-
child.stdout.on("data", (chunk) => {
|
|
1078
|
-
stdout += chunk;
|
|
1079
|
-
});
|
|
1080
|
-
child.stderr.on("data", (chunk) => {
|
|
1081
|
-
stderr += chunk;
|
|
1082
|
-
});
|
|
1083
|
-
child.on("error", (error) => {
|
|
1084
|
-
resolve({ stdout, stderr: `${stderr}${String(error)}` });
|
|
1085
|
-
});
|
|
1086
|
-
child.on("close", () => resolve({ stdout, stderr }));
|
|
1087
|
-
});
|
|
1088
|
-
}
|
|
1089
|
-
function parseDuSizes(stdout) {
|
|
1090
|
-
const sizes = new Map;
|
|
1091
|
-
let duplicated = false;
|
|
1092
|
-
for (const line of stdout.split(`
|
|
1093
|
-
`)) {
|
|
1094
|
-
const match = /^(\d+)\t(.+)$/.exec(line);
|
|
1095
|
-
if (match === null)
|
|
1096
|
-
continue;
|
|
1097
|
-
const sizeKiB = match[1];
|
|
1098
|
-
const path = match[2];
|
|
1099
|
-
if (sizeKiB === undefined || path === undefined)
|
|
1100
|
-
continue;
|
|
1101
|
-
if (sizes.has(path))
|
|
1102
|
-
duplicated = true;
|
|
1103
|
-
sizes.set(path, Number(sizeKiB) * 1024);
|
|
1104
|
-
}
|
|
1105
|
-
return { sizes, duplicated };
|
|
1106
|
-
}
|
|
1107
|
-
function assessDuOutput(stdout, safeTargets) {
|
|
1108
|
-
const safeSet = new Set(safeTargets);
|
|
1109
|
-
const parsed = parseDuSizes(stdout);
|
|
1110
|
-
let unexpected = false;
|
|
1111
|
-
for (const path of parsed.sizes.keys()) {
|
|
1112
|
-
if (!safeSet.has(path))
|
|
1113
|
-
unexpected = true;
|
|
1114
|
-
}
|
|
1115
|
-
const intact = !parsed.duplicated && parsed.sizes.size <= safeTargets.length && !unexpected;
|
|
1116
|
-
return {
|
|
1117
|
-
sizes: parsed.sizes,
|
|
1118
|
-
intact,
|
|
1119
|
-
duplicated: parsed.duplicated,
|
|
1120
|
-
unexpected
|
|
1121
|
-
};
|
|
1122
|
-
}
|
|
1123
|
-
function describeAnomaly(assessment) {
|
|
1124
|
-
const shapes = [];
|
|
1125
|
-
if (assessment.duplicated)
|
|
1126
|
-
shapes.push("同一路径多行");
|
|
1127
|
-
if (assessment.unexpected)
|
|
1128
|
-
shapes.push("含输入之外的路径");
|
|
1129
|
-
if (shapes.length === 0)
|
|
1130
|
-
shapes.push("行数与输入不符");
|
|
1131
|
-
return shapes.join(" / ");
|
|
1132
|
-
}
|
|
1133
|
-
function describeDuFailure(detail) {
|
|
1134
|
-
if (/no such file or directory/i.test(detail))
|
|
1135
|
-
return { reason: "不存在", missing: true };
|
|
1136
|
-
if (/permission denied/i.test(detail))
|
|
1137
|
-
return { reason: "权限不足, 无法读取", missing: false };
|
|
1138
|
-
if (/not a directory/i.test(detail))
|
|
1139
|
-
return { reason: "不是目录", missing: false };
|
|
1140
|
-
if (/too many levels of symbolic links/i.test(detail)) {
|
|
1141
|
-
return { reason: "符号链接层级过深", missing: false };
|
|
1142
|
-
}
|
|
1143
|
-
return { reason: `读取失败 (${detail})`, missing: false };
|
|
1144
|
-
}
|
|
1145
|
-
function parseDuErrorLine(line) {
|
|
1146
|
-
const match = /^du:\s+(.+):\s+(.+)$/.exec(line);
|
|
1147
|
-
if (match === null)
|
|
1148
|
-
return null;
|
|
1149
|
-
const path = match[1];
|
|
1150
|
-
const detail = match[2];
|
|
1151
|
-
if (path === undefined || detail === undefined)
|
|
1152
|
-
return null;
|
|
1153
|
-
return { path, detail };
|
|
1154
|
-
}
|
|
1155
|
-
function createDuSizer(bin = findDu()) {
|
|
1156
|
-
return {
|
|
1157
|
-
name: "du",
|
|
1158
|
-
async measure(targets) {
|
|
1159
|
-
if (bin === null) {
|
|
1160
|
-
return {
|
|
1161
|
-
entries: [],
|
|
1162
|
-
warnings: [
|
|
1163
|
-
"du 候选不可用: /usr/bin/du 与 /bin/du 均不存在, 本候选跳过体积统计"
|
|
1164
|
-
],
|
|
1165
|
-
unmeasured: []
|
|
1166
|
-
};
|
|
1167
|
-
}
|
|
1168
|
-
if (targets.length === 0) {
|
|
1169
|
-
return { entries: [], warnings: [], unmeasured: [] };
|
|
1170
|
-
}
|
|
1171
|
-
const sorted = [...targets].sort();
|
|
1172
|
-
const warnings = [];
|
|
1173
|
-
const entries = [];
|
|
1174
|
-
const unmeasured = [];
|
|
1175
|
-
const safeTargets = sorted.filter((target) => !hasControlChar(target));
|
|
1176
|
-
const safeSet = new Set(safeTargets);
|
|
1177
|
-
const sizes = new Map;
|
|
1178
|
-
const failures = new Map;
|
|
1179
|
-
let intact = true;
|
|
1180
|
-
if (safeTargets.length > 0) {
|
|
1181
|
-
const { stdout, stderr } = await runDu(bin, safeTargets);
|
|
1182
|
-
const assessment = assessDuOutput(stdout, safeTargets);
|
|
1183
|
-
intact = assessment.intact;
|
|
1184
|
-
if (!intact) {
|
|
1185
|
-
warnings.push(`du 输出与输入集合不符 (${describeAnomaly(assessment)}): 本批 ${safeTargets.length} 个目标的体积均未采信`);
|
|
1186
|
-
}
|
|
1187
|
-
for (const [path, bytes] of assessment.sizes)
|
|
1188
|
-
sizes.set(path, bytes);
|
|
1189
|
-
for (const line of stderr.split(`
|
|
1190
|
-
`)) {
|
|
1191
|
-
if (line.trim() === "")
|
|
1192
|
-
continue;
|
|
1193
|
-
const errorLine = parseDuErrorLine(line);
|
|
1194
|
-
if (errorLine === null) {
|
|
1195
|
-
warnings.push(`体积统计失败 (未归因): ${line.trim()}`);
|
|
1196
|
-
continue;
|
|
1197
|
-
}
|
|
1198
|
-
const failure = describeDuFailure(errorLine.detail);
|
|
1199
|
-
if (!safeSet.has(errorLine.path)) {
|
|
1200
|
-
warnings.push(`体积统计失败 (${failure.reason}): ${errorLine.path}`);
|
|
1201
|
-
continue;
|
|
1202
|
-
}
|
|
1203
|
-
failures.set(errorLine.path, failure);
|
|
1204
|
-
}
|
|
1205
|
-
}
|
|
1206
|
-
for (const target of sorted) {
|
|
1207
|
-
if (hasControlChar(target)) {
|
|
1208
|
-
unmeasured.push({ target, reason: "路径含控制字符" });
|
|
1209
|
-
continue;
|
|
1210
|
-
}
|
|
1211
|
-
if (!intact) {
|
|
1212
|
-
unmeasured.push({ target, reason: "输出不可解析" });
|
|
1213
|
-
continue;
|
|
1214
|
-
}
|
|
1215
|
-
const bytes = sizes.get(target);
|
|
1216
|
-
if (bytes !== undefined) {
|
|
1217
|
-
entries.push({ target, bytes });
|
|
1218
|
-
continue;
|
|
1219
|
-
}
|
|
1220
|
-
const failure = failures.get(target);
|
|
1221
|
-
if (failure === undefined) {
|
|
1222
|
-
unmeasured.push({ target, reason: "输出不可解析" });
|
|
1223
|
-
continue;
|
|
1224
|
-
}
|
|
1225
|
-
if (failure.missing) {
|
|
1226
|
-
warnings.push(`体积统计失败 (不存在): ${target}`);
|
|
1227
|
-
continue;
|
|
1228
|
-
}
|
|
1229
|
-
unmeasured.push({ target, reason: failure.reason });
|
|
1230
|
-
}
|
|
1231
|
-
return { entries, warnings, unmeasured };
|
|
1232
|
-
}
|
|
1233
|
-
};
|
|
1234
|
-
}
|
|
1235
|
-
|
|
1236
|
-
// src/size-js.ts
|
|
1237
|
-
import { readdir as readdir2, stat as stat3 } from "node:fs/promises";
|
|
1238
|
-
import { join as join4 } from "node:path";
|
|
1239
|
-
function describeFailure(code) {
|
|
1240
|
-
switch (code) {
|
|
1241
|
-
case "ENOENT":
|
|
1242
|
-
return "不存在";
|
|
1243
|
-
case "EACCES":
|
|
1244
|
-
case "EPERM":
|
|
1245
|
-
return "权限不足, 无法读取";
|
|
1246
|
-
case "ENOTDIR":
|
|
1247
|
-
return "不是目录";
|
|
1248
|
-
case "ELOOP":
|
|
1249
|
-
return "符号链接层级过深";
|
|
1250
|
-
default:
|
|
1251
|
-
return code === undefined ? "读取失败" : `读取失败 (${code})`;
|
|
1252
|
-
}
|
|
1253
|
-
}
|
|
1254
|
-
function errorCode(error) {
|
|
1255
|
-
return error?.code;
|
|
1256
|
-
}
|
|
1257
|
-
async function sumEntries(dirents, dir, warnings) {
|
|
1258
|
-
let total = 0;
|
|
1259
|
-
for (const dirent of dirents) {
|
|
1260
|
-
if (dirent.isSymbolicLink())
|
|
1261
|
-
continue;
|
|
1262
|
-
const path = join4(dir, dirent.name);
|
|
1263
|
-
if (dirent.isDirectory()) {
|
|
1264
|
-
try {
|
|
1265
|
-
total += await sumEntries(await readdir2(path, { withFileTypes: true }), path, warnings);
|
|
1266
|
-
} catch (error) {
|
|
1267
|
-
warnings.push(`体积统计失败 (${describeFailure(errorCode(error))}): ${path}`);
|
|
1268
|
-
}
|
|
1269
|
-
} else if (dirent.isFile()) {
|
|
1270
|
-
try {
|
|
1271
|
-
total += (await stat3(path)).size;
|
|
1272
|
-
} catch (error) {
|
|
1273
|
-
warnings.push(`体积统计失败 (${describeFailure(errorCode(error))}): ${path}`);
|
|
1274
|
-
}
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
return total;
|
|
1278
|
-
}
|
|
1279
|
-
function createJsSizer() {
|
|
1280
|
-
return {
|
|
1281
|
-
name: "js",
|
|
1282
|
-
async measure(targets) {
|
|
1283
|
-
const warnings = [];
|
|
1284
|
-
const entries = [];
|
|
1285
|
-
const unmeasured = [];
|
|
1286
|
-
for (const target of [...targets].sort()) {
|
|
1287
|
-
let dirents;
|
|
1288
|
-
try {
|
|
1289
|
-
dirents = await readdir2(target, { withFileTypes: true });
|
|
1290
|
-
} catch (error) {
|
|
1291
|
-
const code = errorCode(error);
|
|
1292
|
-
if (code === "ENOENT") {
|
|
1293
|
-
warnings.push(`体积统计失败 (不存在): ${target}`);
|
|
1294
|
-
} else {
|
|
1295
|
-
unmeasured.push({ target, reason: describeFailure(code) });
|
|
1296
|
-
}
|
|
1297
|
-
continue;
|
|
1298
|
-
}
|
|
1299
|
-
entries.push({
|
|
1300
|
-
target,
|
|
1301
|
-
bytes: await sumEntries(dirents, target, warnings)
|
|
1302
|
-
});
|
|
1303
|
-
}
|
|
1304
|
-
return { entries, warnings, unmeasured };
|
|
1305
|
-
}
|
|
1306
|
-
};
|
|
1307
|
-
}
|
|
1308
|
-
|
|
1309
|
-
// src/size.ts
|
|
1310
|
-
function createSizer() {
|
|
1311
|
-
return findDu() !== null ? createDuSizer() : createJsSizer();
|
|
1312
|
-
}
|
|
1313
|
-
|
|
1314
|
-
// src/skip.ts
|
|
1315
|
-
var SUSPECT_HINT = "已跳过 (加 --force 一并清理)";
|
|
1316
|
-
var CROSS_DEVICE_NOTES = {
|
|
1317
|
-
"on-path": "跨设备: 根与目标之间有挂载点",
|
|
1318
|
-
"target-itself": "跨设备: 目标本体即挂载点"
|
|
1319
|
-
};
|
|
1320
|
-
var CROSS_DEVICE_HINTS = {
|
|
1321
|
-
"on-path": "已跳过 (把该挂载点声明为独立根即可清理)",
|
|
1322
|
-
"target-itself": "已跳过 (挂载点无法删除, 需先卸载该卷)"
|
|
1323
|
-
};
|
|
1324
|
-
var CROSS_DEVICE_TRAILER_ACTIONS = {
|
|
1325
|
-
"on-path": "把根与目标之间的挂载点声明为独立根即可清理",
|
|
1326
|
-
"target-itself": "目标本体即挂载点, 需先卸载该卷"
|
|
1327
|
-
};
|
|
1328
|
-
function crossDeviceNote(kind) {
|
|
1329
|
-
return CROSS_DEVICE_NOTES[kind];
|
|
1330
|
-
}
|
|
1331
|
-
function skipsBatch(entry, crossDevice, force) {
|
|
1332
|
-
if (crossDevice.has(entry.target))
|
|
1333
|
-
return true;
|
|
1334
|
-
return entry.suspect === true && !force;
|
|
1335
|
-
}
|
|
1336
|
-
function deletionBatch(entries, crossDevice, force) {
|
|
1337
|
-
return entries.filter((entry) => entry.bytes !== undefined && !skipsBatch(entry, crossDevice, force)).map((entry) => entry.target);
|
|
1338
|
-
}
|
|
1339
|
-
function collectSkips(entries, crossDevice, force) {
|
|
1340
|
-
const suspectSkipped = force ? [] : entries.filter((entry) => entry.suspect === true);
|
|
1341
|
-
const deviceSkipped = entries.filter((entry) => crossDevice.has(entry.target));
|
|
1342
|
-
const trailer = [
|
|
1343
|
-
...suspectSkipped.length > 0 ? [`疑似安装树 ${suspectSkipped.length} 处默认跳过 (加 --force 一并清理)`] : [],
|
|
1344
|
-
...["on-path", "target-itself"].flatMap((kind) => {
|
|
1345
|
-
const count = deviceSkipped.filter((entry) => crossDevice.get(entry.target) === kind).length;
|
|
1346
|
-
return count === 0 ? [] : [
|
|
1347
|
-
`跨设备目标 ${count} 处默认跳过 (${CROSS_DEVICE_TRAILER_ACTIONS[kind]})`
|
|
1348
|
-
];
|
|
1349
|
-
})
|
|
1350
|
-
];
|
|
1351
|
-
const hints = new Map;
|
|
1352
|
-
for (const entry of suspectSkipped) {
|
|
1353
|
-
if (entry.bytes !== undefined)
|
|
1354
|
-
hints.set(entry.target, SUSPECT_HINT);
|
|
1355
|
-
}
|
|
1356
|
-
for (const entry of deviceSkipped) {
|
|
1357
|
-
const kind = crossDevice.get(entry.target);
|
|
1358
|
-
if (entry.bytes !== undefined && kind !== undefined) {
|
|
1359
|
-
hints.set(entry.target, CROSS_DEVICE_HINTS[kind]);
|
|
1360
|
-
}
|
|
1361
|
-
}
|
|
1362
|
-
return { trailer, hints };
|
|
1363
|
-
}
|
|
1364
|
-
|
|
1365
|
-
// src/cli.ts
|
|
1366
|
-
function parseArgs(argv) {
|
|
1367
|
-
const options = {
|
|
1368
|
-
command: "sweep",
|
|
1369
|
-
yes: false,
|
|
1370
|
-
force: false,
|
|
1371
|
-
exclude: [],
|
|
1372
|
-
include: [],
|
|
1373
|
-
help: false
|
|
1374
|
-
};
|
|
1375
|
-
const positionals = [];
|
|
1376
|
-
for (let index = 0;index < argv.length; index += 1) {
|
|
1377
|
-
const arg = argv[index];
|
|
1378
|
-
if (arg === undefined)
|
|
1379
|
-
continue;
|
|
1380
|
-
if (arg === "--yes") {
|
|
1381
|
-
options.yes = true;
|
|
1382
|
-
continue;
|
|
1383
|
-
}
|
|
1384
|
-
if (arg === "--force") {
|
|
1385
|
-
options.force = true;
|
|
1386
|
-
continue;
|
|
1387
|
-
}
|
|
1388
|
-
if (arg === "--help" || arg === "-h") {
|
|
1389
|
-
options.help = true;
|
|
1390
|
-
continue;
|
|
1391
|
-
}
|
|
1392
|
-
if (arg === "--exclude" || arg === "--include" || arg === "--config") {
|
|
1393
|
-
const value = argv[index + 1];
|
|
1394
|
-
if (value === undefined || value.startsWith("-")) {
|
|
1395
|
-
return { ok: false, message: `参数 ${arg} 缺少取值` };
|
|
1396
|
-
}
|
|
1397
|
-
if (arg === "--exclude")
|
|
1398
|
-
options.exclude.push(value);
|
|
1399
|
-
else if (arg === "--include")
|
|
1400
|
-
options.include.push(value);
|
|
1401
|
-
else
|
|
1402
|
-
options.config = value;
|
|
1403
|
-
index += 1;
|
|
1404
|
-
continue;
|
|
1405
|
-
}
|
|
1406
|
-
if (arg.startsWith("-"))
|
|
1407
|
-
return { ok: false, message: `未知参数: ${arg}` };
|
|
1408
|
-
positionals.push(arg);
|
|
1409
|
-
}
|
|
1410
|
-
const [only] = positionals;
|
|
1411
|
-
if (positionals.length > 1 || only !== undefined && only !== "init" && only !== "config") {
|
|
1412
|
-
return { ok: false, message: `未知参数: ${positionals.join(" ")}` };
|
|
1413
|
-
}
|
|
1414
|
-
if (only === "init" || only === "config")
|
|
1415
|
-
options.command = only;
|
|
1416
|
-
return { ok: true, options };
|
|
1417
|
-
}
|
|
1418
|
-
function colorEnabled() {
|
|
1419
|
-
return process.stdout.isTTY === true && !process.env.NO_COLOR;
|
|
1420
|
-
}
|
|
1421
|
-
function interactive() {
|
|
1422
|
-
return process.stdin.isTTY === true && process.stdout.isTTY === true;
|
|
1423
|
-
}
|
|
1424
|
-
function print(line) {
|
|
1425
|
-
process.stdout.write(`${line}
|
|
1426
|
-
`);
|
|
1427
|
-
}
|
|
1428
|
-
function warn(line, color) {
|
|
1429
|
-
const text = sanitizeOutputLine(line);
|
|
1430
|
-
process.stderr.write(color ? `${paint("✗", "31", color)} ${text}
|
|
1431
|
-
` : `${text}
|
|
1432
|
-
`);
|
|
1433
|
-
}
|
|
1434
|
-
function notice(line) {
|
|
1435
|
-
process.stderr.write(`${sanitizeOutputLine(line)}
|
|
1436
|
-
`);
|
|
1437
|
-
}
|
|
1438
|
-
async function fileExists(path) {
|
|
1439
|
-
try {
|
|
1440
|
-
await lstat3(path);
|
|
1441
|
-
return true;
|
|
1442
|
-
} catch {
|
|
1443
|
-
return false;
|
|
1444
|
-
}
|
|
1445
|
-
}
|
|
1446
|
-
function runWizard(configPath, color) {
|
|
1447
|
-
return runInit({
|
|
1448
|
-
configPath,
|
|
1449
|
-
fileExists,
|
|
1450
|
-
firstSymlinkOnRoot,
|
|
1451
|
-
firstSymlinkOnTarget,
|
|
1452
|
-
async writeFile(path, text) {
|
|
1453
|
-
await mkdir(dirname(path), { recursive: true });
|
|
1454
|
-
await writeTextFile(path, text);
|
|
1455
|
-
},
|
|
1456
|
-
io: createReadlineIO(color)
|
|
1457
|
-
});
|
|
1458
|
-
}
|
|
1459
|
-
var SOURCE_LABELS = {
|
|
1460
|
-
flag: "--config 指定",
|
|
1461
|
-
env: "环境变量 SWEEP_NM_CONFIG",
|
|
1462
|
-
"platform-default": "平台默认"
|
|
1463
|
-
};
|
|
1464
|
-
async function reportConfig(resolved, color) {
|
|
1465
|
-
const exists = await fileExists(resolved.path);
|
|
1466
|
-
print(bannerLine(`配置 · 来源: ${SOURCE_LABELS[resolved.source]}`, color));
|
|
1467
|
-
print(neutralLine(`配置路径: ${sanitizeLine(resolved.path)}`, color));
|
|
1468
|
-
print(neutralLine(`文件状态: ${exists ? "存在" : "不存在"}`, color));
|
|
1469
|
-
return 0;
|
|
1470
|
-
}
|
|
1471
|
-
async function resolveConfig(resolved, color) {
|
|
1472
|
-
const loaded = await loadResolvedConfig(resolved);
|
|
1473
|
-
if (loaded.state === "ok")
|
|
1474
|
-
return { config: loaded.config, source: "file" };
|
|
1475
|
-
if (!interactive())
|
|
1476
|
-
return {
|
|
1477
|
-
config: {
|
|
1478
|
-
roots: [process.cwd()],
|
|
1479
|
-
exclude: [...DEFAULT_EXCLUDE],
|
|
1480
|
-
include: []
|
|
1481
|
-
},
|
|
1482
|
-
source: "fallback"
|
|
1483
|
-
};
|
|
1484
|
-
const result = await runWizard(resolved.path, color);
|
|
1485
|
-
if (result.state === "written" && result.config !== undefined) {
|
|
1486
|
-
return { config: result.config, source: "wizard" };
|
|
1487
|
-
}
|
|
1488
|
-
print("配置未写入, 本次未执行清理");
|
|
1489
|
-
return null;
|
|
1490
|
-
}
|
|
1491
|
-
var ABORTED_HINT = "整批中止, 未执行删除";
|
|
1492
|
-
async function trustRoots(roots) {
|
|
1493
|
-
return Promise.all(roots.map(async (root) => ({
|
|
1494
|
-
configured: root,
|
|
1495
|
-
real: await realpath3(root).catch(() => null) ?? root
|
|
1496
|
-
})));
|
|
1497
|
-
}
|
|
1498
|
-
function withOutcomes(entries, batch, accepted, removal, skipped) {
|
|
1499
|
-
const outcomes = new Map;
|
|
1500
|
-
for (const target of removal.removed)
|
|
1501
|
-
outcomes.set(target, { ok: true });
|
|
1502
|
-
for (const target of removal.missing)
|
|
1503
|
-
outcomes.set(target, { ok: true });
|
|
1504
|
-
for (const item of removal.failed)
|
|
1505
|
-
outcomes.set(item.target, { ok: false, error: item.error });
|
|
1506
|
-
const byTarget = new Map;
|
|
1507
|
-
for (const [index, target] of batch.entries()) {
|
|
1508
|
-
const real = accepted[index];
|
|
1509
|
-
const outcome = real === undefined ? undefined : outcomes.get(real);
|
|
1510
|
-
if (outcome !== undefined)
|
|
1511
|
-
byTarget.set(target, outcome);
|
|
1512
|
-
}
|
|
1513
|
-
const fallbackOf = (entry) => {
|
|
1514
|
-
if (removal.aborted !== undefined)
|
|
1515
|
-
return { ok: false, error: ABORTED_HINT };
|
|
1516
|
-
const hint = skipped.get(entry.target);
|
|
1517
|
-
if (hint !== undefined)
|
|
1518
|
-
return { ok: false, error: hint };
|
|
1519
|
-
return { ok: false };
|
|
1520
|
-
};
|
|
1521
|
-
return entries.map((entry) => ({
|
|
1522
|
-
...entry,
|
|
1523
|
-
...byTarget.get(entry.target) ?? fallbackOf(entry)
|
|
1524
|
-
}));
|
|
1525
|
-
}
|
|
1526
|
-
var BUILTIN_EXCLUDE_NAMES = new Set(DEFAULT_EXCLUDE);
|
|
1527
|
-
function collectNameNotes(excludeMatches, includeMatches, color) {
|
|
1528
|
-
const notes = [];
|
|
1529
|
-
const tty = process.stdout.isTTY === true;
|
|
1530
|
-
for (const item of excludeMatches ?? []) {
|
|
1531
|
-
if (item.hits === 0) {
|
|
1532
|
-
if (BUILTIN_EXCLUDE_NAMES.has(item.name))
|
|
1533
|
-
continue;
|
|
1534
|
-
warn(`排除名未命中任何已扫描的目录: ${item.name} (按目录名精确匹配; 若其上层目录已被排除则属预期)`, color);
|
|
1535
|
-
} else if (tty)
|
|
1536
|
-
notes.push(`排除生效: ${item.name} (${item.hits} 处)`);
|
|
1537
|
-
}
|
|
1538
|
-
const includes = includeMatches ?? [];
|
|
1539
|
-
for (const item of includes) {
|
|
1540
|
-
if (item.hits === 0)
|
|
1541
|
-
warn(`包含名未命中任何已扫描的目录: ${item.name} (按目录名精确匹配; 若其上层目录已被排除则属预期)`, color);
|
|
1542
|
-
else if (tty)
|
|
1543
|
-
notes.push(`包含命中: ${item.name} (${item.hits} 处)`);
|
|
1544
|
-
}
|
|
1545
|
-
if (includes.length > 0 && includes.every((item) => item.hits === 0))
|
|
1546
|
-
warn("包含名单无一条命中, 本次扫描必为空结果 (请核对名字与大小写; 若名字位于被排除的目录之下则属预期)", color);
|
|
1547
|
-
return notes;
|
|
1548
|
-
}
|
|
1549
|
-
function toEntries(hits, sizeResult, home, crossDevice) {
|
|
1550
|
-
const bytesOf = new Map(sizeResult.entries.map((entry) => [
|
|
1551
|
-
entry.target,
|
|
1552
|
-
entry.bytes
|
|
1553
|
-
]));
|
|
1554
|
-
const reasonOf = new Map(sizeResult.unmeasured.map((item) => [
|
|
1555
|
-
item.target,
|
|
1556
|
-
item.reason
|
|
1557
|
-
]));
|
|
1558
|
-
const entries = [];
|
|
1559
|
-
for (const hit of hits) {
|
|
1560
|
-
const project = basename(hit.project);
|
|
1561
|
-
const classification = classifyTarget(hit.target, { home });
|
|
1562
|
-
const suspect = classification.kind === "suspect-install-tree";
|
|
1563
|
-
const notes = [];
|
|
1564
|
-
if (suspect)
|
|
1565
|
-
notes.push(`疑似安装树: ${classification.reason}`);
|
|
1566
|
-
const deviceKind = crossDevice.get(hit.target);
|
|
1567
|
-
if (deviceKind !== undefined)
|
|
1568
|
-
notes.push(crossDeviceNote(deviceKind));
|
|
1569
|
-
const note = notes.length > 0 ? notes.join(" ") : undefined;
|
|
1570
|
-
const bytes = bytesOf.get(hit.target);
|
|
1571
|
-
if (bytes !== undefined) {
|
|
1572
|
-
entries.push({ project, target: hit.target, bytes, suspect, note });
|
|
1573
|
-
continue;
|
|
1574
|
-
}
|
|
1575
|
-
const reason = reasonOf.get(hit.target);
|
|
1576
|
-
if (reason !== undefined) {
|
|
1577
|
-
entries.push({
|
|
1578
|
-
project,
|
|
1579
|
-
target: hit.target,
|
|
1580
|
-
suspect,
|
|
1581
|
-
note: note === undefined ? `体积统计失败: ${reason}` : `${note} 体积统计失败: ${reason}`
|
|
1582
|
-
});
|
|
1583
|
-
}
|
|
1584
|
-
}
|
|
1585
|
-
return entries;
|
|
1586
|
-
}
|
|
1587
|
-
async function sweep(config, options, color) {
|
|
1588
|
-
const roots = config.roots;
|
|
1589
|
-
const exclude = mergeNames(config.exclude, options.exclude);
|
|
1590
|
-
const include = mergeNames(config.include, options.include);
|
|
1591
|
-
const scanResult = await createParallelScanner().scan({ roots, exclude, include });
|
|
1592
|
-
for (const warning of scanResult.warnings)
|
|
1593
|
-
warn(warning, color);
|
|
1594
|
-
const nameNotes = collectNameNotes(scanResult.excludeMatches, scanResult.includeMatches, color);
|
|
1595
|
-
const tty = process.stdout.isTTY === true;
|
|
1596
|
-
const runtime = tty ? runtimeLabel : undefined;
|
|
1597
|
-
const sizeResult = await createSizer().measure(scanResult.hits.map((hit) => hit.target));
|
|
1598
|
-
for (const warning of sizeResult.warnings)
|
|
1599
|
-
warn(warning, color);
|
|
1600
|
-
const home = homedir5();
|
|
1601
|
-
const crossDevice = await findCrossDeviceTargets(scanResult.hits.map((hit) => hit.target), { roots });
|
|
1602
|
-
const entries = toEntries(scanResult.hits, sizeResult, home, crossDevice);
|
|
1603
|
-
const { trailer, hints: skippedHints } = collectSkips(entries, crossDevice, options.force);
|
|
1604
|
-
if (!options.yes) {
|
|
1605
|
-
print(render({
|
|
1606
|
-
mode: "preview",
|
|
1607
|
-
roots,
|
|
1608
|
-
entries,
|
|
1609
|
-
color,
|
|
1610
|
-
home,
|
|
1611
|
-
notes: nameNotes,
|
|
1612
|
-
runtime,
|
|
1613
|
-
trailer
|
|
1614
|
-
}));
|
|
1615
|
-
return 0;
|
|
1616
|
-
}
|
|
1617
|
-
const batch = deletionBatch(entries, crossDevice, options.force);
|
|
1618
|
-
const { accepted, rejected } = await validateTargets(batch, { roots });
|
|
1619
|
-
if (rejected.length > 0) {
|
|
1620
|
-
warn(`整批拒绝: ${rejected.length} 个目标未通过安全闸, 未执行任何删除`, color);
|
|
1621
|
-
for (const item of rejected)
|
|
1622
|
-
notice(` ${item.target} (${item.reason})`);
|
|
1623
|
-
return 1;
|
|
1624
|
-
}
|
|
1625
|
-
const removal = await removeTargets(accepted, {
|
|
1626
|
-
roots: await trustRoots(roots)
|
|
1627
|
-
});
|
|
1628
|
-
const report = withOutcomes(entries, batch, accepted, removal, skippedHints);
|
|
1629
|
-
const releasedBytes = report.reduce((total, entry) => entry.ok === false ? total : total + (entry.bytes ?? 0), 0);
|
|
1630
|
-
print(render({
|
|
1631
|
-
mode: "execute",
|
|
1632
|
-
roots,
|
|
1633
|
-
entries: report,
|
|
1634
|
-
color,
|
|
1635
|
-
home,
|
|
1636
|
-
releasedBytes,
|
|
1637
|
-
notes: nameNotes,
|
|
1638
|
-
runtime,
|
|
1639
|
-
trailer
|
|
1640
|
-
}));
|
|
1641
|
-
if (removal.aborted !== undefined) {
|
|
1642
|
-
warn(`整批中止: ${removal.aborted.reason}`, color);
|
|
1643
|
-
notice(` 本轮未执行删除: ${batch.length} 处`);
|
|
1644
|
-
}
|
|
1645
|
-
return report.some((entry) => entry.ok === false) ? 1 : 0;
|
|
1646
|
-
}
|
|
1647
|
-
async function main() {
|
|
1648
|
-
const color = colorEnabled();
|
|
1649
|
-
const parsed = parseArgs(process.argv.slice(2));
|
|
1650
|
-
if (!parsed.ok) {
|
|
1651
|
-
warn(`参数错误: ${parsed.message} (用 --help 查看用法)`, color);
|
|
1652
|
-
return 1;
|
|
1653
|
-
}
|
|
1654
|
-
const { options } = parsed;
|
|
1655
|
-
if (options.help) {
|
|
1656
|
-
print(helpText(color));
|
|
1657
|
-
return 0;
|
|
1658
|
-
}
|
|
1659
|
-
try {
|
|
1660
|
-
const resolvedPath = resolveConfigPath({ flag: options.config });
|
|
1661
|
-
if (options.command === "init") {
|
|
1662
|
-
if (!interactive()) {
|
|
1663
|
-
warn("init 需要交互终端 (请在终端直接运行, 不要重定向或经管道)", color);
|
|
1664
|
-
return 1;
|
|
1665
|
-
}
|
|
1666
|
-
const result = await runWizard(resolvedPath.path, color);
|
|
1667
|
-
if (result.state === "written")
|
|
1668
|
-
print(neutralLine("运行 sweep-nm 查看预览", color));
|
|
1669
|
-
else
|
|
1670
|
-
print("配置未变更");
|
|
1671
|
-
return 0;
|
|
1672
|
-
}
|
|
1673
|
-
if (options.command === "config") {
|
|
1674
|
-
return await reportConfig(resolvedPath, color);
|
|
1675
|
-
}
|
|
1676
|
-
const resolved = await resolveConfig(resolvedPath, color);
|
|
1677
|
-
if (resolved === null)
|
|
1678
|
-
return 0;
|
|
1679
|
-
if (resolved.source === "fallback") {
|
|
1680
|
-
const roots = resolved.config.roots.join(", ");
|
|
1681
|
-
if (options.yes) {
|
|
1682
|
-
warn("拒绝执行: 当前无配置文件, --yes 不可用", color);
|
|
1683
|
-
notice(` 将扫的根: ${roots}`);
|
|
1684
|
-
notice(" 先 sweep-nm init 生成配置, 或用 --config 指定配置文件");
|
|
1685
|
-
return 1;
|
|
1686
|
-
}
|
|
1687
|
-
notice(`未找到配置文件, 本次以当前目录为根: ${roots} (想固定此设置, 运行 sweep-nm init)`);
|
|
1688
|
-
}
|
|
1689
|
-
const freshConfig = resolved.source === "wizard";
|
|
1690
|
-
if (freshConfig && options.yes) {
|
|
1691
|
-
notice("首次配置已生成; 本轮先预览, 复核后可再运行 --yes 执行");
|
|
1692
|
-
}
|
|
1693
|
-
return await sweep(resolved.config, freshConfig ? { ...options, yes: false } : options, color);
|
|
1694
|
-
} catch (error) {
|
|
1695
|
-
warn(error instanceof Error ? error.message : String(error), color);
|
|
1696
|
-
return 1;
|
|
1697
|
-
}
|
|
1698
|
-
}
|
|
1699
|
-
process.exitCode = await main();
|