三、代码管理与规范化
3.1 Git分支策略
# Git Flow 简化版 - 分支命名规范
# 主分支
main # 生产环境代码,只能通过PR合并
develop # 开发主分支,集成最新功能
# 临时分支
feature/* # 功能分支,从develop切出,合并回develop
bugfix/* # Bug修复分支,从develop或main切出
hotfix/* # 紧急修复分支,从main切出,合并回main和develop
release/* # 发布分支,从develop切出,合并回main和develop
# 分支生命周期示例
# 1. 创建功能分支
git checkout -b feature/user-authentication develop
# 2. 开发完成后推送到远程
git push -u origin feature/user-authentication
# 3. 创建Pull Request到develop
# 4. 合并后删除功能分支
git branch -d feature/user-authentication
3.2 Commit规范
# .git/hooks/commit-msg - Commit消息格式检查
#!/bin/bash
# Commit格式: <type>(<scope>): <subject>
# type: feat, fix, docs, style, refactor, test, chore
# scope: 可选,表示影响的模块
# subject: 简短描述,不超过50字符
commit_regex='^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .{1,50}$'
if ! grep -qE "$commit_regex" "$1"; then
echo "错误: Commit消息格式不正确"
echo "格式: <type>(<scope>): <subject>"
echo "示例: feat(auth): 添加JWT认证"
echo " fix(order): 修复订单金额计算错误"
exit 1
fi
# Commit规范详解
## Type类型说明
| Type | 说明 | 示例 |
|------|------|------|
| feat | 新功能 | feat(user): 添加用户注册功能 |
| fix | Bug修复 | fix(payment): 修复支付回调签名验证 |
| docs | 文档更新 | docs: 更新API文档 |
| style | 代码格式 | style: 使用black格式化代码 |
| refactor | 重构 | refactor(order): 重构订单状态机 |
| test | 测试相关 | test: 添加订单服务单元测试 |
| chore | 构建/工具 | chore: 升级依赖版本 |
## 详细Commit示例
feat(cart): 支持购物车商品批量删除
- 新增批量删除API端点 DELETE /api/cart/batch
- 支持按商品ID列表删除
- 添加批量删除的事务处理
- 单元测试覆盖批量删除场景
Closes #123
3.3 代码格式化与Linting
# pyproject.toml - 统一的代码规范配置
[tool.black]
line-length = 100
target-version = ['py311']
include = '\.pyi?$'
extend-exclude = '''
/(
\.eggs
| \.git
| \.venv
| \.mypy_cache
| \.pytest_cache
| build
| dist
)/
'''
[tool.isort]
profile = "black"
line_length = 100
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
use_parentheses = true
ensure_newline_before_comments = true
lines_between_types = 1
[tool.ruff]
line-length = 100
select = [
"E", # pycodestyle errors
"W", # pycodestyle warnings
"F", # pyflakes
"I", # isort
"C", # flake8-comprehensions
"B", # flake8-bugbear
"UP", # pyupgrade
"RUF", # ruff-specific rules
]
ignore = [
"E501", # line too long, handled by black
"B008", # do not perform function calls in argument defaults
]
[tool.mypy]
python_version = "3.11"
warn_return_any = true
warn_unused_configs = true
warn_unused_ignores = true
disallow_untyped_defs = true
disallow_any_unimported = true
no_implicit_optional = true
strict_equality = true
warn_redundant_casts = true
warn_unreachable = true
follow_imports = "silent"
[tool.pytest.ini_options]
minversion = "7.0"
addopts = [
"-ra",
"-q",
"--strict-markers",
"--strict-config",
"--cov=src",
"--cov-report=term-missing",
"--cov-report=html",
"--cov-fail-under=80",
]
testpaths = ["tests"]
markers = [
"slow: marks tests as slow",
"integration: marks tests as integration tests",
"unit: marks tests as unit tests",
]
# .pre-commit-config.yaml - Git提交前自动检查
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-json
- id: check-added-large-files
args: ['--maxkb=500']
- id: detect-private-key
- id: check-case-conflict
- id: check-merge-conflict
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.280
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
language_version: python3.11
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
name: isort
args: ["--profile", "black"]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.4.1
hooks:
- id: mypy
additional_dependencies: [types-all]
args: [--ignore-missing-imports]
- repo: local
hooks:
- id: pytest
name: pytest
entry: pytest
language: system
pass_filenames: false
always_run: true
args: ["-m", "not slow"] # 跳过慢速测试
3.4 PR规范与Code Review流程
# .github/pull_request_template.md
## 变更描述
<!-- 请简要描述本次PR的变更内容 -->
## 变更类型
- [ ] 新功能 (feat)
- [ ] Bug修复 (fix)
- [ ] 重构 (refactor)
- [ ] 文档更新 (docs)
- [ ] 测试相关 (test)
- [ ] 构建/工具 (chore)
## 测试
- [ ] 单元测试通过
- [ ] 集成测试通过
- [ ] 手动测试完成
## 检查清单
- [ ] 代码遵循项目规范(black/ruff/isort)
- [ ] 添加/更新了必要的测试
- [ ] 更新了相关文档
- [ ] 无敏感信息泄露(密钥、密码等)
- [ ] 性能影响评估(如有)
## 关联Issue
Closes #
## 截图(如适用)
<!-- 添加UI变更的截图 -->
## 额外说明
<!-- 其他需要reviewer关注的信息 -->
# .github/workflows/pr-checks.yml
name: PR Quality Checks
on:
pull_request:
types: [opened, synchronize, reopened]
branches: [main, develop]
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Cache dependencies
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${
{ runner.os }}-pip-${
{ hashFiles('pyproject.toml') }}
- name: Install dependencies
run: |
pip install poetry
poetry config virtualenvs.create false
poetry install --with dev
- name: Check commit messages
run: |
# 检查PR中的所有commit是否符合规范
for commit in $(git rev-list origin/${
{ github.base_ref }}..HEAD); do
if ! git log -1 --format=%s $commit | grep -qE '^(feat|fix|docs|style|refactor|test|chore)(\(.+\))?: .+'; then
echo "❌ Commit $commit message format invalid"
exit 1
fi
done
- name: Run linters
run: |
ruff check src/
black --check src/
isort --check-only src/
- name: Type check
run: mypy src/
- name: Run tests
run: pytest --cov=src --cov-fail-under=80
- name: Check code coverage threshold
run: |
coverage report --fail-under=80