code-quality

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code 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

快速启动模式

IntentSections to Use
Write codeCore Rules + Language Standards + AI-Friendly Patterns
Review PRReview Process +
references/checklist.md
+ Severity Levels
Setup CIConfig Files + Scripts + Enforcement Strategy
Python style
references/python.md
(full PEP 8 deep-dive)
Context loading: For deep reviews, read the relevant
references/
file for the language under review.
使用目的需使用的章节
编写代码核心规则 + 语言专属标准 + 适配AI的代码模式
审查PR审查流程 +
references/checklist.md
+ 严重程度等级
配置CI配置文件 + 脚本 + 执行策略
Python风格检查
references/python.md
(完整PEP 8深度解析)
上下文加载: 如需深度审查,请阅读对应语言的
references/
文件。

Quick Reference

快速参考

LanguageType SafetyLinterComplexity
TypeScript
strict
, no
any
ESLint + typescript-eslintmax 10
Pythonmypy
strict
, PEP 484
Ruff + mypymax 10
Gostaticcheckgolangci-lintmax 10
Rustclippy pedanticclippy + cargo-audit-
语言类型安全代码检查工具复杂度
TypeScript
strict
,禁止使用
any
ESLint + typescript-eslint最大值10
Pythonmypy
strict
,PEP 484
Ruff + mypy最大值10
Gostaticcheckgolangci-lint最大值10
Rustclippy pedanticclippy + cargo-audit-

Severity Levels

严重程度等级

LevelDescriptionAction
CriticalSecurity vulnerabilities, data lossBlock merge
ErrorBugs, type violations,
any
Block merge
WarningCode smells, complexityMust address
StyleFormatting, namingAuto-fix

等级描述处理方式
严重(Critical)安全漏洞、数据丢失阻止合并
错误(Error)程序缺陷、类型违规、使用
any
阻止合并
警告(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.md
typescript
// 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.md
typescript
// 【严重问题】禁止使用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.md
python
undefined
参考:
references/python.md
python
undefined

CRITICAL: 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)
undefined
value: str | None = None # 合规(不使用Optional) items: list[str] = [] # 合规(不使用List)
undefined

Go

Go

See:
references/go.md
go
// CRITICAL: Never ignore errors
result, _ := doSomething()       // Error
result, err := doSomething()     // OK
if err != nil {
    return fmt.Errorf("doing something: %w", err)
}
参考:
references/go.md
go
// 【严重问题】禁止忽略错误
result, _ := doSomething()       // 错误
result, err := doSomething()     // 合规
if err != nil {
    return fmt.Errorf("doing something: %w", err)
}

Rust

Rust

See:
references/rust.md
rust
// CRITICAL: No unwrap in production
let value = data.unwrap();        // Error
let value = data?;                // OK
let value = data.unwrap_or_default(); // OK

参考:
references/rust.md
rust
// 【严重问题】生产环境禁止使用unwrap
let value = data.unwrap();        // 错误
let value = data?;                // 合规
let value = data.unwrap_or_default(); // 合规

Cross-Language Standards

跨语言标准

Structured Logging

结构化日志

See:
references/logging.md
typescript
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.md
typescript
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
MetricThreshold
Line coverage80% min
Branch coverage70% min
New code90% 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:理解上下文

  1. Identify the language/framework
  2. Understand the purpose of the code
  3. Check for existing patterns in the codebase
  4. Review any related tests
  1. 确定语言/框架
  2. 明确代码的用途
  3. 检查代码库中已有的模式
  4. 审查相关测试

Step 2: Systematic Review

步骤2:系统化审查

Use the checklist at
references/checklist.md
for thorough reviews covering:
  • 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 suggestion
markdown
**[严重级别] 问题标题**
- 文件:`path/to/file.ts:line`
- 问题:清晰描述
- 影响:可能导致的后果
- 修复方案:具体代码建议

Git Integration

Git集成

bash
undefined
bash
undefined

Review 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>
undefined
gh pr diff <number>
undefined

Review Output Format

审查输出格式

Use severity levels from the table above (Critical / Error / Warning / Style).
markdown
undefined
使用上述表格中的严重程度等级(Critical / Error / Warning / Style)。
markdown
undefined

Code 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

命名规范

ElementTypeScriptPythonGoRust
VariablescamelCasesnake_casecamelCasesnake_case
FunctionscamelCasesnake_casecamelCasesnake_case
ConstantsSCREAMING_SNAKESCREAMING_SNAKEMixedCapsSCREAMING_SNAKE
TypesPascalCasePascalCasePascalCasePascalCase
Fileskebab-casesnake_caselowercasesnake_case
元素TypeScriptPythonGoRust
变量camelCasesnake_casecamelCasesnake_case
函数camelCasesnake_casecamelCasesnake_case
常量SCREAMING_SNAKESCREAMING_SNAKEMixedCapsSCREAMING_SNAKE
类型PascalCasePascalCasePascalCasePascalCase
文件kebab-casesnake_caselowercasesnake_case

AI-Friendly Patterns

适配AI的代码模式

  1. Explicit types always
  2. Single responsibility per function
  3. Small functions (< 30 lines ideal)
  4. Max nesting depth 3
  5. Guard clauses for early returns
  6. Named constants, no magic values
  7. Linear, predictable execution flow
  1. 始终使用显式类型
  2. 单一职责原则(每个函数仅负责一件事)
  3. 函数尽量短小(理想情况下少于30行)
  4. 嵌套深度最大值3
  5. 使用守卫语句提前返回
  6. 使用命名常量,禁止魔法值
  7. 线性、可预测的执行流程

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与合并模式

ModeTriggerBehavior
WIPLocal commitWarnings only
Pushgit pushErrors block
PRPR to mainFull strict
模式触发条件行为
WIP本地提交仅显示警告
推送git push错误阻止推送
PR合并到主分支的PR全面严格执行

Config Files

配置文件

Available in
configs/
:
  • typescript/
    - ESLint, tsconfig, Prettier
  • python/
    - pyproject.toml, pre-commit
  • go/
    - golangci.yaml
  • rust/
    - clippy.toml
  • .pre-commit-config.yaml
  • .gitleaks.toml
位于
configs/
目录下:
  • typescript/
    - ESLint, tsconfig, Prettier
  • python/
    - pyproject.toml, pre-commit
  • go/
    - golangci.yaml
  • rust/
    - clippy.toml
  • .pre-commit-config.yaml
  • .gitleaks.toml

Scripts

脚本

Available in
scripts/
:
  • check_changed.sh
    - Monorepo-aware incremental linting
  • check_all.sh
    - Full repository check
  • check_style.py
    - Python full check (ruff + pycodestyle + mypy)
  • check_pep8.sh
    - Quick PEP 8 only
  • check_types.sh
    - Python type hints only
  • fix_style.sh
    - Python auto-fix issues
位于
scripts/
目录下:
  • check_changed.sh
    - 支持Monorepo的增量Linting检查
  • check_all.sh
    - 全仓库检查
  • check_style.py
    - Python全面检查(ruff + pycodestyle + mypy)
  • check_pep8.sh
    - 快速PEP 8检查
  • check_types.sh
    - 仅检查Python类型提示
  • fix_style.sh
    - 自动修复Python风格问题