ln-742-precommit-setup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ln-742-precommit-setup

ln-742-precommit-setup

Type: L3 Worker Category: 7XX Project Bootstrap Parent: ln-740-quality-setup
Sets up Git hooks for automated code quality enforcement before commits.

类型: L3 工作流 分类: 7XX 项目初始化 父级任务: ln-740-quality-setup
为Git仓库配置提交前自动代码质量检查钩子。

Purpose & Scope

目标与范围

Does:
  • Installs hook management tools (Husky or pre-commit)
  • Configures staged file linting (lint-staged or pre-commit hooks)
  • Sets up commit message validation (commitlint)
  • Verifies hooks trigger correctly
Does NOT:
  • Configure linters themselves (ln-741 does this)
  • Set up test infrastructure (ln-743 does this)
  • Modify source code

实现功能:
  • 安装钩子管理工具(Husky 或 pre-commit)
  • 配置暂存文件检查(lint-staged 或 pre-commit 钩子)
  • 设置提交消息验证(commitlint)
  • 验证钩子能否正确触发
不包含功能:
  • 配置检查器本身(由ln-741完成)
  • 设置测试基础设施(由ln-743完成)
  • 修改源代码

Supported Stacks

支持的技术栈

TechnologyHook ManagerStaged LintingCommit Validation
Node.jsHuskylint-stagedcommitlint
Pythonpre-commitpre-commit hookspre-commit hook
MixedBoth (if needed)Stack-specificcommitlint

技术栈钩子管理器暂存文件检查提交消息验证
Node.jsHuskylint-stagedcommitlint
Pythonpre-commitpre-commit 钩子pre-commit 钩子
混合栈两者(如有需要)基于技术栈选择commitlint

Phase 1: Check Existing Hooks

阶段1:检查现有钩子配置

Before installing, check for existing hook configurations.
Files to Check:
ToolIndicators
Husky
.husky/
directory,
husky
in package.json
pre-commit
.pre-commit-config.yaml
lint-staged
lint-staged
in package.json or
.lintstagedrc*
commitlint
commitlint.config.*
,
.commitlintrc*
Decision Logic:
  1. If hooks exist and working: SKIP (inform user)
  2. If partial setup: ASK user to complete or replace
  3. If no hooks: CREATE from templates

安装前,先检查是否已有钩子配置。
需检查的文件:
工具标识文件
Husky
.husky/
目录、package.json 中的 husky 依赖
pre-commit
.pre-commit-config.yaml
lint-stagedpackage.json 中的 lint-staged 或
.lintstagedrc*
文件
commitlint
commitlint.config.*
.commitlintrc*
决策逻辑:
  1. 若钩子已存在且正常工作:跳过(通知用户)
  2. 若仅部分配置:询问用户是补全还是替换
  3. 若无钩子配置:基于模板创建

Phase 2: Install Hook Manager

阶段2:安装钩子管理器

Node.js Projects (Husky)

Node.js 项目(使用Husky)

bash
npm install -D husky
npx husky init
This creates:
  • .husky/
    directory
  • .husky/pre-commit
    hook file
  • Adds
    prepare
    script to package.json
bash
npm install -D husky
npx husky init
此命令会创建:
  • .husky/
    目录
  • .husky/pre-commit
    钩子文件
  • 在 package.json 中添加
    prepare
    脚本

Python Projects (pre-commit)

Python 项目(使用pre-commit)

bash
pip install pre-commit
bash
pip install pre-commit

OR with uv:

或使用uv:

uv add --dev pre-commit
pre-commit install

This creates:
- `.git/hooks/pre-commit` (managed by pre-commit)
- Requires `.pre-commit-config.yaml` for configuration

---
uv add --dev pre-commit
pre-commit install

此命令会创建:
- `.git/hooks/pre-commit`(由pre-commit管理)
- 需要 `.pre-commit-config.yaml` 文件进行配置

---

Phase 3: Configure Staged Linting

阶段3:配置暂存文件检查

Node.js (lint-staged)

Node.js(使用lint-staged)

bash
npm install -D lint-staged
Create configuration (
.lintstagedrc.mjs
or in package.json):
Key Rules:
  • TypeScript files: ESLint + Prettier
  • JSON/MD/CSS: Prettier only
  • C# files: dotnet format (if mixed project)
CRITICAL FIX: For .NET files, use correct syntax:
"*.cs": "dotnet format --include"
is WRONG Use:
"*.cs": "dotnet format whitespace --include"
or run dotnet format separately
bash
npm install -D lint-staged
创建配置文件(
.lintstagedrc.mjs
或在 package.json 中配置):
关键规则:
  • TypeScript 文件:ESLint + Prettier
  • JSON/MD/CSS 文件:仅使用 Prettier
  • C# 文件:dotnet format(若为混合项目)
重要修复: 对于.NET文件,需使用正确语法:
"*.cs": "dotnet format --include"
是错误的 应使用:
"*.cs": "dotnet format whitespace --include"
或单独运行 dotnet format

Python (pre-commit hooks)

Python(使用pre-commit钩子)

Configuration in
.pre-commit-config.yaml
:
yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.8.0
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

配置文件在
.pre-commit-config.yaml
中:
yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.8.0
    hooks:
      - id: ruff
        args: [--fix]
      - id: ruff-format

Phase 4: Configure Commit Message Validation

阶段4:配置提交消息验证

Node.js (commitlint)

Node.js(使用commitlint)

bash
npm install -D @commitlint/cli @commitlint/config-conventional
Create
commitlint.config.mjs
with:
  • Conventional Commits format
  • Allowed types: feat, fix, docs, style, refactor, test, chore, ci
  • Max header length: 100 characters
bash
npm install -D @commitlint/cli @commitlint/config-conventional
创建
commitlint.config.mjs
文件,包含:
  • 符合 Conventional Commits 格式
  • 允许的类型:feat、fix、docs、style、refactor、test、chore、ci
  • 提交标题最大长度:100字符

Update Husky hook

更新Husky钩子

Add commit-msg hook:
bash
echo 'npx --no -- commitlint --edit "$1"' > .husky/commit-msg
添加 commit-msg 钩子:
bash
echo 'npx --no -- commitlint --edit "$1"' > .husky/commit-msg

Python (pre-commit hook for commit message)

Python(使用pre-commit钩子验证提交消息)

Add to
.pre-commit-config.yaml
:
yaml
  - repo: https://github.com/compilerla/conventional-pre-commit
    rev: v3.4.0
    hooks:
      - id: conventional-pre-commit
        stages: [commit-msg]

添加到
.pre-commit-config.yaml
yaml
  - repo: https://github.com/compilerla/conventional-pre-commit
    rev: v3.4.0
    hooks:
      - id: conventional-pre-commit
        stages: [commit-msg]

Phase 5: Test Hooks

阶段5:测试钩子

Verify hooks work correctly.
Test 1: Lint-staged triggers
bash
undefined
验证钩子能否正常工作。
测试1:触发lint-staged
bash
undefined

Create a file with lint issues

创建一个包含检查问题的文件

echo "const x=1" > test-file.ts git add test-file.ts git commit -m "test: verify hooks"
echo "const x=1" > test-file.ts git add test-file.ts git commit -m "test: verify hooks"

Expected: lint-staged runs, either fixes or blocks

预期结果:lint-staged 运行,自动修复问题或阻止提交


**Test 2: Commit message validation**
```bash
git commit --allow-empty -m "bad message"

**测试2:提交消息验证**
```bash
git commit --allow-empty -m "bad message"

Expected: commitlint rejects

预期结果:commitlint 拒绝提交

git commit --allow-empty -m "test: valid message format"
git commit --allow-empty -m "test: valid message format"

Expected: commit succeeds

预期结果:提交成功


**Cleanup:**
```bash
rm test-file.ts
git reset HEAD~1  # If test commit was made


**清理操作:**
```bash
rm test-file.ts
git reset HEAD~1  # 若已创建测试提交

Critical Rules

关键规则

RULE 1: Husky requires Git repository (
git init
first).
RULE 2: lint-staged MUST have linters configured first (run ln-741 before ln-742).
RULE 3: Document
--no-verify
escape hatch for emergency commits.
RULE 4: pre-commit hooks should auto-fix when possible (
--fix
flag).

规则1: Husky 需要 Git 仓库(需先执行
git init
)。
规则2: lint-staged 必须先配置好检查器(先运行ln-741再运行ln-742)。
规则3: 需记录
--no-verify
参数,用于紧急提交时跳过钩子。
规则4: pre-commit 钩子应尽可能自动修复问题(使用
--fix
参数)。

Definition of Done

完成标准

  • Hook manager installed (Husky or pre-commit)
  • Staged linting configured and working
  • Commit message validation configured
  • Test commit triggers hooks correctly
  • User informed of:
    • How hooks work
    • How to skip hooks in emergency (
      git commit --no-verify
      )
    • Commit message format required

  • 已安装钩子管理器(Husky 或 pre-commit)
  • 已配置暂存文件检查且可正常工作
  • 已配置提交消息验证
  • 测试提交可正确触发钩子
  • 已告知用户:
    • 钩子的工作方式
    • 紧急情况下如何跳过钩子(
      git commit --no-verify
    • 要求的提交消息格式

Reference Files

参考文件

FilePurpose
husky_precommit_template.shHusky pre-commit hook
husky_commitmsg_template.shHusky commit-msg hook
lintstaged_template.mjslint-staged configuration
commitlint_template.mjscommitlint configuration
precommit_config_template.yamlPython pre-commit config
hooks_guide.mdDetailed hooks guide

文件用途
husky_precommit_template.shHusky pre-commit 钩子模板
husky_commitmsg_template.shHusky commit-msg 钩子模板
lintstaged_template.mjslint-staged 配置模板
commitlint_template.mjscommitlint 配置模板
precommit_config_template.yamlPython pre-commit 配置模板
hooks_guide.md钩子详细指南

Error Handling

错误处理

ErrorCauseResolution
Husky not runningMissing prepare scriptRun
npx husky init
again
lint-staged failsMissing linterRun ln-741 first
pre-commit not foundNot in PATH
pip install pre-commit
Hooks not triggeringGit hooks disabledCheck
.git/hooks/
permissions
Windows path issuesShell script formatUse cross-platform syntax

错误原因解决方法
Husky 未运行缺少 prepare 脚本重新运行
npx husky init
lint-staged 执行失败缺少检查器先运行 ln-741
pre-commit 未找到不在系统PATH中执行
pip install pre-commit
钩子未触发Git 钩子被禁用检查
.git/hooks/
目录权限
Windows 路径问题Shell 脚本格式错误使用跨平台语法

Emergency Bypass

紧急跳过方式

Document for users:
bash
undefined
告知用户:
bash
undefined

Skip all hooks (use sparingly!)

跳过所有钩子(谨慎使用!)

git commit --no-verify -m "emergency: bypass hooks"
git commit --no-verify -m "emergency: bypass hooks"

Skip only pre-commit (keeps commit-msg)

仅跳过pre-commit钩子(保留commit-msg验证)

HUSKY=0 git commit -m "fix: urgent hotfix"

---

**Version:** 2.0.0
**Last Updated:** 2026-01-10
HUSKY=0 git commit -m "fix: urgent hotfix"

---

**版本:** 2.0.0
**最后更新时间:** 2026-01-10