code-quality
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCode Quality
代码质量
Production-grade code standards and review for TypeScript, Python, Go, and Rust.
适用于生产环境的TypeScript、Python、Go和Rust代码标准与审查规范。
When to Use
适用场景
- Writing or reviewing code in TS/Python/Go/Rust
- Code review or pull request analysis
- Security or performance audit
- Setting up linting/CI for a project
- Python-specific style check (PEP 8)
- 编写或审查TS/Python/Go/Rust代码
- 代码审查或拉取请求分析
- 安全性或性能审计
- 为项目配置Linting/CI
- 针对Python的专属风格检查(PEP 8)
Quick-Start Modes
快速启动模式
| Intent | Sections to Use |
|---|---|
| Write code | Core Rules + Language Standards + AI-Friendly Patterns |
| Review PR | Review Process + |
| Setup CI | Config Files + Scripts + Enforcement Strategy |
| Python style | |
Context loading: For deep reviews, read the relevant file for the language under review.
references/| 使用目的 | 需使用的章节 |
|---|---|
| 编写代码 | 核心规则 + 语言专属标准 + 适配AI的代码模式 |
| 审查PR | 审查流程 + |
| 配置CI | 配置文件 + 脚本 + 执行策略 |
| Python风格检查 | |
上下文加载: 如需深度审查,请阅读对应语言的文件。
references/Quick Reference
快速参考
| Language | Type Safety | Linter | Complexity |
|---|---|---|---|
| TypeScript | | ESLint + typescript-eslint | max 10 |
| Python | mypy | Ruff + mypy | max 10 |
| Go | staticcheck | golangci-lint | max 10 |
| Rust | clippy pedantic | clippy + cargo-audit | - |
| 语言 | 类型安全 | 代码检查工具 | 复杂度 |
|---|---|---|---|
| TypeScript | | ESLint + typescript-eslint | 最大值10 |
| Python | mypy | Ruff + mypy | 最大值10 |
| Go | staticcheck | golangci-lint | 最大值10 |
| Rust | clippy pedantic | clippy + cargo-audit | - |
Severity Levels
严重程度等级
| Level | Description | Action |
|---|---|---|
| Critical | Security vulnerabilities, data loss | Block merge |
| Error | Bugs, type violations, | Block merge |
| Warning | Code smells, complexity | Must address |
| Style | Formatting, naming | Auto-fix |
| 等级 | 描述 | 处理方式 |
|---|---|---|
| 严重(Critical) | 安全漏洞、数据丢失 | 阻止合并 |
| 错误(Error) | 程序缺陷、类型违规、使用 | 阻止合并 |
| 警告(Warning) | 代码异味、复杂度超标 | 必须处理 |
| 风格(Style) | 格式问题、命名规范 | 自动修复 |
Core Rules (All Languages)
核心规则(所有语言)
Type Safety
类型安全
- No implicit any / untyped functions
- No type assertions without guards
- Explicit return types on public APIs
- 禁止隐式any/无类型函数
- 无类型断言(除非有守卫检查)
- 公共API需显式声明返回类型
Security
安全性
- No hardcoded secrets (use gitleaks)
- No eval/pickle/unsafe deserialization
- Parameterized queries only
- SCA scanning (npm audit / pip-audit / govulncheck / cargo-audit)
- 禁止硬编码密钥(使用gitleaks)
- 禁止使用eval/pickle/不安全的反序列化
- 仅使用参数化查询
- 依赖项安全扫描(npm audit / pip-audit / govulncheck / cargo-audit)
Complexity
复杂度
- Max cyclomatic complexity: 10
- Max function lines: 50
- Max nesting depth: 3
- Max parameters: 5
- 圈复杂度最大值:10
- 函数行数最大值:50
- 嵌套深度最大值:3
- 参数数量最大值:5
Error Handling
错误处理
- No ignored errors (Go: no for err)
_ - No bare except (Python)
- No unwrap in prod (Rust)
- Wrap errors with context
- 禁止忽略错误(Go:禁止用接收err)
_ - Python禁止使用bare except
- Rust生产环境禁止使用unwrap
- 为错误添加上下文信息
Language-Specific Standards
各语言专属标准
TypeScript
TypeScript
See:
references/typescript.mdtypescript
// CRITICAL: Never use any
const bad: any = data; // Error
const good: unknown = data; // OK
// ERROR: No type assertions
const bad = data as User; // Error
const good = isUser(data) ? data : null; // OK
// ERROR: Non-null assertions
const bad = user!.name; // Error
const good = user?.name ?? ''; // OK参考:
references/typescript.mdtypescript
// 【严重问题】禁止使用any
const bad: any = data; // 错误
const good: unknown = data; // 合规
// 【错误】禁止类型断言
const bad = data as User; // 错误
const good = isUser(data) ? data : null; // 合规
// 【错误】禁止非空断言
const bad = user!.name; // 错误
const good = user?.name ?? ''; // 合规Python (PEP 8 / 3.11+)
Python(PEP 8 / 3.11+)
See:
references/python.mdpython
undefined参考:
references/python.mdpython
undefinedCRITICAL: All functions must be typed
【严重问题】所有函数必须声明类型
def bad(data): # Error
return data
def good(data: dict[str, Any]) -> list[str]: # OK
return list(data.keys())
def bad(data): # 错误
return data
def good(data: dict[str, Any]) -> list[str]: # 合规
return list(data.keys())
Use modern syntax
使用现代语法
value: str | None = None # OK (not Optional)
items: list[str] = [] # OK (not List)
undefinedvalue: str | None = None # 合规(不使用Optional)
items: list[str] = [] # 合规(不使用List)
undefinedGo
Go
See:
references/go.mdgo
// CRITICAL: Never ignore errors
result, _ := doSomething() // Error
result, err := doSomething() // OK
if err != nil {
return fmt.Errorf("doing something: %w", err)
}参考:
references/go.mdgo
// 【严重问题】禁止忽略错误
result, _ := doSomething() // 错误
result, err := doSomething() // 合规
if err != nil {
return fmt.Errorf("doing something: %w", err)
}Rust
Rust
See:
references/rust.mdrust
// CRITICAL: No unwrap in production
let value = data.unwrap(); // Error
let value = data?; // OK
let value = data.unwrap_or_default(); // OK参考:
references/rust.mdrust
// 【严重问题】生产环境禁止使用unwrap
let value = data.unwrap(); // 错误
let value = data?; // 合规
let value = data.unwrap_or_default(); // 合规Cross-Language Standards
跨语言标准
Structured Logging
结构化日志
See:
references/logging.mdtypescript
logger.info({ userId, action: 'login' }, 'User logged in'); // TS (pino)python
logger.info("user_login", user_id=user_id) # Python (structlog)go
log.Info().Str("user_id", userID).Msg("user logged in") // Go (zerolog)参考:
references/logging.mdtypescript
logger.info({ userId, action: 'login' }, 'User logged in'); // TS (pino)python
logger.info("user_login", user_id=user_id) // Python (structlog)go
log.Info().Str("user_id", userID).Msg("user logged in") // Go (zerolog)Test Coverage
测试覆盖率
See:
references/testing.md| Metric | Threshold |
|---|---|
| Line coverage | 80% min |
| Branch coverage | 70% min |
| New code | 90% min |
参考:
references/testing.md| 指标 | 阈值 |
|---|---|
| 行覆盖率 | 最低80% |
| 分支覆盖率 | 最低70% |
| 新增代码 | 最低90% |
Security Scanning
安全扫描
See:
references/security.md- Secrets: gitleaks (pre-commit + CI)
- Dependencies: npm audit / pip-audit / govulncheck / cargo-audit
- Accessibility: jsx-a11y (TypeScript)
- Race detection: go test -race (Go)
参考:
references/security.md- 密钥检测:gitleaks(pre-commit + CI)
- 依赖项扫描:npm audit / pip-audit / govulncheck / cargo-audit
- 可访问性:jsx-a11y(TypeScript)
- 竞态检测:go test -race(Go)
API Design
API设计
See:
references/api-design.md- Proper HTTP status codes (200, 201, 204, 400, 401, 403, 404, 422, 429, 500)
- RFC 7807 error format
- Plural nouns for resources:
/users/{id}/orders - Validate at API boundary
参考:
references/api-design.md- 使用标准HTTP状态码(200, 201, 204, 400, 401, 403, 404, 422, 429, 500)
- 遵循RFC 7807错误格式
- 资源使用复数名词:
/users/{id}/orders - 在API边界进行校验
Database Patterns
数据库模式
See:
references/database.md- Transactions for multi-write operations
- N+1 prevention: eager load or batch
- Safe migrations (expand-contract pattern)
- Always paginate list queries
参考:
references/database.md- 多写操作使用事务
- 避免N+1查询:预加载或批量查询
- 安全的迁移(扩展-收缩模式)
- 列表查询必须分页
Async & Concurrency
异步与并发
See:
references/async-concurrency.md- Always clean up resources (try/finally, defer, Drop)
- Set timeouts on all async operations
- Use semaphores for rate limiting
- Avoid blocking in async contexts
参考:
references/async-concurrency.md- 务必清理资源(try/finally, defer, Drop)
- 所有异步操作设置超时
- 使用信号量进行限流
- 避免在异步上下文里阻塞
Review Process
审查流程
Step 1: Understand Context
步骤1:理解上下文
- Identify the language/framework
- Understand the purpose of the code
- Check for existing patterns in the codebase
- Review any related tests
- 确定语言/框架
- 明确代码的用途
- 检查代码库中已有的模式
- 审查相关测试
Step 2: Systematic Review
步骤2:系统化审查
Use the checklist at for thorough reviews covering:
references/checklist.md- Code quality (structure, naming, type safety, dead code)
- Security (injection, auth, secrets, input validation)
- Performance (N+1, memory leaks, caching, re-renders)
- Error handling (edge cases, recovery, cleanup)
- Testing (coverage, quality, assertions)
- Best practices (SOLID, patterns, maintainability)
使用中的检查清单进行全面审查,涵盖:
references/checklist.md- 代码质量(结构、命名、类型安全、死代码)
- 安全性(注入、认证、密钥、输入校验)
- 性能(N+1查询、内存泄漏、缓存、重渲染)
- 错误处理(边缘情况、恢复、清理)
- 测试(覆盖率、质量、断言)
- 最佳实践(SOLID、设计模式、可维护性)
Step 3: Categorize & Report
步骤3:分类与报告
markdown
**[SEVERITY] Issue Title**
- File: `path/to/file.ts:line`
- Problem: Clear description
- Impact: What could go wrong
- Fix: Specific code suggestionmarkdown
**[严重级别] 问题标题**
- 文件:`path/to/file.ts:line`
- 问题:清晰描述
- 影响:可能导致的后果
- 修复方案:具体代码建议Git Integration
Git集成
bash
undefinedbash
undefinedReview staged changes
审查暂存的变更
git --no-pager diff --cached
git --no-pager diff --cached
Review specific commit
审查特定提交
git --no-pager show <commit>
git --no-pager show <commit>
Review PR diff
审查PR差异
gh pr diff <number>
undefinedgh pr diff <number>
undefinedReview Output Format
审查输出格式
Use severity levels from the table above (Critical / Error / Warning / Style).
markdown
undefined使用上述表格中的严重程度等级(Critical / Error / Warning / Style)。
markdown
undefinedCode Review Summary
代码审查总结
Overview
概述
- Files reviewed: X
- Issues found: Y (X Critical, Y Error, Z Warning)
- Recommendation: [Approve / Request Changes / Needs Discussion]
- 审查文件数:X
- 发现问题数:Y(X个严重问题,Y个错误,Z个警告)
- 建议:[批准 / 请求修改 / 需要讨论]
Critical Issues
严重问题
[Security vulnerabilities, data loss - must fix]
[安全漏洞、数据丢失 - 必须修复]
Error Issues
错误问题
[Bugs, type violations - must fix]
[程序缺陷、类型违规 - 必须修复]
Warnings
警告
[Code smells, complexity - should address]
[代码异味、复杂度超标 - 应处理]
Style
风格问题
[Formatting, naming - auto-fixable]
[格式、命名 - 可自动修复]
Positive Observations
积极发现
[Good practices found]
---[符合最佳实践的内容]
---Naming Conventions
命名规范
| Element | TypeScript | Python | Go | Rust |
|---|---|---|---|---|
| Variables | camelCase | snake_case | camelCase | snake_case |
| Functions | camelCase | snake_case | camelCase | snake_case |
| Constants | SCREAMING_SNAKE | SCREAMING_SNAKE | MixedCaps | SCREAMING_SNAKE |
| Types | PascalCase | PascalCase | PascalCase | PascalCase |
| Files | kebab-case | snake_case | lowercase | snake_case |
| 元素 | TypeScript | Python | Go | Rust |
|---|---|---|---|---|
| 变量 | camelCase | snake_case | camelCase | snake_case |
| 函数 | camelCase | snake_case | camelCase | snake_case |
| 常量 | SCREAMING_SNAKE | SCREAMING_SNAKE | MixedCaps | SCREAMING_SNAKE |
| 类型 | PascalCase | PascalCase | PascalCase | PascalCase |
| 文件 | kebab-case | snake_case | lowercase | snake_case |
AI-Friendly Patterns
适配AI的代码模式
- Explicit types always
- Single responsibility per function
- Small functions (< 30 lines ideal)
- Max nesting depth 3
- Guard clauses for early returns
- Named constants, no magic values
- Linear, predictable execution flow
- 始终使用显式类型
- 单一职责原则(每个函数仅负责一件事)
- 函数尽量短小(理想情况下少于30行)
- 嵌套深度最大值3
- 使用守卫语句提前返回
- 使用命名常量,禁止魔法值
- 线性、可预测的执行流程
Enforcement Strategy
执行策略
Progressive (Ratchet-Based)
渐进式(基于棘轮机制)
Phase 1: Errors block, Warnings tracked
Phase 2: Strict on NEW files only
Phase 3: Strict on TOUCHED files
Phase 4: Full enforcement阶段1:错误阻止合并,警告仅追踪
阶段2:仅对新文件严格执行
阶段3:仅对修改过的文件严格执行
阶段4:全面强制执行WIP vs Merge Mode
WIP与合并模式
| Mode | Trigger | Behavior |
|---|---|---|
| WIP | Local commit | Warnings only |
| Push | git push | Errors block |
| PR | PR to main | Full strict |
| 模式 | 触发条件 | 行为 |
|---|---|---|
| WIP | 本地提交 | 仅显示警告 |
| 推送 | git push | 错误阻止推送 |
| PR | 合并到主分支的PR | 全面严格执行 |
Config Files
配置文件
Available in :
configs/- - ESLint, tsconfig, Prettier
typescript/ - - pyproject.toml, pre-commit
python/ - - golangci.yaml
go/ - - clippy.toml
rust/ .pre-commit-config.yaml.gitleaks.toml
位于目录下:
configs/- - ESLint, tsconfig, Prettier
typescript/ - - pyproject.toml, pre-commit
python/ - - golangci.yaml
go/ - - clippy.toml
rust/ .pre-commit-config.yaml.gitleaks.toml
Scripts
脚本
Available in :
scripts/- - Monorepo-aware incremental linting
check_changed.sh - - Full repository check
check_all.sh - - Python full check (ruff + pycodestyle + mypy)
check_style.py - - Quick PEP 8 only
check_pep8.sh - - Python type hints only
check_types.sh - - Python auto-fix issues
fix_style.sh
位于目录下:
scripts/- - 支持Monorepo的增量Linting检查
check_changed.sh - - 全仓库检查
check_all.sh - - Python全面检查(ruff + pycodestyle + mypy)
check_style.py - - 快速PEP 8检查
check_pep8.sh - - 仅检查Python类型提示
check_types.sh - - 自动修复Python风格问题
fix_style.sh