@iyowei/sweep-node-modules 0.1.0 → 0.3.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/README.md CHANGED
@@ -6,29 +6,72 @@
6
6
 
7
7
  ## 要求
8
8
 
9
- - 运行时二选一: **bun 或 node** 皆可 (双运行时, 装任一即可用)。
10
- - 取最新一代运行时 API: bun 任意近期版本; node 需原生支持 TypeScript 直跑的版本 (版本快照与实测记录见 [ADR 0006](docs/adrs/0006-dual-runtime-bun-first.md))。
9
+ - 业务逻辑**双运行时**: 有 bun 走 bun, 否则 node (功能一致, bun 启动更快)。
10
+ - 取最新一代运行时 API: bun 任意近期版本; node 需原生支持 TypeScript 直跑的版本 (源码方式与包方式取同一版本下限; 版本快照与实测记录见 [ADR 0006](docs/adrs/0006-dual-runtime-bun-first.md))。
11
11
  - 零第三方运行时依赖 (只用运行时内置能力)。
12
12
  - 平台: Windows / macOS / Linux 三平台均可运行 (见 [ADR 0007](docs/adrs/0007-platform-portability.md))。
13
13
 
14
14
  ## 安装
15
15
 
16
- **npm** (推荐):
16
+ 三种方式, 按你机器上已有的运行时挑。**每条下的「需要」是硬门槛**:
17
+
18
+ > **机器上只有 bun、没装 node?** 直接走 ① 或 ③; ② 的全局安装 (npm 与 bun 皆然) 都需要 node。
19
+
20
+ ### ① 免安装 (试用或偶尔用)
21
+
22
+ ```shell
23
+ # 机器上有 bun
24
+ bunx @iyowei/sweep-node-modules
25
+
26
+ # 机器上有 node (npx 随 npm 一同安装, 本身就需要 node)
27
+ npx @iyowei/sweep-node-modules
28
+ ```
29
+
30
+ - **需要**: bun 或 node, 与所选命令对应
31
+ - 特点: 零安装; 每次运行会解析一次包
32
+ - 注意: `bunx` 与 `npx` 各自依附一个运行时, 不是可互换的通用选项: 只有 bun 的机器没有 `npx`, 只有 node 的机器没有 `bunx`
33
+
34
+ ### ② 包管理器全局安装 (常用推荐)
17
35
 
18
36
  ```shell
19
37
  npm install -g @iyowei/sweep-node-modules
38
+ bun install -g @iyowei/sweep-node-modules
20
39
  ```
21
40
 
22
- **从源码**:
41
+ - **需要**: **node** (两条命令都要)。npm 本身跑在 node 上; `bun install -g` 生成的是指向入口文件的符号链接, 执行时由系统内核读该文件的 shebang (node) 来决定解释器, 应用层插不上手
42
+ - 特点: 装一次后直接敲 `sweep-nm`; 有 bun 时业务逻辑仍优先走 bun
43
+
44
+ ### ③ 从源码 (开发, 或无 node 环境)
45
+
46
+ **macOS / Linux**:
23
47
 
24
48
  ```shell
49
+ # 克隆后进入仓库根 (路径按你的实际位置调整)
50
+ cd "<克隆位置>/sweep-node-modules"
51
+
25
52
  chmod +x bin/sweep-nm
26
53
 
27
- # 软链进 ~/.local/bin, 启动器会挑选运行时 (Bun 优先, Node 回退)
28
- ln -sf "$HOME/self/development/sweep-node-modules/bin/sweep-nm" ~/.local/bin/sweep-nm
54
+ # 软链进 ~/.local/bin (通常已在 PATH 中), 启动器会挑选运行时
55
+ ln -sf "$PWD/bin/sweep-nm" ~/.local/bin/sweep-nm
29
56
  ```
30
57
 
31
- > 两种方式都支持 Bun / Node 双运行时 (装任一即可用); 从源码安装的 Windows 用户入口为 `bin\sweep-nm.cmd`。
58
+ **Windows** (PowerShell):
59
+
60
+ ```powershell
61
+ # 把仓库的 bin 目录加入用户 PATH, 只需一次, 重开终端后生效
62
+ # 路径按你的实际克隆位置调整 (启动器靠自身位置定位 src, 故不能把脚本单独复制走)
63
+ $bin = "$env:USERPROFILE\tools\sweep-node-modules\bin"
64
+ [Environment]::SetEnvironmentVariable(
65
+ 'Path',
66
+ [Environment]::GetEnvironmentVariable('Path', 'User') + ";$bin",
67
+ 'User'
68
+ )
69
+ ```
70
+
71
+ > 也可以不经命令行: 在「系统属性 → 环境变量」里把该 `bin` 目录加到用户变量 `Path` 中。
72
+
73
+ - **需要**: bun 或 node 任一 (启动器是 shell / cmd 脚本, 由系统执行, 不依赖 node)
74
+ - 特点: 入口最直接; 之后直接敲 `sweep-nm` (Windows 经 `bin\sweep-nm.cmd`)
32
75
 
33
76
  ## 使用
34
77
 
@@ -42,13 +85,21 @@ sweep-nm --yes
42
85
  # 临时追加排除(可重复)
43
86
  sweep-nm --exclude my-kits --exclude url-tool
44
87
 
88
+ # 只清理名单命中的目录(可重复, 与配置合并)
89
+ sweep-nm --include my-kits
90
+
91
+ # 查看实际生效的配置文件位置与状态 (来源 / 路径 / 是否存在)
92
+ sweep-nm config
93
+
45
94
  # 初始化向导: 交互式生成配置文件
46
95
  sweep-nm init
47
96
  ```
48
97
 
98
+ 清单顶栏尾部会标注本次实际使用的运行时 (如 `bun 1.4.2`), 仅交互终端显示 (非 TTY 不增噪音)。
99
+
49
100
  ## 配置
50
101
 
51
- 配置文件位置 (平台自适应): Windows 为 `%APPDATA%\sweep-node-modules\config.json`, 其余为 `~/.config/sweep-node-modules/config.json`; 可用 `--config` 或环境变量 `SWEEP_NM_CONFIG` 覆盖。
102
+ 配置文件位置 (平台自适应): Windows 为 `%APPDATA%\sweep-node-modules\config.json`, 其余为 `~/.config/sweep-node-modules/config.json`; 可用 `--config` 或环境变量 `SWEEP_NM_CONFIG` 覆盖, 本次实际生效的路径与文件状态用 `sweep-nm config` 查看。
52
103
 
53
104
  ```json
54
105
  {
@@ -56,32 +107,22 @@ sweep-nm init
56
107
  "/Users/iyowei/workspace/development",
57
108
  "/Users/iyowei/self/development"
58
109
  ],
59
- "exclude": ["my-kits"]
110
+ "exclude": ["my-kits"],
111
+ "include": []
60
112
  }
61
113
  ```
62
114
 
63
115
  - `roots`: 扫描根目录, 任意多个; 重复或嵌套的根按真实路径去重。
64
116
  - `exclude`: 排除名单; 从根到 `node_modules` 的任意一级目录名命中即跳过 (多排除 = 少删, 安全方向)。
65
- - 首次运行且无配置: 交互终端下自动进入初始化向导; 非交互环境 (脚本等) 以当前工作目录为根并提示, 不询问; 随时可用 `sweep-nm init` 重进向导。
117
+ - `include`: 包含名单 (白名单); 命中才纳入, 口径与 `exclude` 同款; 缺省或空数组 = 不过滤 (多包含 = 多删); 与 `exclude` 同时命中时 `exclude` 优先。写错名字会让结果直接为空, 故未命中的名字会在 stderr 警示。
118
+ - 两份名单里的 `node_modules` 与 `.git` 一律被剔除: 前者是本工具的目标 (列入排除等于排掉唯一目标, 列入包含则永久零命中), 后者是扫描恒定跳过的目录; 剔除后 `include` 为空数组 = 不过滤 (不是「只扫 node_modules」)。
119
+ - 首次运行且无配置: 交互终端下自动进入初始化向导 (扫描根默认家目录); 非交互环境 (脚本等) 以当前工作目录为根并提示, 不询问; 随时可用 `sweep-nm init` 重进向导。
66
120
 
67
121
  > 字段定义以[设计文档](docs/designs/config-and-initialization.md)为准。
68
122
 
69
123
  ## 开发
70
124
 
71
- ```shell
72
- bun install # 安装 devDependencies, 并自动装好 git 钩子 (lefthook)
73
-
74
- bun run typecheck # tsc --noEmit
75
- bun run lint # oxlint
76
- bun run format # prettier --write
77
- bun test # bun test (243 条: 契约 / 鲁棒 / 压测 / 双载体 e2e / 伪终端冒烟)
78
- bun run bench # 基准四组 (扫描 / 体积 / 真实工作区 / 压测)
79
- bun run conformance -- --target "bun src/cli.ts" # 转写一致性验收 (40 条金样本, 见 docs/protocol/)
80
- ```
81
-
82
- 运行时双跑验证: `bun src/cli.ts` 与 `node src/cli.ts` 均可直接运行。
83
-
84
- 提交与推送由 lefthook 把关: pre-commit 增量 (prettier 重暂存 + oxlint + 全量类型检查), pre-push 全量只读 (typecheck / test / oxlint / prettier `--check`)。
125
+ 环境准备、常用命令、双运行时验证与提交钩子, 见 [开发指南](docs/development.md)。
85
126
 
86
127
  ## 文档
87
128
 
package/bin/sweep-nm.mjs CHANGED
@@ -1,7 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
3
  * npm 安装场景的启动器: 挑选运行时 (Bun 优先, 其次 Node) 后启动真实入口。
4
- * 与 bin/sweep-nm (sh) / bin/sweep-nm.cmd (cmd) 同逻辑, 三者的差异只在宿主:
4
+ * 与 bin/sweep-nm (sh) / bin/sweep-nm.cmd (cmd) 职责同逻辑 (挑选运行时: Bun 优先, Node 回退),
5
+ * 差异在宿主与本文件多加的入口选择 (优先跑编译产物 dist/cli.js, 无产物则回退源码 src/cli.ts;
6
+ * 包内只有产物, 开发态通常无产物):
5
7
  * 本文件同时承担 Unix 与 Windows 的 npm shim 目标 (shebang 必须是 node, 否则
6
8
  * npm 的 cmd-shim 会按 shebang 解释器生成 Windows 上不存在的调用)。
7
9
  * 退出码原样透传; 两个运行时都缺席时给出可操作提示并非零退出。
package/dist/cli.js CHANGED
@@ -60,7 +60,10 @@ function shapeError(value) {
60
60
  const rootsError = fieldError(candidate, "roots", false);
61
61
  if (rootsError !== null)
62
62
  return rootsError;
63
- return fieldError(candidate, "exclude", true);
63
+ const excludeError = fieldError(candidate, "exclude", true);
64
+ if (excludeError !== null)
65
+ return excludeError;
66
+ return fieldError(candidate, "include", true);
64
67
  }
65
68
  async function loadConfig(path) {
66
69
  let text;
@@ -84,7 +87,11 @@ async function loadConfig(path) {
84
87
  const raw = data;
85
88
  return {
86
89
  state: "ok",
87
- config: { roots: raw.roots, exclude: raw.exclude ?? [] }
90
+ config: {
91
+ roots: raw.roots,
92
+ exclude: raw.exclude ?? [],
93
+ include: raw.include ?? []
94
+ }
88
95
  };
89
96
  }
90
97
  async function loadResolvedConfig(resolved) {
@@ -94,8 +101,8 @@ async function loadResolvedConfig(resolved) {
94
101
  }
95
102
  return result;
96
103
  }
97
- function mergeExcludes(configExclude, cliExclude) {
98
- return [...new Set([...configExclude, ...cliExclude])];
104
+ function mergeNames(configNames, cliNames) {
105
+ return [...new Set([...configNames, ...cliNames])].filter((name) => name !== "node_modules" && name !== ".git");
99
106
  }
100
107
 
101
108
  // src/delete.ts
@@ -308,6 +315,128 @@ async function validateTargets(targets, options) {
308
315
  import { homedir as homedir3 } from "node:os";
309
316
  import { join as join2 } from "node:path";
310
317
  import { createInterface } from "node:readline/promises";
318
+
319
+ // src/render.ts
320
+ var BANNER = "SWEEP-NM";
321
+ var BAR_BLOCK = "▍";
322
+ var TOTAL_BLOCK = "█";
323
+ var NEUTRAL_BLOCK = "░";
324
+ var PLATFORM_STYLE = nativeStyle();
325
+ var NEUTRAL_TIER = { block: NEUTRAL_BLOCK, sgr: "2" };
326
+ var ROOT_LIST_LIMIT = 3;
327
+ var TIER_BIG = 1024 ** 3;
328
+ var TIER_MID = 100 * 1024 ** 2;
329
+ function formatBytes(bytes) {
330
+ if (bytes < 1024)
331
+ return `${Math.round(bytes)} B`;
332
+ const units = ["KB", "MB", "GB", "TB"];
333
+ let value = bytes;
334
+ let index = -1;
335
+ do {
336
+ value /= 1024;
337
+ index += 1;
338
+ } while (value >= 1024 && index < units.length - 1);
339
+ return `${Math.round(value * 10) / 10} ${units[index]}`;
340
+ }
341
+ function render(options) {
342
+ const { mode, roots, entries, color, home, releasedBytes, pathStyle } = options;
343
+ const style = pathStyle ?? PLATFORM_STYLE;
344
+ const scope = roots.length > 0 && roots.length <= ROOT_LIST_LIMIT ? `${roots.length} 个根: ${roots.map((root) => oneLine(shortenPath(root, style, home))).join(" · ")}` : `${roots.length} 个根`;
345
+ const runtime = options.runtime ? ` · ${oneLine(options.runtime)}` : "";
346
+ const head = paint(`${BAR_BLOCK} ${BANNER} ${mode === "execute" ? "执行" : "预览"} · ${scope}${runtime}`, "1;7", color);
347
+ const notes = (options.notes ?? []).map((note) => ` ${paint(`${NEUTRAL_BLOCK} ${oneLine(note)}`, "2", color)}`);
348
+ if (entries.length === 0) {
349
+ return [
350
+ head,
351
+ ...notes,
352
+ ` ${paint(`${NEUTRAL_BLOCK} 未发现 node_modules`, "2", color)}`
353
+ ].join(`
354
+ `);
355
+ }
356
+ const rows = [...entries].sort((a, b) => (b.bytes ?? -1) - (a.bytes ?? -1));
357
+ const volumeWidth = Math.max(...rows.map((row) => displayWidth(volumeOf(row))));
358
+ const nameWidth = Math.max(...rows.map((row) => displayWidth(oneLine(row.project))));
359
+ const body = rows.map((row) => {
360
+ const fail = mode === "execute" && row.ok === false;
361
+ const tier = row.bytes === undefined ? NEUTRAL_TIER : tierOf(row.bytes);
362
+ const mark = mode === "execute" ? paint(fail ? "✗" : "✓", fail ? "31" : "32", color) : paint(tier.block, tier.sgr, color);
363
+ const volume = padStart(volumeOf(row), volumeWidth);
364
+ const name = oneLine(row.project);
365
+ const rawPath = displayPath(row.target, style, home);
366
+ const path = oneLine(rawPath);
367
+ const rewritten = name !== row.project || path !== rawPath;
368
+ const tail = tailsOf(row, fail, rewritten);
369
+ const shown = `${paint(padEnd(name, nameWidth), "1", color)} ${paint(path, "2", color)}`;
370
+ return ` ${mark} ${volume} ${shown}${tail ? ` ${paint(tail, "2", color)}` : ""}`;
371
+ });
372
+ const hint = [
373
+ paint("加", "2", color),
374
+ paint("--yes", "1", color),
375
+ paint("执行删除", "2", color)
376
+ ].join(" ");
377
+ const foot = mode === "execute" ? footExecute(rows, color, releasedBytes) : ` ${paint(TOTAL_BLOCK, "7", color)} ${paint(`合计 ${rows.length} 处 · ${formatBytes(sum(rows))}`, "1", color)} ${hint}`;
378
+ return [head, ...notes, ...body, foot].join(`
379
+ `);
380
+ }
381
+ function footExecute(rows, color, releasedBytes) {
382
+ const failed = rows.filter((row) => row.ok === false).length;
383
+ const released = releasedBytes === undefined ? "" : ` · 释放 ${formatBytes(releasedBytes)}`;
384
+ return ` ${paint(TOTAL_BLOCK, "7", color)} ${paint(`汇总 成功 ${rows.length - failed} 处${released} · 失败 ${failed} 处`, "1", color)}`;
385
+ }
386
+ var volumeOf = (row) => row.bytes === undefined ? "?" : formatBytes(row.bytes);
387
+ var SANITIZED_NOTE = "名字已净化显示";
388
+ function tailsOf(row, fail, rewritten) {
389
+ const parts = [];
390
+ if (rewritten)
391
+ parts.push(SANITIZED_NOTE);
392
+ if (row.note)
393
+ parts.push(oneLine(row.note));
394
+ if (fail && row.error)
395
+ parts.push(oneLine(row.error));
396
+ return parts.join(" ");
397
+ }
398
+ function tierOf(bytes) {
399
+ if (bytes >= TIER_BIG)
400
+ return { block: "█", sgr: "31" };
401
+ if (bytes >= TIER_MID)
402
+ return { block: "▓", sgr: "33" };
403
+ return { block: "▒", sgr: "36" };
404
+ }
405
+ var paint = (text, sgr, color) => color ? `\x1B[${sgr}m${text}\x1B[0m` : text;
406
+ var sum = (rows) => rows.reduce((total, row) => total + (row.bytes ?? 0), 0);
407
+ var fold2 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
408
+ function shortenPath(path, style, home) {
409
+ if (!home)
410
+ return path;
411
+ if (fold2(path, style) === fold2(home, style))
412
+ return "~";
413
+ const prefix = `${home}${style.ops.sep}`;
414
+ return fold2(path, style).startsWith(fold2(prefix, style)) ? `~${path.slice(home.length)}` : path;
415
+ }
416
+ function shortenHome(path, home) {
417
+ return shortenPath(path, PLATFORM_STYLE, home);
418
+ }
419
+ function displayPath(target, style, home) {
420
+ const suffix = `${style.ops.sep}node_modules`;
421
+ const dir = fold2(target, style).endsWith(fold2(suffix, style)) ? target.slice(0, -suffix.length) : target;
422
+ return shortenPath(dir, style, home);
423
+ }
424
+ var oneLine = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "").replace(/\s+/g, " ").trim();
425
+ var padEnd = (text, width) => text + " ".repeat(Math.max(0, width - displayWidth(text)));
426
+ var padStart = (text, width) => " ".repeat(Math.max(0, width - displayWidth(text))) + text;
427
+ function displayWidth(text) {
428
+ let width = 0;
429
+ for (const char of text) {
430
+ const code = char.codePointAt(0) ?? 0;
431
+ width += isFullWidth(code) ? 2 : 1;
432
+ }
433
+ return width;
434
+ }
435
+ function isFullWidth(code) {
436
+ 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;
437
+ }
438
+
439
+ // src/init.ts
311
440
  var WHITESPACE = /\s/;
312
441
  function expandHome(token) {
313
442
  if (token === "~")
@@ -368,13 +497,13 @@ async function runInit(deps) {
368
497
  return { state: "declined-overwrite" };
369
498
  }
370
499
  io.print("首次使用, 先确定扫描范围");
371
- const cwd = process.cwd();
500
+ const home = homedir3();
372
501
  let roots = [];
373
502
  for (;; ) {
374
- const rootsAnswer = await io.ask("扫描根 (逗号或空白分隔多个)", `默认: ${cwd}`);
503
+ const rootsAnswer = await io.ask("扫描根 (逗号或空白分隔多个)", `默认: ${home}`);
375
504
  if (rootsAnswer === null)
376
505
  return cancelled();
377
- roots = parseList(rootsAnswer, [cwd]);
506
+ roots = parseList(rootsAnswer, [home]);
378
507
  const missing = [];
379
508
  for (const root of roots) {
380
509
  if (!await fileExists(root))
@@ -392,10 +521,14 @@ async function runInit(deps) {
392
521
  io.print(`将写入 roots: ${JSON.stringify(roots)} · exclude: ${JSON.stringify(exclude)}`);
393
522
  if (!await io.confirm("确认写入?", true))
394
523
  return cancelled();
395
- const config = { roots, exclude };
396
- await writeFile(configPath, `${JSON.stringify(config, null, 2)}
397
- `);
398
- io.print(`配置已写入: ${configPath}`);
524
+ const config = { roots, exclude, include: [] };
525
+ const text = `${JSON.stringify(config, null, 2)}
526
+ `;
527
+ await writeFile(configPath, text);
528
+ io.print(`配置已写入: ${shortenHome(configPath, homedir3())}`);
529
+ io.print("");
530
+ io.print(text.trimEnd());
531
+ io.print("");
399
532
  return { state: "written", config };
400
533
  }
401
534
  function setStdinRef(shouldRef) {
@@ -474,123 +607,12 @@ function createReadlineIO() {
474
607
  };
475
608
  }
476
609
 
477
- // src/render.ts
478
- var BANNER = "SWEEP-NM";
479
- var BAR_BLOCK = "▍";
480
- var TOTAL_BLOCK = "█";
481
- var NEUTRAL_BLOCK = "░";
482
- var PLATFORM_STYLE = nativeStyle();
483
- var NEUTRAL_TIER = { block: NEUTRAL_BLOCK, sgr: "2" };
484
- var ROOT_LIST_LIMIT = 3;
485
- var TIER_BIG = 1024 ** 3;
486
- var TIER_MID = 100 * 1024 ** 2;
487
- function formatBytes(bytes) {
488
- if (bytes < 1024)
489
- return `${Math.round(bytes)} B`;
490
- const units = ["KB", "MB", "GB", "TB"];
491
- let value = bytes;
492
- let index = -1;
493
- do {
494
- value /= 1024;
495
- index += 1;
496
- } while (value >= 1024 && index < units.length - 1);
497
- return `${Math.round(value * 10) / 10} ${units[index]}`;
498
- }
499
- function render(options) {
500
- const { mode, roots, entries, color, home, releasedBytes, pathStyle } = options;
501
- const style = pathStyle ?? PLATFORM_STYLE;
502
- const scope = roots.length > 0 && roots.length <= ROOT_LIST_LIMIT ? `${roots.length} 个根: ${roots.map((root) => oneLine(shortenPath(root, style, home))).join(" · ")}` : `${roots.length} 个根`;
503
- const head = paint(`${BAR_BLOCK} ${BANNER} ${mode === "execute" ? "执行" : "预览"} · ${scope}`, "1;7", color);
504
- if (entries.length === 0) {
505
- return [
506
- head,
507
- ` ${paint(`${NEUTRAL_BLOCK} 未发现 node_modules`, "2", color)}`
508
- ].join(`
509
- `);
510
- }
511
- const rows = [...entries].sort((a, b) => (b.bytes ?? -1) - (a.bytes ?? -1));
512
- const volumeWidth = Math.max(...rows.map((row) => displayWidth(volumeOf(row))));
513
- const nameWidth = Math.max(...rows.map((row) => displayWidth(oneLine(row.project))));
514
- const body = rows.map((row) => {
515
- const fail = mode === "execute" && row.ok === false;
516
- const tier = row.bytes === undefined ? NEUTRAL_TIER : tierOf(row.bytes);
517
- const mark = mode === "execute" ? paint(fail ? "✗" : "✓", fail ? "31" : "32", color) : paint(tier.block, tier.sgr, color);
518
- const volume = padStart(volumeOf(row), volumeWidth);
519
- const name = oneLine(row.project);
520
- const rawPath = displayPath(row.target, style, home);
521
- const path = oneLine(rawPath);
522
- const rewritten = name !== row.project || path !== rawPath;
523
- const tail = tailsOf(row, fail, rewritten);
524
- const shown = `${paint(padEnd(name, nameWidth), "1", color)} ${paint(path, "2", color)}`;
525
- return ` ${mark} ${volume} ${shown}${tail ? ` ${paint(tail, "2", color)}` : ""}`;
526
- });
527
- const hint = [
528
- paint("加", "2", color),
529
- paint("--yes", "1", color),
530
- paint("执行删除", "2", color)
531
- ].join(" ");
532
- const foot = mode === "execute" ? footExecute(rows, color, releasedBytes) : ` ${paint(TOTAL_BLOCK, "7", color)} ${paint(`合计 ${rows.length} 处 · ${formatBytes(sum(rows))}`, "1", color)} ${hint}`;
533
- return [head, ...body, foot].join(`
534
- `);
535
- }
536
- function footExecute(rows, color, releasedBytes) {
537
- const failed = rows.filter((row) => row.ok === false).length;
538
- const released = releasedBytes === undefined ? "" : ` · 释放 ${formatBytes(releasedBytes)}`;
539
- return ` ${paint(TOTAL_BLOCK, "7", color)} ${paint(`汇总 成功 ${rows.length - failed} 处${released} · 失败 ${failed} 处`, "1", color)}`;
540
- }
541
- var volumeOf = (row) => row.bytes === undefined ? "?" : formatBytes(row.bytes);
542
- var SANITIZED_NOTE = "名字已净化显示";
543
- function tailsOf(row, fail, rewritten) {
544
- const parts = [];
545
- if (rewritten)
546
- parts.push(SANITIZED_NOTE);
547
- if (row.note)
548
- parts.push(oneLine(row.note));
549
- if (fail && row.error)
550
- parts.push(oneLine(row.error));
551
- return parts.join(" ");
552
- }
553
- function tierOf(bytes) {
554
- if (bytes >= TIER_BIG)
555
- return { block: "█", sgr: "31" };
556
- if (bytes >= TIER_MID)
557
- return { block: "▓", sgr: "33" };
558
- return { block: "▒", sgr: "36" };
559
- }
560
- var paint = (text, sgr, color) => color ? `\x1B[${sgr}m${text}\x1B[0m` : text;
561
- var sum = (rows) => rows.reduce((total, row) => total + (row.bytes ?? 0), 0);
562
- var fold2 = (text, style) => style.caseInsensitive ? text.toLowerCase() : text;
563
- function shortenPath(path, style, home) {
564
- if (!home)
565
- return path;
566
- if (fold2(path, style) === fold2(home, style))
567
- return "~";
568
- const prefix = `${home}${style.ops.sep}`;
569
- return fold2(path, style).startsWith(fold2(prefix, style)) ? `~${path.slice(home.length)}` : path;
570
- }
571
- function displayPath(target, style, home) {
572
- const suffix = `${style.ops.sep}node_modules`;
573
- const dir = fold2(target, style).endsWith(fold2(suffix, style)) ? target.slice(0, -suffix.length) : target;
574
- return shortenPath(dir, style, home);
575
- }
576
- var oneLine = (text) => text.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "").replace(/\s+/g, " ").trim();
577
- var padEnd = (text, width) => text + " ".repeat(Math.max(0, width - displayWidth(text)));
578
- var padStart = (text, width) => " ".repeat(Math.max(0, width - displayWidth(text))) + text;
579
- function displayWidth(text) {
580
- let width = 0;
581
- for (const char of text) {
582
- const code = char.codePointAt(0) ?? 0;
583
- width += isFullWidth(code) ? 2 : 1;
584
- }
585
- return width;
586
- }
587
- function isFullWidth(code) {
588
- 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;
589
- }
590
-
591
610
  // src/runtime.ts
592
611
  import { readFile as readFile2, writeFile } from "node:fs/promises";
593
612
  var isBun = typeof Bun !== "undefined";
613
+ var versions = process.versions;
614
+ var runtimeName = isBun ? "bun" : "node";
615
+ var runtimeLabel = `${runtimeName} ${versions[runtimeName] ?? "unknown"}`;
594
616
  async function writeTextFile(path, text) {
595
617
  if (isBun) {
596
618
  await Bun.write(path, text);
@@ -626,8 +648,17 @@ function describeRootFailure(error) {
626
648
  return `根不可用 (${code ?? "UNKNOWN"})`;
627
649
  }
628
650
  }
629
- async function walkRoot(root, style, exclude, excludeCounts, hits, warnings) {
630
- const stack = [root];
651
+ async function walkRoot(root, ctx) {
652
+ const {
653
+ style,
654
+ exclude,
655
+ excludeCounts,
656
+ include,
657
+ includeCounts,
658
+ hits,
659
+ warnings
660
+ } = ctx;
661
+ const stack = [{ dir: root, included: include.size === 0 }];
631
662
  let outstanding = 1;
632
663
  let active = 0;
633
664
  const failures = [];
@@ -637,9 +668,9 @@ async function walkRoot(root, style, exclude, excludeCounts, hits, warnings) {
637
668
  });
638
669
  function pump() {
639
670
  while (active < CONCURRENCY && stack.length > 0) {
640
- const dir = stack.pop();
671
+ const next = stack.pop();
641
672
  active += 1;
642
- visit(dir);
673
+ visit(next.dir, next.included);
643
674
  }
644
675
  if (outstanding === 0 && resolveDrained !== null) {
645
676
  const resolve = resolveDrained;
@@ -647,7 +678,7 @@ async function walkRoot(root, style, exclude, excludeCounts, hits, warnings) {
647
678
  resolve();
648
679
  }
649
680
  }
650
- async function visit(dir) {
681
+ async function visit(dir, included) {
651
682
  try {
652
683
  let entries;
653
684
  try {
@@ -661,6 +692,8 @@ async function walkRoot(root, style, exclude, excludeCounts, hits, warnings) {
661
692
  continue;
662
693
  const name = entry.name;
663
694
  if (name === NODE_MODULES) {
695
+ if (!included)
696
+ continue;
664
697
  const target = join3(dir, name);
665
698
  const key = dedupeKey(await realpath2(target).catch(() => target), style);
666
699
  if (!hits.has(key))
@@ -669,11 +702,15 @@ async function walkRoot(root, style, exclude, excludeCounts, hits, warnings) {
669
702
  }
670
703
  if (name === GIT_DIR)
671
704
  continue;
705
+ const childIncluded = included || include.has(name);
706
+ if (!included && include.has(name)) {
707
+ includeCounts.set(name, (includeCounts.get(name) ?? 0) + 1);
708
+ }
672
709
  if (exclude.has(name)) {
673
710
  excludeCounts.set(name, (excludeCounts.get(name) ?? 0) + 1);
674
711
  continue;
675
712
  }
676
- stack.push(join3(dir, name));
713
+ stack.push({ dir: join3(dir, name), included: childIncluded });
677
714
  outstanding += 1;
678
715
  }
679
716
  } catch (error) {
@@ -701,6 +738,12 @@ function createParallelScanner() {
701
738
  if (!excludeCounts.has(name))
702
739
  excludeCounts.set(name, 0);
703
740
  }
741
+ const include = new Set(options.include);
742
+ const includeCounts = new Map;
743
+ for (const name of options.include) {
744
+ if (!includeCounts.has(name))
745
+ includeCounts.set(name, 0);
746
+ }
704
747
  const hitsByRealTarget = new Map;
705
748
  const style = nativeStyle();
706
749
  const seenRoots = new Set;
@@ -723,15 +766,28 @@ function createParallelScanner() {
723
766
  seenRoots.add(key);
724
767
  roots.push(root);
725
768
  }
769
+ const context = {
770
+ style,
771
+ exclude,
772
+ excludeCounts,
773
+ include,
774
+ includeCounts,
775
+ hits: hitsByRealTarget,
776
+ warnings
777
+ };
726
778
  for (const root of roots) {
727
- await walkRoot(root, style, exclude, excludeCounts, hitsByRealTarget, warnings);
779
+ await walkRoot(root, context);
728
780
  }
729
781
  const hits = [...hitsByRealTarget.values()].sort(compareTarget);
730
782
  const excludeMatches = options.exclude.map((name) => ({
731
783
  name,
732
784
  hits: excludeCounts.get(name) ?? 0
733
785
  }));
734
- return { hits, warnings, excludeMatches };
786
+ const includeMatches = options.include.map((name) => ({
787
+ name,
788
+ hits: includeCounts.get(name) ?? 0
789
+ }));
790
+ return { hits, warnings, excludeMatches, includeMatches };
735
791
  }
736
792
  };
737
793
  }
@@ -973,6 +1029,7 @@ function parseArgs(argv) {
973
1029
  command: "sweep",
974
1030
  yes: false,
975
1031
  exclude: [],
1032
+ include: [],
976
1033
  help: false
977
1034
  };
978
1035
  const positionals = [];
@@ -988,13 +1045,15 @@ function parseArgs(argv) {
988
1045
  options.help = true;
989
1046
  continue;
990
1047
  }
991
- if (arg === "--exclude" || arg === "--config") {
1048
+ if (arg === "--exclude" || arg === "--include" || arg === "--config") {
992
1049
  const value = argv[index + 1];
993
1050
  if (value === undefined || value.startsWith("-")) {
994
1051
  return { ok: false, message: `参数 ${arg} 缺少取值` };
995
1052
  }
996
1053
  if (arg === "--exclude")
997
1054
  options.exclude.push(value);
1055
+ else if (arg === "--include")
1056
+ options.include.push(value);
998
1057
  else
999
1058
  options.config = value;
1000
1059
  index += 1;
@@ -1005,11 +1064,11 @@ function parseArgs(argv) {
1005
1064
  positionals.push(arg);
1006
1065
  }
1007
1066
  const [only] = positionals;
1008
- if (positionals.length > 1 || only !== undefined && only !== "init") {
1067
+ if (positionals.length > 1 || only !== undefined && only !== "init" && only !== "config") {
1009
1068
  return { ok: false, message: `未知参数: ${positionals.join(" ")}` };
1010
1069
  }
1011
- if (only === "init")
1012
- options.command = "init";
1070
+ if (only === "init" || only === "config")
1071
+ options.command = only;
1013
1072
  return { ok: true, options };
1014
1073
  }
1015
1074
  function colorEnabled() {
@@ -1042,29 +1101,34 @@ function helpText(color) {
1042
1101
  row("sweep-nm", "预览: 清单 + 体积 + 合计, 零副作用"),
1043
1102
  row("sweep-nm --yes", "执行删除"),
1044
1103
  row("sweep-nm --exclude <name>", "临时追加排除 (可重复, 与配置合并)"),
1104
+ row("sweep-nm --include <name>", "只清理命中名单的目录 (可重复, 与配置合并)"),
1045
1105
  row("sweep-nm --config <path>", "指定配置文件 (优先于 SWEEP_NM_CONFIG)"),
1106
+ row("sweep-nm config", "查看实际生效的配置: 来源 + 路径 + 文件状态"),
1046
1107
  row("sweep-nm init", "初始化向导: 交互生成配置文件"),
1047
1108
  row("sweep-nm --help", "帮助"),
1048
1109
  "",
1049
1110
  "说明:",
1050
1111
  " --exclude 按目录名精确匹配 (区分大小写), 从根到命中点的任意一级命中即跳过",
1051
- ` 默认配置位置 (平台自适应): ${defaultConfigPath()}`,
1112
+ " --include 同款匹配口径, 命中才纳入; 同时命中 exclude 的照旧跳过",
1113
+ ` 默认配置位置 (平台自适应; 用了 --config 或 SWEEP_NM_CONFIG 时实际读的不是它): ${defaultConfigPath()}`,
1114
+ " 查实际生效的路径: sweep-nm config",
1052
1115
  "",
1053
1116
  "退出码: 0 成功 (含预览与空结果); 1 删除失败 / 配置损坏 / 参数错误"
1054
1117
  ].join(`
1055
1118
  `);
1056
1119
  }
1120
+ async function fileExists(path) {
1121
+ try {
1122
+ await lstat2(path);
1123
+ return true;
1124
+ } catch {
1125
+ return false;
1126
+ }
1127
+ }
1057
1128
  function runWizard(configPath) {
1058
1129
  return runInit({
1059
1130
  configPath,
1060
- async fileExists(path) {
1061
- try {
1062
- await lstat2(path);
1063
- return true;
1064
- } catch {
1065
- return false;
1066
- }
1067
- },
1131
+ fileExists,
1068
1132
  async writeFile(path, text) {
1069
1133
  await mkdir(dirname(path), { recursive: true });
1070
1134
  await writeTextFile(path, text);
@@ -1072,13 +1136,25 @@ function runWizard(configPath) {
1072
1136
  io: createReadlineIO()
1073
1137
  });
1074
1138
  }
1139
+ var SOURCE_LABELS = {
1140
+ flag: "--config 指定",
1141
+ env: "环境变量 SWEEP_NM_CONFIG",
1142
+ "platform-default": "平台默认"
1143
+ };
1144
+ async function reportConfig(resolved) {
1145
+ const exists = await fileExists(resolved.path);
1146
+ print(`配置来源: ${SOURCE_LABELS[resolved.source]}`);
1147
+ print(`配置路径: ${resolved.path}`);
1148
+ print(`文件状态: ${exists ? "存在" : "不存在"}`);
1149
+ return 0;
1150
+ }
1075
1151
  async function resolveConfig(resolved) {
1076
1152
  const loaded = await loadResolvedConfig(resolved);
1077
1153
  if (loaded.state === "ok")
1078
1154
  return { config: loaded.config, source: "file" };
1079
1155
  if (!interactive())
1080
1156
  return {
1081
- config: { roots: [process.cwd()], exclude: [] },
1157
+ config: { roots: [process.cwd()], exclude: [], include: [] },
1082
1158
  source: "fallback"
1083
1159
  };
1084
1160
  const result = await runWizard(resolved.path);
@@ -1113,16 +1189,25 @@ function withOutcomes(entries, batch, accepted, removal) {
1113
1189
  ...byTarget.get(entry.target) ?? fallback
1114
1190
  }));
1115
1191
  }
1116
- function reportExcludeMatches(matches, color) {
1117
- if (matches === undefined)
1118
- return;
1119
- const tty = process.stderr.isTTY === true;
1120
- for (const item of matches) {
1192
+ function collectNameNotes(excludeMatches, includeMatches, color) {
1193
+ const notes = [];
1194
+ const tty = process.stdout.isTTY === true;
1195
+ for (const item of excludeMatches ?? []) {
1121
1196
  if (item.hits === 0)
1122
- warn(`排除名未匹配到任何目录: ${item.name} (按目录名精确匹配)`, color);
1197
+ warn(`排除名未命中任何已扫描的目录: ${item.name} (按目录名精确匹配; 若其上层目录已被排除则属预期)`, color);
1123
1198
  else if (tty)
1124
- notice(`排除生效: ${item.name} (${item.hits} 处)`);
1199
+ notes.push(`排除生效: ${item.name} (${item.hits} 处)`);
1125
1200
  }
1201
+ const includes = includeMatches ?? [];
1202
+ for (const item of includes) {
1203
+ if (item.hits === 0)
1204
+ warn(`包含名未命中任何已扫描的目录: ${item.name} (按目录名精确匹配; 若其上层目录已被排除则属预期)`, color);
1205
+ else if (tty)
1206
+ notes.push(`包含命中: ${item.name} (${item.hits} 处)`);
1207
+ }
1208
+ if (includes.length > 0 && includes.every((item) => item.hits === 0))
1209
+ warn("包含名单无一条命中, 本次扫描必为空结果 (请核对名字与大小写; 若名字位于被排除的目录之下则属预期)", color);
1210
+ return notes;
1126
1211
  }
1127
1212
  function toEntries(hits, sizeResult) {
1128
1213
  const bytesOf = new Map(sizeResult.entries.map((entry) => [
@@ -1154,18 +1239,29 @@ function toEntries(hits, sizeResult) {
1154
1239
  }
1155
1240
  async function sweep(config, options, color) {
1156
1241
  const roots = config.roots;
1157
- const exclude = mergeExcludes(config.exclude, options.exclude);
1158
- const scanResult = await createParallelScanner().scan({ roots, exclude });
1242
+ const exclude = mergeNames(config.exclude, options.exclude);
1243
+ const include = mergeNames(config.include, options.include);
1244
+ const scanResult = await createParallelScanner().scan({ roots, exclude, include });
1159
1245
  for (const warning of scanResult.warnings)
1160
1246
  warn(warning, color);
1161
- reportExcludeMatches(scanResult.excludeMatches, color);
1247
+ const nameNotes = collectNameNotes(scanResult.excludeMatches, scanResult.includeMatches, color);
1248
+ const tty = process.stdout.isTTY === true;
1249
+ const runtime = tty ? runtimeLabel : undefined;
1162
1250
  const sizeResult = await createSizer().measure(scanResult.hits.map((hit) => hit.target));
1163
1251
  for (const warning of sizeResult.warnings)
1164
1252
  warn(warning, color);
1165
1253
  const entries = toEntries(scanResult.hits, sizeResult);
1166
1254
  const home = homedir4();
1167
1255
  if (!options.yes) {
1168
- print(render({ mode: "preview", roots, entries, color, home }));
1256
+ print(render({
1257
+ mode: "preview",
1258
+ roots,
1259
+ entries,
1260
+ color,
1261
+ home,
1262
+ notes: nameNotes,
1263
+ runtime
1264
+ }));
1169
1265
  return 0;
1170
1266
  }
1171
1267
  const batch = entries.filter((entry) => entry.bytes !== undefined).map((entry) => entry.target);
@@ -1187,7 +1283,9 @@ async function sweep(config, options, color) {
1187
1283
  entries: report,
1188
1284
  color,
1189
1285
  home,
1190
- releasedBytes
1286
+ releasedBytes,
1287
+ notes: nameNotes,
1288
+ runtime
1191
1289
  }));
1192
1290
  if (removal.aborted !== undefined) {
1193
1291
  warn(`整批中止: ${removal.aborted.reason}`, color);
@@ -1221,6 +1319,9 @@ async function main() {
1221
1319
  print("配置未变更");
1222
1320
  return 0;
1223
1321
  }
1322
+ if (options.command === "config") {
1323
+ return await reportConfig(resolvedPath);
1324
+ }
1224
1325
  const resolved = await resolveConfig(resolvedPath);
1225
1326
  if (resolved === null)
1226
1327
  return 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iyowei/sweep-node-modules",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "工作区级 node_modules 清理工具: 一次扫描多个根目录, 跨项目列出体积, 确认后批量删除。",
5
5
  "keywords": [
6
6
  "cli",
@@ -10,6 +10,7 @@
10
10
  "disk-usage",
11
11
  "cleanup"
12
12
  ],
13
+ "author": "iYoWei",
13
14
  "license": "MIT",
14
15
  "repository": {
15
16
  "type": "git",