my-code-style 1.8.5 → 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,22 @@
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
+
14
+ ## [1.8.6](https://github.com/myvn/codeStyle/compare/v1.8.5...v1.8.6) (2026-09-22)
15
+
16
+ ### 🐛 Bug Fixes | Bug 修复
17
+
18
+ - 下游升级实测三缺陷——stylelint×prettier 内联互搏、release 脚本纠偏、stale versionrc 清理 ([7fa54f6](https://github.com/myvn/codeStyle/commit/7fa54f67aebc4497a9ce0f612758bd84d64ca550))
19
+
3
20
  ## [1.8.5](https://github.com/myvn/codeStyle/compare/v1.8.4...v1.8.5) (2026-09-22)
4
21
 
5
22
  ### 🐛 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` 无法消除报错)
@@ -214,38 +231,39 @@ npx my-code-style-init [--dry-run] [--backup] [--version|-v] [--help|-h]
214
231
  - **现代化 Git Hooks**:采用 Husky 9 原生极简 hook + lint-staged 互斥文件分组,串行运行、消除并发写入缓存冲突
215
232
  - **Stylelint SCSS、Less 及混合工程双支持**:支持纯 SCSS、纯 Less 以及两者共存的混合工程,放行 `@` 变量、小程序 `rpx`/`page`、深度选择器 `::v-deep` 及现代 CSS 伪类,组件内嵌多预处理器样式全面检查
216
233
  - **严格暂存区 Scope 猜测**:`guessCurrentScope()` 严格只依据 Git 暂存区推断 scope,支持多目录频次投票、重命名、物理删除、中文路径与空格路径
217
- - **ESM 兼容的自动版本发布**:支持 CommonJS(`.versionrc.js`)与 ESM(`.versionrc.cjs`)工程无缝对接 commit-and-tag-version(standard-version 的社区维护分支),一键版本递增与 CHANGELOG 生成
234
+ - **ESM 兼容的自动版本发布**:支持 CommonJS(`.versionrc.js`)与 ESM(`.versionrc.cjs`)工程无缝对接 commit-and-tag-version(standard-version 的社区维护分支),一键版本递增与 CHANGELOG 生成。peer 范围有意钉在 `^12`:13.x 的 writer 存在回归且要求搭配新 preset 组合,稳定性待观察后再放宽(旧项目遗留的 `release: standard-version` 会在 init 时被自动纠偏)
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 # 全量运行 184 项:用例明细 + 分类统计 + 最慢文件定位
261
+ npm run test:all # 全量运行 194 项:用例明细 + 分类统计 + 最慢文件定位
244
262
  npm run diagnose # 换机器后先跑它:进程 / git / 文件系统 / hooks 各占多少
245
263
  npm run sweep # 给本机找最佳文件级并发(扫 integration 套件)
246
- npm test # 只跑基础 CLI 与配置矩阵(86 项)
264
+ npm test # 只跑基础 CLI 与配置矩阵(93 项)
247
265
  npm run test:integration:setup # 安装现代化隔离依赖运行环境
248
- npm run test:integration # Flat Config、真实 Husky 及提交链路测试(63 项)
266
+ npm run test:integration # Flat Config、真实 Husky 及提交链路测试(65 项)
249
267
  npm run test:legacy:setup # 安装 ESLint 8 隔离运行环境
250
268
  npm run test:legacy # ESLint 8.57.0 兼容性回归测试(27 项)
251
269
  npm run test:stylelint17:setup # 安装 Stylelint 17 隔离运行环境
@@ -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 与配置矩阵 (共 86 项,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
- ✓ 通过 86 · 3.6s · 最慢文件 init-matrix.test.cjs 3.2s
286
+ ✓ 通过 93 · 4.9s · 最慢文件 init-matrix.test.cjs 4.6s
269
287
 
270
- ▶ [2/4] 现代工具链与提交链 (共 63 项,24 文件 · 3 文件并发(自动:2 核 / 内存 4G))
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
- ✓ 通过 63 · 40.2s · 最慢文件 commit-chain-both.test.cjs 10.7s
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
- ▶ [4/4] Stylelint 17 兼容性 (共 8 项,1 文件 · 3 文件并发(自动:2 核 / 内存 4G))
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
- ✓ 通过 8 · 7.2s
304
+ ✓ 通过 9 · 9.6s
287
305
 
288
306
  ──────────────────────────────────────────────────────
289
307
  套件 通过 失败 跳过 用时
290
308
  ──────────────────────────────────────────────────────
291
- 基础 CLI 与配置矩阵 86 0 - 3.6s
292
- 现代工具链与提交链 63 0 - 40.2s
293
- ESLint 8 兼容性 27 0 - 18.7s
294
- Stylelint 17 兼容性 8 0 - 7.3s
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
- 合计 184 0 - 69.1s
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
- ✅ 全部通过:184/184 项,用时 69.1s
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
- 同机复测(184 项,同一台 2 核沙箱连续跑;绝对秒数随机器负载波动,相对关系稳定):串行套件 + 文件级并发 1 = 72.3s、默认自动并发 3 = 69.1s、`--parallel` 四套件 = 64.0s、`npm run test:integration` = 43.3s、`node --test demo-test/integration/*.test.cjs` = 62.4s(部分为 182 项时实测,本轮仅集成套件 +2 用例,差值在秒级)。
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)
@@ -1031,6 +1049,25 @@ function main() {
1031
1049
  backedUpCount++
1032
1050
  }
1033
1051
  }
1052
+ // 与本次生成的 .versionrc.cjs 抢生效顺序的同名旧配置(.versionrc /
1053
+ // .versionrc.json 会直接压过生成物,ESM 项目的 .versionrc.js 徒增歧义):
1054
+ // 备份后移除,不留"哪份在生效"的悬案(下游升级实测 D2)
1055
+ // --merge 不动用户已有配置:stale 文件保持原样(前面已给出告警)
1056
+ const staleVersionrcFiles = mergeMode
1057
+ ? []
1058
+ : [...staleVersionrcTop, ...(staleVersionrc ? [".versionrc.js"] : [])]
1059
+ for (const relPath of staleVersionrcFiles) {
1060
+ if (!fileExists(relPath)) continue
1061
+ const staleSrc = path.resolve(PROJECT_ROOT, relPath)
1062
+ const staleTarget = path.resolve(backupDir, relPath)
1063
+ ensureDir(path.dirname(staleTarget))
1064
+ fs.copyFileSync(staleSrc, staleTarget)
1065
+ fs.rmSync(staleSrc)
1066
+ backedUpCount++
1067
+ console.log(
1068
+ ` · 旧 ${relPath} 已备份到 .my-code-style-backup/ 并移除(由 ${versionrcPath} 接管)`,
1069
+ )
1070
+ }
1034
1071
  }
1035
1072
 
1036
1073
  // ESLint 8 directory traversal defaults to .js; explicitly include typed
@@ -1087,6 +1124,10 @@ function main() {
1087
1124
  try {
1088
1125
  // Actually write files
1089
1126
  for (const f of files) {
1127
+ if (mergeMode && snapshot.get(f.path)?.existed) {
1128
+ console.log(` · 保留 ${f.path}(--merge 不覆盖)`)
1129
+ continue
1130
+ }
1090
1131
  writeFile(f.path, f.content)
1091
1132
  }
1092
1133
 
@@ -1095,23 +1136,33 @@ function main() {
1095
1136
  ensureDir(huskyDir)
1096
1137
  }
1097
1138
  for (const h of hooks) {
1139
+ if (mergeMode && snapshot.get(h.path)?.existed) {
1140
+ console.log(` · 保留 ${h.path}(--merge 不覆盖)`)
1141
+ continue
1142
+ }
1098
1143
  writeFile(h.path, h.content)
1099
1144
  fs.chmodSync(path.resolve(PROJECT_ROOT, h.path), 0o755)
1100
1145
  }
1101
1146
 
1102
1147
  // package.json scripts + lint-staged
1103
- modifyPackageJson({
1104
- scripts: {
1105
- lint: lintCommand,
1106
- "lint:fix": `${lintCommand} --fix`,
1107
- format: "prettier --write .",
1108
- prepare: "husky",
1109
- release: "commit-and-tag-version",
1110
- 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),
1111
1159
  },
1112
- "lint-staged": getLintStagedConfig(cssPreprocessor),
1113
- })
1160
+ { merge: mergeMode },
1161
+ )
1114
1162
  printPackageJsonStep()
1163
+ if (!dryRun) {
1164
+ verifyGeneratedHooks(hooks)
1165
+ }
1115
1166
 
1116
1167
  // The backup directory is ours, not the user's source — keep it out of git
1117
1168
  if (backup) {
@@ -1158,7 +1209,43 @@ function main() {
1158
1209
  printFooter()
1159
1210
  }
1160
1211
 
1161
- 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 } = {}) {
1162
1249
  const pkgPath = path.resolve(PROJECT_ROOT, "package.json")
1163
1250
  let pkg = {}
1164
1251
  if (fileExists("package.json")) {
@@ -1182,10 +1269,21 @@ function modifyPackageJson(updates) {
1182
1269
  // Merge scripts: updates won't overwrite existing scripts with the same key
1183
1270
  if (updates.scripts) {
1184
1271
  pkg.scripts = { ...updates.scripts, ...(pkg.scripts || {}) }
1272
+ // 唯一纠偏例外:standard-version 已停止维护且从未是我们的 peer,旧项目
1273
+ // 遗留的 release: standard-version 会让 pnpm release 必然 command not
1274
+ // found(下游 1.2 → 1.8.5 升级实测)。其余自定义脚本仍尊重不覆盖。
1275
+ if (
1276
+ typeof pkg.scripts.release === "string" &&
1277
+ pkg.scripts.release.includes("standard-version")
1278
+ ) {
1279
+ pkg.scripts.release = updates.scripts.release
1280
+ console.log(" ✓ release 脚本已从 standard-version 纠偏为 commit-and-tag-version")
1281
+ }
1185
1282
  }
1186
1283
 
1187
1284
  // Set lint-staged (replace existing lint-staged to avoid stale/duplicate patterns)
1188
- if (updates["lint-staged"]) {
1285
+ // --merge 例外:用户已有分组原样保留,只补缺失
1286
+ if (updates["lint-staged"] && !(merge && pkg["lint-staged"])) {
1189
1287
  pkg["lint-staged"] = updates["lint-staged"]
1190
1288
  }
1191
1289
 
@@ -1349,79 +1447,79 @@ const PEER_SOURCE_TARGETS = [
1349
1447
  * stylelint ^17),以及 typescript-eslint 与其 parser/plugin 的版本错位。
1350
1448
  */
1351
1449
  function checkInstalledVersions({ peerDeps, allPeerDeps, rootDir = PROJECT_ROOT }) {
1352
- const problems = [];
1353
- const seen = new Set();
1450
+ const problems = []
1451
+ const seen = new Set()
1354
1452
  const add = (name, message, target) => {
1355
- const key = `${name}\u0000${message}`;
1356
- if (seen.has(key)) return;
1357
- seen.add(key);
1358
- problems.push({ name, message, target });
1359
- };
1360
- const minorOf = (version) => String(version).split(".").slice(0, 2).join(".");
1453
+ const key = `${name}\u0000${message}`
1454
+ if (seen.has(key)) return
1455
+ seen.add(key)
1456
+ problems.push({ name, message, target })
1457
+ }
1458
+ const minorOf = (version) => String(version).split(".").slice(0, 2).join(".")
1361
1459
 
1362
1460
  // 1) 本工具的 peer 范围 vs 实际安装
1363
1461
  for (const dep of allPeerDeps) {
1364
- const range = dep === "eslint" ? peerDeps.eslint : peerDeps[dep];
1365
- if (!range || range === "*" || range.startsWith("npm:")) continue;
1366
- const installed = findInstalledPackage(dep, rootDir);
1367
- if (!installed) continue;
1368
- const allowed = satisfiesRange(range, installed.version);
1369
- if (allowed === null || allowed) continue;
1370
- add(dep, `${dep} 装了 ${installed.version},本工具要求 ${range}`, `${dep}@${range}`);
1462
+ const range = dep === "eslint" ? peerDeps.eslint : peerDeps[dep]
1463
+ if (!range || range === "*" || range.startsWith("npm:")) continue
1464
+ const installed = findInstalledPackage(dep, rootDir)
1465
+ if (!installed) continue
1466
+ const allowed = satisfiesRange(range, installed.version)
1467
+ if (allowed === null || allowed) continue
1468
+ add(dep, `${dep} 装了 ${installed.version},本工具要求 ${range}`, `${dep}@${range}`)
1371
1469
  }
1372
1470
 
1373
1471
  // 2) 上游配置包的 peer vs 实际安装(配置文件本身也会挑底层版本)
1374
1472
  for (const dep of PEER_SOURCE_PACKAGES) {
1375
- const source = findInstalledPackage(dep, rootDir);
1376
- if (!source) continue;
1473
+ const source = findInstalledPackage(dep, rootDir)
1474
+ if (!source) continue
1377
1475
  for (const [target, range] of Object.entries(source.manifest.peerDependencies || {})) {
1378
- if (!PEER_SOURCE_TARGETS.includes(target)) continue;
1379
- if (range === "*" || String(range).startsWith("npm:")) continue;
1380
- const installed = findInstalledPackage(target, rootDir);
1476
+ if (!PEER_SOURCE_TARGETS.includes(target)) continue
1477
+ if (range === "*" || String(range).startsWith("npm:")) continue
1478
+ const installed = findInstalledPackage(target, rootDir)
1381
1479
  if (!installed) {
1382
- if (!rangeIntervals(range).length) continue;
1480
+ if (!rangeIntervals(range).length) continue
1383
1481
  add(
1384
1482
  target,
1385
1483
  `${dep}@${source.version} 需要 ${target}@${range},项目里没有安装`,
1386
1484
  `${target}@${range}`,
1387
- );
1388
- continue;
1485
+ )
1486
+ continue
1389
1487
  }
1390
- const allowed = satisfiesRange(range, installed.version);
1391
- if (allowed === null || allowed) continue;
1488
+ const allowed = satisfiesRange(range, installed.version)
1489
+ if (allowed === null || allowed) continue
1392
1490
  add(
1393
1491
  target,
1394
1492
  `${dep}@${source.version} 要求 ${target}@${range},实际装了 ${installed.version}`,
1395
1493
  `${target}@${range}`,
1396
- );
1494
+ )
1397
1495
  }
1398
1496
  }
1399
1497
 
1400
1498
  // 3) typescript-eslint 与 @typescript-eslint/parser、eslint-plugin 必须同版本
1401
- const meta = findInstalledPackage("typescript-eslint", rootDir);
1499
+ const meta = findInstalledPackage("typescript-eslint", rootDir)
1402
1500
  if (meta) {
1403
1501
  for (const sibling of ["@typescript-eslint/parser", "@typescript-eslint/eslint-plugin"]) {
1404
- const installed = findInstalledPackage(sibling, rootDir);
1405
- if (!installed) continue;
1406
- if (minorOf(installed.version) === minorOf(meta.version)) continue;
1502
+ const installed = findInstalledPackage(sibling, rootDir)
1503
+ if (!installed) continue
1504
+ if (minorOf(installed.version) === minorOf(meta.version)) continue
1407
1505
  add(
1408
1506
  sibling,
1409
1507
  `${sibling}@${installed.version} 与 typescript-eslint@${meta.version} 不是同一版本`,
1410
1508
  `${sibling}@${meta.version}`,
1411
- );
1509
+ )
1412
1510
  }
1413
1511
  }
1414
1512
 
1415
1513
  if (!problems.length) return 0
1416
- console.log("");
1417
- warn(`以下依赖已安装,但版本与当前配置不匹配(${problems.length} 个):`);
1418
- for (const problem of problems) console.log(` · ${problem.message}`);
1419
- console.log("");
1420
- warn("对齐命令(可整段粘贴执行;也可以把上游配置包降到匹配的大版本):");
1421
- const targets = [...new Set(problems.map((problem) => problem.target))];
1514
+ console.log("")
1515
+ warn(`以下依赖已安装,但版本与当前配置不匹配(${problems.length} 个):`)
1516
+ for (const problem of problems) console.log(` · ${problem.message}`)
1517
+ console.log("")
1518
+ warn("对齐命令(可整段粘贴执行;也可以把上游配置包降到匹配的大版本):")
1519
+ const targets = [...new Set(problems.map((problem) => problem.target))]
1422
1520
  console.log(
1423
1521
  ` ${addDevCommand(detectPackageManager())} ${targets.map(shellSafeSpec).join(" ")}`,
1424
- );
1522
+ )
1425
1523
  return problems.length
1426
1524
  }
1427
1525
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-code-style",
3
- "version": "1.8.5",
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
@@ -6,7 +6,6 @@ module.exports = {
6
6
  "stylelint-config-recommended-scss",
7
7
  "stylelint-config-recommended-vue/scss",
8
8
  "stylelint-config-html/vue",
9
- "stylelint-config-recess-order",
10
9
  ],
11
10
  plugins: ["stylelint-prettier"],
12
11
  ignoreFiles: [
@@ -21,14 +20,28 @@ module.exports = {
21
20
  {
22
21
  files: ["**/*.{vue,nvue,html}"],
23
22
  customSyntax: "postcss-html",
23
+ // 内联 style="..." 属性同时被 prettier(经 eslint-plugin-prettier 以 vue
24
+ // 解析器处理整份 SFC)格式化;stylelint 侧任何声明级 fixer(recess-order
25
+ // 重排、stylelint-prettier)对同一批内联属性都有独立主张,且 postcss-html
26
+ // 把属性内容 round-trip 时会有损(实测产生前导空格、丢失分号后空格),
27
+ // 两边对"正确形态"永远谈不拢——lint-staged 链 stylelint 最后执行,提交
28
+ // 产物永远 prettier-red,门禁无法收敛(下游 1.8.5 升级实测,BUG-031)。
29
+ // 因此 vue/html 交给 prettier 全权格式化:这里既关 stylelint-prettier,
30
+ // 也不启用 recess-order;<style> 块的格式化由 prettier CLI / eslint
31
+ // --fix 承担,stylelint 只保留下面 rules 里的语义规则。
32
+ rules: { "prettier/prettier": null },
24
33
  },
25
34
  {
26
35
  files: ["**/*.{css,scss}"],
27
36
  customSyntax: "postcss-scss",
37
+ // recess-order 只在纯样式文件生效(extends 在 lint 时惰性解析,
38
+ // 配置本体保持无 peer 可加载);vue/html 的内联属性不参与排序
39
+ extends: ["stylelint-config-recess-order"],
28
40
  },
29
41
  {
30
42
  files: ["**/*.less"],
31
43
  customSyntax: "postcss-less",
44
+ extends: ["stylelint-config-recess-order"],
32
45
  },
33
46
  ],
34
47
  rules: {
@@ -5,7 +5,6 @@ module.exports = {
5
5
  "stylelint-config-recommended",
6
6
  "stylelint-config-recommended-vue",
7
7
  "stylelint-config-html/vue",
8
- "stylelint-config-recess-order",
9
8
  ],
10
9
  plugins: ["stylelint-prettier"],
11
10
  ignoreFiles: [
@@ -20,10 +19,17 @@ module.exports = {
20
19
  {
21
20
  files: ["**/*.{vue,nvue,html}"],
22
21
  customSyntax: "postcss-html",
22
+ // 与统一入口(index.cjs)同理:内联 style="..." 属性归 prettier 管,
23
+ // stylelint 侧的声明级 fixer(recess-order / stylelint-prettier)对它
24
+ // 的改写经 postcss-html round-trip 会有损且与 prettier 主张冲突,
25
+ // lint-staged 链尾的 stylelint --fix 会把提交产物改成 prettier-red
26
+ // 形态(BUG-031)。vue/html 只保留语义规则。
27
+ rules: { "prettier/prettier": null },
23
28
  },
24
29
  {
25
30
  files: ["**/*.less"],
26
31
  customSyntax: "postcss-less",
32
+ extends: ["stylelint-config-recess-order"],
27
33
  },
28
34
  ],
29
35
  rules: {