my-code-style 1.8.6 → 1.9.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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  ## 变更日志
2
2
 
3
+ ## [1.9.0](https://github.com/myvn/codeStyle/compare/v1.8.6...v1.9.0) (2026-09-23)
4
+
5
+ ### ✨ Features | 新功能
6
+
7
+ - **cli:** 新增 my-code-style-doctor 独立体检命令 ([fd3ac0d](https://github.com/myvn/codeStyle/commit/fd3ac0da3ac123f1bf69e755da1de288bdf5eeb4)), closes [#6](https://github.com/myvn/codeStyle/issues/6)
8
+ - **init:** --merge 合并模式 + 收尾 hook 自检 ([f6f6fa7](https://github.com/myvn/codeStyle/commit/f6f6fa7f391f4371a9cd76ff8e436c7061b25335)), closes [#7](https://github.com/myvn/codeStyle/issues/7) [#8](https://github.com/myvn/codeStyle/issues/8)
9
+
10
+ ### 🐛 Bug Fixes | Bug 修复
11
+
12
+ - **prettier:** 默认 prettierignore 纳入各包管理器 lockfile(BUG-034) ([ece6d03](https://github.com/myvn/codeStyle/commit/ece6d035d3d71e64e1aca541dd49efaab615da48)), closes [#9](https://github.com/myvn/codeStyle/issues/9)
13
+
3
14
  ## [1.8.6](https://github.com/myvn/codeStyle/compare/v1.8.5...v1.8.6) (2026-09-22)
4
15
 
5
16
  ### 🐛 Bug Fixes | Bug 修复
package/README.md CHANGED
@@ -25,7 +25,7 @@ pnpm add -D my-code-style # npm: npm i -D my-code-style
25
25
  npx my-code-style-init --dry-run
26
26
  npx my-code-style-init # 需保留旧文件时加 --backup
27
27
 
28
- # 3. 按 CLI 输出的缺失依赖清单安装 peerDependencies(会按包管理器生成命令,别漏 typescript)
28
+ # 3. 按 CLI 输出的缺失依赖清单安装 peerDependencies(会按包管理器生成命令,别漏 typescript 和 stylelint-order——后者是 recess-order 7 的 peer,Vue/SCSS 项目缺了它 stylelint 直接崩)
29
29
  pnpm add -D my-code-style eslint@^9.0.0 typescript@^5.0.0 prettier@^3.0.0 ... # 以 CLI 实际输出为准
30
30
 
31
31
  # 4. 初始化 hooks 并首次检查
@@ -195,13 +195,30 @@ module.exports = {
195
195
  ## CLI 初始化参数
196
196
 
197
197
  ```bash
198
- npx my-code-style-init [--dry-run] [--backup] [--version|-v] [--help|-h]
198
+ npx my-code-style-init [--dry-run] [--backup] [--merge] [--version|-v] [--help|-h]
199
199
  ```
200
200
 
201
201
  - `--dry-run`:试运行模式,仅输出将执行的变更,不修改任何文件。
202
202
  - `--backup`:在覆盖已有配置文件之前,将其备份到 `.my-code-style-backup/` 目录。
203
+ - `--merge`(别名 `--no-overwrite`):合并模式——已存在的配置与 hooks 一律保留,只补缺失文件;`package.json` 只新增缺失的 scripts,已有 `lint-staged` 分组原样保留。适合升级场景先合并、再人工比对。
204
+ - 初始化结束时**自动自检 hooks**(存在 / 非空 / 可执行位 / `lint-staged`、`commitlint` 是否可解析),只提示不阻断——把"hook 存在但不生效"消灭在当场。
203
205
  - 具备**事务回滚保护**:若在写入过程中遭遇文件权限或磁盘异常,自动回滚所有修改,恢复工作区原始状态。
204
206
 
207
+ ## 项目体检:my-code-style-doctor
208
+
209
+ ```bash
210
+ npx my-code-style-doctor
211
+ ```
212
+
213
+ 对既有项目随时复验(init 的依赖体检只在新装/重装时打印一次):
214
+
215
+ - **peer 依赖**:按项目类型裁剪核对(与 init 同口径——ESLint 8 才查 classic import、无预处理器不查 stylelint 族),缺失/版本越界逐项报红,并输出可整段粘贴的补齐命令;
216
+ - **husky hooks**:存在 / 非空 / 可执行位 / 引用命令可解析 / `core.hooksPath` 指向;
217
+ - **lockfile**:是否被 `.gitignore` 排除(排除 = 不同机器版本组合不可复现);
218
+ - **配置文件**:四件套是否就位。
219
+
220
+ 退出码 `0` 健康 / `1` 有问题,可直接当 CI 门禁用。
221
+
205
222
  ## 特性
206
223
 
207
224
  - **双引号**:`quotes: ["error", "double", { avoidEscape: true, allowTemplateLiterals: true }]`(`avoidEscape` 必须为 `true`,否则与 Prettier 的转义策略冲突,`--fix` 无法消除报错)
@@ -218,32 +235,33 @@ npx my-code-style-init [--dry-run] [--backup] [--version|-v] [--help|-h]
218
235
 
219
236
  ## 常见问题(使用中遇到的问题)
220
237
 
221
- | 现象 | 原因 | 处理 |
222
- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
223
- | 只装了 `my-code-style`,`pnpm lint` 报找不到 eslint | peerDependencies 全部是 optional,不会自动安装 | 按 CLI 结尾输出的清单装全,**别漏 `typescript`**(`@typescript-eslint/parser` / `typescript-eslint` 的必需 peer) |
224
- | `pnpm prepare` 输出 `.git can't be found`,hooks 不生效 | husky 必须在 git 仓库内执行 | 先 `git init`、再 `pnpm prepare`;验证 `git config core.hooksPath` 输出 `.husky/_` |
225
- | 安装依赖报 `ERR_PNPM_IGNORED_BUILDS`(如 `unrs-resolver`) | pnpm 10+ 默认拦截依赖的构建脚本 | 执行 `pnpm approve-builds` 后重新安装,不是初始化失败 |
226
- | `eslint` 声明 `>=8.0.0` 却生成了 Flat Config | 无上界范围 npm 实际会装 9,CLI 按 9 生成 | 确定留在 8 就把范围收紧到 `<9`(如 `~8.57.0`)后重跑 init |
227
- | 重复 init 后,改过的 `.prettierrc.cjs` / hooks 被覆盖 | 除 ESLint 入口与已存在的 `.gitignore` 外,目标文件一律覆盖 | 先用 `--dry-run` 看清单、用 `--backup` 留档(备份含 `package.json`,目录会自动写入 `.gitignore`) |
228
- | 自定义 `lint-staged` 分组消失 | `lint-staged` 为整体替换,避免残留失效分组 | 从 `.my-code-style-backup/package.json` 恢复后手动合并 |
229
- | 提交时 lint 报错、提交失败 | 修不了的错误(语法错误、非法 CSS 属性)会阻止提交 | 按提示修复;紧急情况可用 `git commit --no-verify`,但请在 **CI 用 `pnpm lint` 兜底** |
230
- | 提交信息被拒(`type may not be empty` / `subject may not be empty`) | 提交信息需符合 conventional commits,`类型(范围): 描述` 的**冒号后必须有空格** | 先看冒号后面有没有空格(`fix:(修复)…` 会被判成 type 与 subject 双空);用 `pnpm cz` 交互式生成;header 上限 108 字符 |
231
- | `pnpm cz` 报 `No files added to staging!` | czg 由暂存区驱动:没有暂存文件就不启动(`--all` / `-a` 也不绕过) | 先 `git add -A` 再 `pnpm cz`;scope 候选与默认值也是按暂存区推断的 |
232
- | 想让 `pnpm cz` 的提示换成英文/自己的措辞 | 提示语来自 `prompt.messages`,本包默认中文 | 在项目的 `.commitlintrc.cjs` 里覆盖 `prompt.messages`(标题)与 `prompt.types`(类型描述);scope 列表里的「自定义 / 不填」对应 `customScopesAlias` / `emptyScopesAlias` |
233
- | 老项目已有 `.eslintrc.*`,init 只读退出 | ESLint 版本与配置格式冲突时 CLI 拒绝写入 | 先确认/迁移版本,再重跑 init |
234
- | `pnpm release` 之后如何发布 | `release` 只生成版本、CHANGELOG、提交与 tag | 另行执行 `npm publish` |
235
- | 装完看到一片 `unmet peer` 警告,要不要管 | npm 遇到不满足的 peer 会直接 ERESOLVE 拒装,pnpm 只打印 WARN 就装完 | 先看警告来自谁:`unmet peer … from my-code-style` 说明版本声明没跟上,先升级本包;来自别的包(如 `postcss-html@1.8.1` 却要 `^2`)按提示对齐。重跑 `init` 会主动体检(范围精确到 minor,例如 `vue-eslint-parser 10.2.0` 不满足 `^10.3.0`)并打印对齐命令 |
236
- | `stylelint` 该用 16 还是 17 | 两条线都支持:`stylelint ^16.24.0 \|\| ^17.0.0` | 16 线(`stylelint-config-recommended@17`)兼容面最广;17 线要 stylelint 17 + `config-recommended@18` + `recommended-scss@17` + `stylelint-order@7/8`,且 Node ≥ 22.12。两条线都有真实运行回归(集成套件跑 16 线,Stylelint 17 套件跑 17 线) |
238
+ | 现象 | 原因 | 处理 |
239
+ | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
240
+ | 只装了 `my-code-style`,`pnpm lint` 报找不到 eslint | peerDependencies 全部是 optional,不会自动安装 | 按 CLI 结尾输出的清单装全,**别漏 `typescript`**(`@typescript-eslint/parser` / `typescript-eslint` 的必需 peer) |
241
+ | stylelint 报 `Could not find plugin "stylelint-order"` | recess-order 7 把 stylelint-order 声明为 peer(非依赖),pnpm 10+ 严格模式 / npm / yarn 不自动装 | 显式安装 `stylelint-order`(对齐 peer 范围 `^6 \|\| ^7 \|\| ^8`;Vue/SCSS 项目必装) |
242
+ | `pnpm prepare` 输出 `.git can't be found`,hooks 不生效 | husky 必须在 git 仓库内执行 | 先 `git init`、再 `pnpm prepare`;验证 `git config core.hooksPath` 输出 `.husky/_` |
243
+ | 安装依赖报 `ERR_PNPM_IGNORED_BUILDS`(如 `unrs-resolver`) | pnpm 10+ 默认拦截依赖的构建脚本 | 执行 `pnpm approve-builds` 后重新安装,不是初始化失败 |
244
+ | `eslint` 声明 `>=8.0.0` 却生成了 Flat Config | 无上界范围 npm 实际会装 9,CLI 按 9 生成 | 确定留在 8 就把范围收紧到 `<9`(如 `~8.57.0`)后重跑 init |
245
+ | 重复 init 后,改过的 `.prettierrc.cjs` / hooks 被覆盖 | 除 ESLint 入口与已存在的 `.gitignore` 外,目标文件一律覆盖 | 先用 `--dry-run` 看清单、用 `--backup` 留档(备份含 `package.json`,目录会自动写入 `.gitignore`) |
246
+ | 自定义 `lint-staged` 分组消失 | `lint-staged` 为整体替换,避免残留失效分组 | 从 `.my-code-style-backup/package.json` 恢复后手动合并 |
247
+ | 提交时 lint 报错、提交失败 | 修不了的错误(语法错误、非法 CSS 属性)会阻止提交 | 按提示修复;紧急情况可用 `git commit --no-verify`,但请在 **CI 用 `pnpm lint` 兜底** |
248
+ | 提交信息被拒(`type may not be empty` / `subject may not be empty`) | 提交信息需符合 conventional commits,`类型(范围): 描述` 的**冒号后必须有空格** | 先看冒号后面有没有空格(`fix:(修复)…` 会被判成 type 与 subject 双空);用 `pnpm cz` 交互式生成;header 上限 108 字符 |
249
+ | `pnpm cz` 报 `No files added to staging!` | czg 由暂存区驱动:没有暂存文件就不启动(`--all` / `-a` 也不绕过) | 先 `git add -A` 再 `pnpm cz`;scope 候选与默认值也是按暂存区推断的 |
250
+ | 想让 `pnpm cz` 的提示换成英文/自己的措辞 | 提示语来自 `prompt.messages`,本包默认中文 | 在项目的 `.commitlintrc.cjs` 里覆盖 `prompt.messages`(标题)与 `prompt.types`(类型描述);scope 列表里的「自定义 / 不填」对应 `customScopesAlias` / `emptyScopesAlias` |
251
+ | 老项目已有 `.eslintrc.*`,init 只读退出 | ESLint 版本与配置格式冲突时 CLI 拒绝写入 | 先确认/迁移版本,再重跑 init |
252
+ | `pnpm release` 之后如何发布 | `release` 只生成版本、CHANGELOG、提交与 tag | 另行执行 `npm publish` |
253
+ | 装完看到一片 `unmet peer` 警告,要不要管 | npm 遇到不满足的 peer 会直接 ERESOLVE 拒装,pnpm 只打印 WARN 就装完 | 先看警告来自谁:`unmet peer … from my-code-style` 说明版本声明没跟上,先升级本包;来自别的包(如 `postcss-html@1.8.1` 却要 `^2`)按提示对齐。重跑 `init` 会主动体检(范围精确到 minor,例如 `vue-eslint-parser 10.2.0` 不满足 `^10.3.0`)并打印对齐命令 |
254
+ | `stylelint` 该用 16 还是 17 | 两条线都支持:`stylelint ^16.24.0 \|\| ^17.0.0` | 16 线(`stylelint-config-recommended@17`)兼容面最广;17 线要 stylelint 17 + `config-recommended@18` + `recommended-scss@17` + `stylelint-order@7/8`,且 Node ≥ 22.12。两条线都有真实运行回归(集成套件跑 16 线,Stylelint 17 套件跑 17 线) |
237
255
 
238
256
  完整 FAQ(含更多场景与解释)见 [docs/manual.md](docs/manual.md#五使用中遇到的问题faq)。
239
257
 
240
258
  ## 测试套件
241
259
 
242
260
  ```bash
243
- npm run test:all # 全量运行 189 项:用例明细 + 分类统计 + 最慢文件定位
261
+ npm run test:all # 全量运行 194 项:用例明细 + 分类统计 + 最慢文件定位
244
262
  npm run diagnose # 换机器后先跑它:进程 / git / 文件系统 / hooks 各占多少
245
263
  npm run sweep # 给本机找最佳文件级并发(扫 integration 套件)
246
- npm test # 只跑基础 CLI 与配置矩阵(88 项)
264
+ npm test # 只跑基础 CLI 与配置矩阵(93 项)
247
265
  npm run test:integration:setup # 安装现代化隔离依赖运行环境
248
266
  npm run test:integration # Flat Config、真实 Husky 及提交链路测试(65 项)
249
267
  npm run test:legacy:setup # 安装 ESLint 8 隔离运行环境
@@ -258,47 +276,47 @@ npm run test:stylelint17 # Stylelint 17 生态兼容性回归(8 项)
258
276
  ```text
259
277
  my-code-style 测试套件
260
278
 
261
- ▶ [1/4] 基础 CLI 与配置矩阵 (共 88 项,5 文件 · 3 文件并发(自动:2 核 / 内存 4G))
279
+ ▶ [1/4] 基础 CLI 与配置矩阵 (共 93 项,5 文件 · 3 文件并发(自动:2 核 / 内存 4G))
262
280
  ✓ 运行器 TAP 解析:统计通过与失败、SKIP 与每用例耗时 · 7ms
263
281
  ✓ cz 交互提示为中文,且可选类型与 type-enum 一一对应 · 1ms
264
282
  ✓ peer 范围覆盖我们声明支持的上游大版本(校准防回退,BUG-027) · 0ms
265
283
  ✓ 一键安装命令对含 || 的版本范围加引号,可整段粘贴执行 · 40ms
266
284
  ✓ 初始化结尾指引把 cz 用法说清楚(先 git add + 指到 README 手册) · 80ms
267
285
  …
268
- ✓ 通过 88 · 3.6s · 最慢文件 init-matrix.test.cjs 3.4s
286
+ ✓ 通过 93 · 4.9s · 最慢文件 init-matrix.test.cjs 4.6s
269
287
 
270
288
  ▶ [2/4] 现代工具链与提交链 (共 65 项,24 文件 · 3 文件并发(自动:2 核 / 内存 4G))
271
289
  ✓ 完整提交链:JS/TS/Vue/nvue/CSS/less 自动修复及二次复检 · 10.4s
272
290
  ✓ 发布防呆:HEAD 已有 v* tag 时拦截(此时 release 工具会静默抬版并写出空 CHANGELOG) · 609ms
273
291
  …
274
- ✓ 通过 65 · 45.3s · 最慢文件 commit-chain-both.test.cjs 12.4s
292
+ ✓ 通过 65 · 50.7s · 最慢文件 commit-chain-both.test.cjs 16.1s
275
293
 
276
294
  ▶ [3/4] ESLint 8 兼容性 (共 27 项,1 文件 · 3 文件并发(自动:2 核 / 内存 4G))
277
295
  ✓ 独立运行 ESLint 8 支持下限而非 ESLint 9 · 1ms
278
296
  ✓ ESLint 8 base:实际 CLI 加载生成配置并接受正常文件 · 1.3s
279
297
  …
280
- ✓ 通过 27 · 18.3s
298
+ ✓ 通过 27 · 19.4s
281
299
 
282
300
  ▶ [4/4] Stylelint 17 兼容性 (共 9 项,1 文件 · 3 文件并发(自动:2 核 / 内存 4G))
283
301
  ✓ 隔离环境装的是 stylelint 17(不是 16) · 2ms
284
302
  ✓ 生成的 .stylelintrc.cjs 在 stylelint 17 下可加载并放过正常 SCSS · 700ms
285
303
  …
286
- ✓ 通过 9 · 8.2s
304
+ ✓ 通过 9 · 9.6s
287
305
 
288
306
  ──────────────────────────────────────────────────────
289
307
  套件 通过 失败 跳过 用时
290
308
  ──────────────────────────────────────────────────────
291
- 基础 CLI 与配置矩阵 88 0 - 3.6s
292
- 现代工具链与提交链 65 0 - 45.3s
293
- ESLint 8 兼容性 27 0 - 18.7s
294
- Stylelint 17 兼容性 9 0 - 8.2s
309
+ 基础 CLI 与配置矩阵 93 0 - 4.9s
310
+ 现代工具链与提交链 65 0 - 50.7s
311
+ ESLint 8 兼容性 27 0 - 19.4s
312
+ Stylelint 17 兼容性 9 0 - 9.6s
295
313
  ──────────────────────────────────────────────────────
296
- 合计 189 0 - 76.9s
314
+ 合计 194 0 - 84.6s
297
315
  ──────────────────────────────────────────────────────
298
316
 
299
317
  ⏱ 最慢文件:eslint8.test.cjs 18.0s · commit-chain-less.test.cjs 11.4s · commit-chain-both.test.cjs 11.3s
300
318
 
301
- ✅ 全部通过:189/189 项,用时 76.9s
319
+ ✅ 全部通过:194/194 项,用时 84.6s
302
320
  ```
303
321
 
304
322
  终端里每个套件下方还有一条实时进度条(`██████░░░░ 38/66 失败 0 4.0s`)。附加参数:
@@ -376,7 +394,7 @@ npm run test:all -- --profile # 看每个测试文件耗时,定位瓶颈
376
394
  | `npm run test:integration`(运行器调度,自动并发 3) | 30.6s(只看集成套件那一段) |
377
395
  | 串行套件 + 文件级并发 23(全部一波) | ✗ 3.8G 内存沙箱被 OOM 压垮(19 项 SIGKILL) |
378
396
 
379
- 同机复测(189 项,同一台 2 核沙箱连续跑;绝对秒数随机器负载波动,相对关系稳定):串行套件 + 文件级并发 1 = 84.4s、默认自动并发 3 = 76.9s、`npm run test:integration` = 45.3s(其余口径为早前基线实测,相对关系稳定)。
397
+ 同机复测(194 项,同一台 2 核沙箱连续跑;绝对秒数随机器负载波动,相对关系稳定):默认自动并发 3 = 84.6s、`npm run test:integration` = 50.7s(本轮实跑;串行与 parallel 口径为早前基线实测,相对关系稳定)。
380
398
 
381
399
  (2 核沙箱里并行收益被 CPU 争抢吃掉大半,`--concurrency=1` 时单个文件只要 0.7–4.2s;
382
400
  16 核机器上集成套件那段 ≈ 最慢子文件,即"一次真实提交"的量级。)
package/bin/doctor ADDED
@@ -0,0 +1,334 @@
1
+ #!/usr/bin/env node
2
+ // my-code-style-doctor — 项目体检:peer 是否装齐且版本达标、hooks 是否真的能跑、
3
+ // lockfile 是否被 gitignore 排除、配置文件是否就位。一次性报红,供 CI 与人工复验。
4
+ //
5
+ // 背景:peerDependencies 全部 optional(包管理器零警告),"看起来配了、实际全死"
6
+ // 可以长期潜伏(下游 1.2 → 1.8 升级实测 20 个 peer 一个没装、hook 命令被注释)。
7
+ // init 的依赖体检只在新装/重装时打印一次;doctor 让既有项目随时可查(issue #6)。
8
+
9
+ const fs = require("fs")
10
+ const path = require("path")
11
+ const { spawnSync } = require("child_process")
12
+
13
+ const PROJECT_ROOT = process.cwd()
14
+ let problems = 0
15
+
16
+ const ok = (msg) => console.log(` ✓ ${msg}`)
17
+ const bad = (msg) => {
18
+ problems++
19
+ console.log(` ✗ ${msg}`)
20
+ }
21
+ const info = (msg) => console.log(` · ${msg}`)
22
+
23
+ const args = process.argv.slice(2)
24
+ const supported = new Set(["--help", "-h", "--version", "-v"])
25
+ const unknown = args.filter((arg) => !supported.has(arg))
26
+ if (unknown.length) {
27
+ console.error(`未知参数: ${unknown.join(", ")};使用 --help 查看帮助`)
28
+ process.exit(1)
29
+ }
30
+ if (args.includes("--help") || args.includes("-h")) {
31
+ console.log("Usage: my-code-style-doctor [--version|-v] [--help|-h]")
32
+ console.log("在项目根目录运行:体检 peer 依赖、husky hooks、lockfile 入库与配置文件。")
33
+ console.log("退出码:0 = 全部健康;1 = 存在需要处理的问题(可用于 CI 门禁)。")
34
+ process.exit(0)
35
+ }
36
+ if (args.includes("--version") || args.includes("-v")) {
37
+ console.log(require("../package.json").version)
38
+ process.exit(0)
39
+ }
40
+
41
+ // ---- 环境解析 ----
42
+ const projectRequire = (() => {
43
+ try {
44
+ return require("node:module").createRequire(path.join(PROJECT_ROOT, "package.json"))
45
+ } catch {
46
+ return require
47
+ }
48
+ })()
49
+
50
+ function readManifest() {
51
+ try {
52
+ return JSON.parse(fs.readFileSync(path.join(PROJECT_ROOT, "package.json"), "utf8"))
53
+ } catch {
54
+ return null
55
+ }
56
+ }
57
+
58
+ // 读取依赖包版本:优先裸包名/package.json(可能被 exports 挡,如 less),
59
+ // 回退到 resolve(裸包名) 后读相邻 package.json
60
+ function installedVersion(projectRequire, name) {
61
+ try {
62
+ return require(`${name}/package.json`).version
63
+ } catch {}
64
+ try {
65
+ const entry = projectRequire.resolve(name)
66
+ // 截掉入口文件取包目录(用 path.dirname;别用正则截第一个分隔符——会得到空串)
67
+ const dir = path.dirname(entry)
68
+ return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")).version
69
+ } catch {
70
+ return null
71
+ }
72
+ }
73
+
74
+ // 迷你 semver:覆盖本包 peer 的全部形态(^x.y.z 的 || 组合、*)
75
+ function satisfies(version, range) {
76
+ const [major, minor = 0, patch = 0] = String(version)
77
+ .split(".")
78
+ .map((n) => parseInt(n, 10))
79
+ if ([major, minor, patch].some(Number.isNaN)) return false
80
+ return range
81
+ .split("||")
82
+ .map((alt) => alt.trim())
83
+ .some((alt) => {
84
+ if (!alt || alt === "*") return true
85
+ const caret = alt.match(/^\^(\d+)\.(\d+)\.(\d+)$/)
86
+ if (!caret) return false
87
+ const [M, m, p] = caret.slice(1).map(Number)
88
+ if (M > 0) return major === M
89
+ if (m > 0) return major === 0 && minor === m
90
+ return major === 0 && minor === 0 && patch === p
91
+ })
92
+ }
93
+
94
+ console.log(`my-code-style-doctor · 项目 ${path.basename(PROJECT_ROOT)}`)
95
+
96
+ // ---- ① package.json 与 my-code-style ----
97
+ const manifest = readManifest()
98
+ if (!manifest) {
99
+ bad("package.json 不存在或不是合法 JSON(在项目根目录运行)")
100
+ console.log(`\n体检完成:${problems} 个问题`)
101
+ process.exit(1)
102
+ }
103
+ ok("package.json 可解析")
104
+
105
+ let selfPkg = null
106
+ try {
107
+ selfPkg = projectRequire("my-code-style/package.json")
108
+ } catch {}
109
+ if (!selfPkg) {
110
+ bad("my-code-style 未安装(npm i -D my-code-style)")
111
+ console.log(`\n体检完成:${problems} 个问题`)
112
+ process.exit(1)
113
+ }
114
+ ok(`my-code-style ${selfPkg.version}`)
115
+
116
+ // ---- ② peer 依赖:装了吗?版本对吗? ----
117
+ // 与 init 的依赖体检(checkPeerDeps)同口径裁剪:classic import 仅 ESLint 8 legacy
118
+ // 线需要;无预处理器且非 Vue 项目不查 stylelint 族;Vue 项目才查 vue 全家。
119
+ // 改动需与 bin/init 两侧同步(init-matrix 回归守底)。
120
+ function requiredPeers(manifest) {
121
+ const deps = {
122
+ ...manifest.dependencies,
123
+ ...manifest.devDependencies,
124
+ ...manifest.peerDependencies,
125
+ }
126
+ const eslintSpec = String(deps.eslint ?? "")
127
+ const eslintMajor = Number((eslintSpec.match(/(\d+)\./) || [])[1] ?? 0)
128
+ const hasLegacyEntry = [".eslintrc.cjs", ".eslintrc.js", ".eslintrc.json"].some((f) =>
129
+ fs.existsSync(path.join(PROJECT_ROOT, f)),
130
+ )
131
+ const hasFlatEntry = [
132
+ "eslint.config.mjs",
133
+ "eslint.config.js",
134
+ "eslint.config.ts",
135
+ "eslint.config.cjs",
136
+ ].some((f) => fs.existsSync(path.join(PROJECT_ROOT, f)))
137
+ const useFlat = hasFlatEntry || (!hasLegacyEntry && eslintMajor >= 9)
138
+ const isVue = !!(deps.vue || deps["@dcloudio/uni-app"] || deps["uni-app"])
139
+ const cssPre =
140
+ deps.less && (deps.sass || isVue)
141
+ ? "both"
142
+ : deps.less
143
+ ? "less"
144
+ : deps.sass || isVue
145
+ ? "scss"
146
+ : null
147
+
148
+ const list = [
149
+ "eslint",
150
+ "typescript",
151
+ "prettier",
152
+ ...(isVue ? ["eslint-plugin-vue"] : []),
153
+ "@commitlint/cli",
154
+ "@commitlint/config-conventional",
155
+ "husky",
156
+ "lint-staged",
157
+ "czg",
158
+ "commit-and-tag-version",
159
+ ]
160
+ if (useFlat) {
161
+ list.push(
162
+ "typescript-eslint",
163
+ "eslint-import-resolver-typescript",
164
+ ...(isVue ? ["vue-eslint-parser"] : []),
165
+ "globals",
166
+ "eslint-plugin-import-x",
167
+ "@eslint/js",
168
+ "eslint-plugin-prettier",
169
+ "eslint-config-prettier",
170
+ )
171
+ } else {
172
+ list.push(
173
+ "@typescript-eslint/parser",
174
+ "@typescript-eslint/eslint-plugin",
175
+ ...(isVue ? ["vue-eslint-parser"] : []),
176
+ "eslint-plugin-import",
177
+ "eslint-import-resolver-typescript",
178
+ "eslint-plugin-prettier",
179
+ "eslint-config-prettier",
180
+ )
181
+ }
182
+ if (cssPre === "scss" || cssPre === "both") {
183
+ list.push(
184
+ "stylelint",
185
+ "postcss-scss",
186
+ "postcss-html",
187
+ "stylelint-config-recommended",
188
+ "stylelint-config-recommended-scss",
189
+ "stylelint-config-recommended-vue",
190
+ "stylelint-config-html",
191
+ "stylelint-config-recess-order",
192
+ "stylelint-prettier",
193
+ )
194
+ }
195
+ if (cssPre === "less" || cssPre === "both") {
196
+ list.push(
197
+ "stylelint",
198
+ "postcss-less",
199
+ "postcss-html",
200
+ "stylelint-config-recommended",
201
+ "stylelint-config-recommended-vue",
202
+ "stylelint-config-html",
203
+ "stylelint-config-recess-order",
204
+ "stylelint-prettier",
205
+ )
206
+ }
207
+ return [...new Set(list)]
208
+ }
209
+
210
+ const peers = selfPkg.peerDependencies || {}
211
+ const scopedPeers = manifest.name === "my-code-style" ? [] : requiredPeers(manifest)
212
+ const declared = {
213
+ ...manifest.dependencies,
214
+ ...manifest.devDependencies,
215
+ ...manifest.peerDependencies,
216
+ }
217
+ const missing = []
218
+ const mismatched = []
219
+ const peerRanges = selfPkg.peerDependencies || {}
220
+ for (const name of scopedPeers) {
221
+ const range = peerRanges[name] ?? "*"
222
+ const version = installedVersion(projectRequire, name)
223
+ if (!version) {
224
+ missing.push([name, range])
225
+ continue
226
+ }
227
+ if (!satisfies(version, range)) {
228
+ mismatched.push([name, version, range])
229
+ }
230
+ }
231
+ if (manifest.name === "my-code-style") {
232
+ info("my-code-style 仓库自身:跳过 peer 体检(狗粮环境按需自装)")
233
+ } else if (scopedPeers.length === 0) {
234
+ info("未检出需要体检的 peer(项目类型判定为空)")
235
+ } else if (missing.length === 0 && mismatched.length === 0) {
236
+ ok(`peer 依赖 ${scopedPeers.length} 个全部安装且版本达标`)
237
+ } else {
238
+ for (const [name, range] of missing) bad(`peer ${name} 未安装(要求 ${range})`)
239
+ for (const [name, version, range] of mismatched) bad(`peer ${name}@${version} 不满足 ${range}`)
240
+ const spec = [...missing, ...mismatched.map(([n, , r]) => [n, r])]
241
+ .map(([name, range]) => (range.includes("||") ? `"${name}@${range}"` : `${name}@${range}`))
242
+ .join(" ")
243
+ info(`一键补齐(按包管理器换命令):npm i -D ${spec}`)
244
+ }
245
+
246
+ // ---- ③ husky hooks:存在 / 非空 / 可执行 / 命令可解析 ----
247
+ const hooksDir = path.join(PROJECT_ROOT, ".husky")
248
+ const hookNames = ["pre-commit", "commit-msg"]
249
+ if (!fs.existsSync(hooksDir)) {
250
+ bad(".husky/ 不存在:先跑 init 生成 hooks,再 npm i 触发 prepare")
251
+ } else {
252
+ const gitHooksPath = spawnSync("git", ["config", "core.hooksPath"], {
253
+ cwd: PROJECT_ROOT,
254
+ encoding: "utf8",
255
+ })
256
+ if (gitHooksPath.status !== 0) {
257
+ info("非 git 仓库或 core.hooksPath 未设置:git init + npm run prepare 后 hooks 生效")
258
+ } else if (gitHooksPath.stdout.trim() !== ".husky/_") {
259
+ bad(`core.hooksPath=${gitHooksPath.stdout.trim()},预期 .husky/_`)
260
+ } else {
261
+ ok("core.hooksPath 指向 .husky/_")
262
+ }
263
+ for (const name of hookNames) {
264
+ const hookPath = path.join(hooksDir, name)
265
+ if (!fs.existsSync(hookPath)) {
266
+ bad(`.husky/${name} 缺失`)
267
+ continue
268
+ }
269
+ const content = fs.readFileSync(hookPath, "utf8")
270
+ if (!content.trim()) {
271
+ bad(`.husky/${name} 内容为空(曾出现注释掉命令导致门禁静默失效的案例)`)
272
+ continue
273
+ }
274
+ if ((fs.statSync(hookPath).mode & 0o111) === 0) {
275
+ bad(`.husky/${name} 缺少可执行位,git 会静默忽略(chmod +x 修复)`)
276
+ continue
277
+ }
278
+ let cmdOk = true
279
+ for (const cmd of ["lint-staged", "commitlint"]) {
280
+ if (!content.includes(cmd)) continue
281
+ const localBin = fs.existsSync(path.join(PROJECT_ROOT, "node_modules", ".bin", cmd))
282
+ const installed = Boolean(declared[name]) || Boolean(declared[cmd])
283
+ if (!localBin && !installedVersion(projectRequire, cmd) && !installed) {
284
+ bad(`.husky/${name} 引用的 ${cmd} 未安装:提交时会因 npx --no-install 失败`)
285
+ cmdOk = false
286
+ }
287
+ }
288
+ if (cmdOk) ok(`.husky/${name} 存在、可执行、引用命令可解析`)
289
+ }
290
+ }
291
+
292
+ // ---- ④ lockfile 入库(F3):被 gitignore 的 lockfile 让版本不可复现 ----
293
+ const lockfiles = ["pnpm-lock.yaml", "yarn.lock", "package-lock.json", "bun.lockb", "bun.lock"]
294
+ const presentLock = lockfiles.find((f) => fs.existsSync(path.join(PROJECT_ROOT, f)))
295
+ if (!presentLock) {
296
+ info("未发现 lockfile(可复现安装建议入库一份)")
297
+ } else {
298
+ const check = spawnSync("git", ["check-ignore", presentLock], {
299
+ cwd: PROJECT_ROOT,
300
+ encoding: "utf8",
301
+ })
302
+ if (check.status === 0) {
303
+ bad(`${presentLock} 被 .gitignore 排除:不同机器/CI 的版本组合将不可复现`)
304
+ } else {
305
+ ok(`lockfile ${presentLock} 已入库`)
306
+ }
307
+ }
308
+
309
+ // ---- ⑤ 配置文件就位 ----
310
+ const flatEntry = [
311
+ "eslint.config.mjs",
312
+ "eslint.config.js",
313
+ "eslint.config.ts",
314
+ "eslint.config.cjs",
315
+ ].find((f) => fs.existsSync(path.join(PROJECT_ROOT, f)))
316
+ const configs = [
317
+ [".prettierrc.cjs", "prettier"],
318
+ [".stylelintrc.cjs", "stylelint(有 CSS 预处理器的项目)"],
319
+ [flatEntry || null, "eslint 入口"],
320
+ [".commitlintrc.cjs", "commitlint"],
321
+ ]
322
+ let configCount = 0
323
+ for (const [file, label] of configs) {
324
+ if (!file) continue
325
+ if (fs.existsSync(path.join(PROJECT_ROOT, file))) {
326
+ configCount++
327
+ } else {
328
+ info(`缺 ${file}(${label})——需要时用 my-code-style-init 生成`)
329
+ }
330
+ }
331
+ if (configCount > 0) ok(`配置文件 ${configCount} 个就位`)
332
+
333
+ console.log(`\n体检完成:${problems === 0 ? "全部健康 ✓" : `${problems} 个问题需要处理`}`)
334
+ process.exit(problems === 0 ? 0 : 1)
package/bin/init CHANGED
@@ -682,7 +682,16 @@ function getLintStagedConfig(cssPreprocessor) {
682
682
 
683
683
  function main() {
684
684
  const args = process.argv.slice(2)
685
- const supported = new Set(["--dry-run", "--backup", "--version", "-v", "--help", "-h"])
685
+ const supported = new Set([
686
+ "--dry-run",
687
+ "--backup",
688
+ "--merge",
689
+ "--no-overwrite",
690
+ "--version",
691
+ "-v",
692
+ "--help",
693
+ "-h",
694
+ ])
686
695
  const unknown = args.filter((arg) => !supported.has(arg))
687
696
  if (unknown.length) {
688
697
  console.error(`未知参数: ${unknown.join(", ")};使用 --help 查看帮助`)
@@ -690,9 +699,15 @@ function main() {
690
699
  return
691
700
  }
692
701
  if (args.includes("--help") || args.includes("-h")) {
693
- console.log("Usage: my-code-style-init [--dry-run] [--backup] [--version|-v] [--help|-h]")
702
+ console.log(
703
+ "Usage: my-code-style-init [--dry-run] [--backup] [--merge] [--version|-v] [--help|-h]",
704
+ )
694
705
  console.log(" --backup 覆盖已有配置前将其备份到 .my-code-style-backup/ 目录")
695
706
  console.log(" --dry-run 试运行,仅输出将执行的变更,不写入任何文件")
707
+ console.log(
708
+ " --merge 合并模式:已存在的配置一律保留,只补缺失文件(别名 --no-overwrite)",
709
+ )
710
+ console.log(" 结束时自动自检 hooks(存在 / 可执行 / 命令可解析),仅提示不阻断")
696
711
  console.log("初始化会覆盖部分配置和 hooks;请先备份并运行 --dry-run。")
697
712
  return
698
713
  }
@@ -907,6 +922,7 @@ function main() {
907
922
  }
908
923
 
909
924
  const backup = args.includes("--backup")
925
+ const mergeMode = args.includes("--merge") || args.includes("--no-overwrite")
910
926
  stepHeader(3, 6, "配置文件与 Git hooks")
911
927
  let overwriteTotal = 0
912
928
  let createTotal = 0
@@ -1023,6 +1039,8 @@ function main() {
1023
1039
  // package.json is rewritten (scripts + lint-staged), so it must be backed
1024
1040
  // up as well — users lose custom lint-staged groups otherwise.
1025
1041
  for (const item of [...files, ...hooks, { path: "package.json" }]) {
1042
+ // --merge 不覆盖已有文件,无需为其备份(package.json 例外:scripts 仍会补齐)
1043
+ if (mergeMode && item.path !== "package.json") continue
1026
1044
  if (fileExists(item.path)) {
1027
1045
  const srcPath = path.resolve(PROJECT_ROOT, item.path)
1028
1046
  const targetPath = path.resolve(backupDir, item.path)
@@ -1034,10 +1052,10 @@ function main() {
1034
1052
  // 与本次生成的 .versionrc.cjs 抢生效顺序的同名旧配置(.versionrc /
1035
1053
  // .versionrc.json 会直接压过生成物,ESM 项目的 .versionrc.js 徒增歧义):
1036
1054
  // 备份后移除,不留"哪份在生效"的悬案(下游升级实测 D2)
1037
- const staleVersionrcFiles = [
1038
- ...staleVersionrcTop,
1039
- ...(staleVersionrc ? [".versionrc.js"] : []),
1040
- ]
1055
+ // --merge 不动用户已有配置:stale 文件保持原样(前面已给出告警)
1056
+ const staleVersionrcFiles = mergeMode
1057
+ ? []
1058
+ : [...staleVersionrcTop, ...(staleVersionrc ? [".versionrc.js"] : [])]
1041
1059
  for (const relPath of staleVersionrcFiles) {
1042
1060
  if (!fileExists(relPath)) continue
1043
1061
  const staleSrc = path.resolve(PROJECT_ROOT, relPath)
@@ -1106,6 +1124,10 @@ function main() {
1106
1124
  try {
1107
1125
  // Actually write files
1108
1126
  for (const f of files) {
1127
+ if (mergeMode && snapshot.get(f.path)?.existed) {
1128
+ console.log(` · 保留 ${f.path}(--merge 不覆盖)`)
1129
+ continue
1130
+ }
1109
1131
  writeFile(f.path, f.content)
1110
1132
  }
1111
1133
 
@@ -1114,23 +1136,33 @@ function main() {
1114
1136
  ensureDir(huskyDir)
1115
1137
  }
1116
1138
  for (const h of hooks) {
1139
+ if (mergeMode && snapshot.get(h.path)?.existed) {
1140
+ console.log(` · 保留 ${h.path}(--merge 不覆盖)`)
1141
+ continue
1142
+ }
1117
1143
  writeFile(h.path, h.content)
1118
1144
  fs.chmodSync(path.resolve(PROJECT_ROOT, h.path), 0o755)
1119
1145
  }
1120
1146
 
1121
1147
  // package.json scripts + lint-staged
1122
- modifyPackageJson({
1123
- scripts: {
1124
- lint: lintCommand,
1125
- "lint:fix": `${lintCommand} --fix`,
1126
- format: "prettier --write .",
1127
- prepare: "husky",
1128
- release: "commit-and-tag-version",
1129
- cz: "czg",
1148
+ modifyPackageJson(
1149
+ {
1150
+ scripts: {
1151
+ lint: lintCommand,
1152
+ "lint:fix": `${lintCommand} --fix`,
1153
+ format: "prettier --write .",
1154
+ prepare: "husky",
1155
+ release: "commit-and-tag-version",
1156
+ cz: "czg",
1157
+ },
1158
+ "lint-staged": getLintStagedConfig(cssPreprocessor),
1130
1159
  },
1131
- "lint-staged": getLintStagedConfig(cssPreprocessor),
1132
- })
1160
+ { merge: mergeMode },
1161
+ )
1133
1162
  printPackageJsonStep()
1163
+ if (!dryRun) {
1164
+ verifyGeneratedHooks(hooks)
1165
+ }
1134
1166
 
1135
1167
  // The backup directory is ours, not the user's source — keep it out of git
1136
1168
  if (backup) {
@@ -1177,7 +1209,43 @@ function main() {
1177
1209
  printFooter()
1178
1210
  }
1179
1211
 
1180
- function modifyPackageJson(updates) {
1212
+ // init 收尾 hook 自检(issue #8):存在 / 非空 / 可执行位 / 引用命令可解析。
1213
+ // 只报告不阻断——真实提交链路才是最终裁判,这里负责把"装了但没用"提前亮出来。
1214
+ function verifyGeneratedHooks(hooks) {
1215
+ console.log(" · hook 自检")
1216
+ let pkg = {}
1217
+ try {
1218
+ pkg = JSON.parse(fs.readFileSync(path.resolve(PROJECT_ROOT, "package.json"), "utf8"))
1219
+ } catch {}
1220
+ for (const h of hooks) {
1221
+ const abs = path.resolve(PROJECT_ROOT, h.path)
1222
+ if (!fileExists(abs)) {
1223
+ warn(`${h.path} 缺失`)
1224
+ continue
1225
+ }
1226
+ const content = fs.readFileSync(abs, "utf8")
1227
+ if (!content.trim()) {
1228
+ warn(`${h.path} 内容为空,git 将静默跳过`)
1229
+ continue
1230
+ }
1231
+ if ((fs.statSync(abs).mode & 0o111) === 0) {
1232
+ warn(`${h.path} 缺少可执行位,git 会静默忽略(chmod +x 修复)`)
1233
+ }
1234
+ for (const cmd of ["lint-staged", "commitlint"]) {
1235
+ if (!content.includes(cmd)) continue
1236
+ const localBin = fs.existsSync(path.join(PROJECT_ROOT, "node_modules", ".bin", cmd))
1237
+ const declared = Boolean(pkg.devDependencies?.[cmd] ?? pkg.dependencies?.[cmd])
1238
+ if (!localBin && !declared) {
1239
+ warn(`${h.path} 引用的 ${cmd} 未安装:安装依赖前提交会因 npx --no-install 失败`)
1240
+ }
1241
+ }
1242
+ }
1243
+ if (!fs.existsSync(path.join(PROJECT_ROOT, ".husky", "_"))) {
1244
+ console.log(" · 提示:.husky/_ 未生成,安装依赖(触发 prepare)后 hooks 才生效")
1245
+ }
1246
+ }
1247
+
1248
+ function modifyPackageJson(updates, { merge = false } = {}) {
1181
1249
  const pkgPath = path.resolve(PROJECT_ROOT, "package.json")
1182
1250
  let pkg = {}
1183
1251
  if (fileExists("package.json")) {
@@ -1214,7 +1282,8 @@ function modifyPackageJson(updates) {
1214
1282
  }
1215
1283
 
1216
1284
  // Set lint-staged (replace existing lint-staged to avoid stale/duplicate patterns)
1217
- if (updates["lint-staged"]) {
1285
+ // --merge 例外:用户已有分组原样保留,只补缺失
1286
+ if (updates["lint-staged"] && !(merge && pkg["lint-staged"])) {
1218
1287
  pkg["lint-staged"] = updates["lint-staged"]
1219
1288
  }
1220
1289
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-code-style",
3
- "version": "1.8.6",
3
+ "version": "1.9.0",
4
4
  "description": "Lint/Format/Git 配置工程化 npm 包(ESLint + Prettier + Stylelint + Commitlint + Husky + standard-version)",
5
5
  "type": "commonjs",
6
6
  "main": "src/eslint/uniapp.cjs",
@@ -13,7 +13,8 @@
13
13
  "url": "https://github.com/myvn/codeStyle/issues"
14
14
  },
15
15
  "bin": {
16
- "my-code-style-init": "./bin/init"
16
+ "my-code-style-init": "./bin/init",
17
+ "my-code-style-doctor": "./bin/doctor"
17
18
  },
18
19
  "exports": {
19
20
  ".": "./src/eslint/uniapp.cjs",
@@ -14,3 +14,13 @@
14
14
  *.woff2
15
15
  *.apk
16
16
  *.plist
17
+
18
+ # 各包管理器 lockfile:格式所有权归包管理器——pnpm 9 的单引号紧凑风格
19
+ # 与 prettier 的 YAML 风格互搏,lint-staged 每次提交都会改写、下次 install
20
+ # 又被包管理器写回(下游实测单次 diff 7664 行,BUG-034 / issue #5)
21
+ pnpm-lock.yaml
22
+ yarn.lock
23
+ package-lock.json
24
+ npm-shrinkwrap.json
25
+ bun.lockb
26
+ bun.lock