code-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Code Review Skill

代码审查技能

Perform automated code reviews on GitLab merge requests with multi-category analysis and structured summary reports. Automatically generates an HTML report with professional styling for easy reading and sharing.
对GitLab合并请求执行自动化代码审查,支持多类别分析并生成结构化总结报告。自动生成带有专业样式的HTML报告,便于阅读和分享。

Output

输出

After completing the review, the skill automatically saves an HTML report:
  • Filename:
    code-review-{MR-number}.html
    in the current directory
  • Features:
    • Color-coded severity levels (🔴 critical, 🟡 warning, 🔵 suggestion, 🟢 positive)
    • Syntax-highlighted code snippets
    • Summary statistics at the top
    • Responsive design for easy reading on any device
完成审查后,本技能会自动保存一份HTML报告:
  • 文件名: 当前目录下的
    code-review-{MR-number}.html
  • 特性:
    • 按严重程度颜色编码(🔴 关键,🟡 警告,🔵 建议,🟢 好评)
    • 语法高亮的代码片段
    • 顶部的汇总统计信息
    • 响应式设计,适配各类设备阅读

Prerequisites

前提条件

This skill requires the
gitlab-code-review
MCP server to fetch merge request data automatically.
Setup: Run
install.sh
after installing the skill - it will prompt for your GitLab token and configure the MCP server automatically.
Manual setup: See
code-review/mcp-server/README.md
本技能需要
gitlab-code-review
MCP服务器来自动获取合并请求数据。
设置: 安装技能后运行
install.sh
- 它会提示您输入GitLab令牌并自动配置MCP服务器。
手动设置: 查看
code-review/mcp-server/README.md

When to Use This Skill

使用场景

  • "/code-review"
  • "/code-review <url>"
  • "code review"
  • "review this MR"
  • "review merge request"

  • "/code-review"
  • "/code-review <url>"
  • "code review"
  • "review this MR"
  • "review merge request"

Commands

命令

CommandDescription
/code-review
Activate skill and prompt for a GitLab merge request URL
/code-review <url>
Start review with the provided GitLab merge request URL
code review
Natural language trigger to activate the skill
review this MR
Natural language trigger to activate the skill
review merge request
Natural language trigger to activate the skill

命令描述
/code-review
激活技能并提示输入GitLab合并请求URL
/code-review <url>
使用提供的GitLab合并请求URL启动审查
code review
自然语言触发,激活技能
review this MR
自然语言触发,激活技能
review merge request
自然语言触发,激活技能

GitLab Merge Request URL Pattern

GitLab合并请求URL格式

The skill accepts GitLab merge request URLs following this pattern:
https://<gitlab-host>/<group>/<project>/-/merge_requests/<id>
本技能接受符合以下格式的GitLab合并请求URL:
https://<gitlab-host>/<group>/<project>/-/merge_requests/<id>

URL Components

URL组件

ComponentDescriptionExample
gitlab-host
The GitLab instance domain
gitlab.com
,
gitlab.example.com
group
Project group or namespace (supports nested paths)
myteam
,
org/subgroup
project
Repository name
my-project
id
Merge request number (numeric)
123
组件描述示例
gitlab-host
GitLab实例域名
gitlab.com
,
gitlab.example.com
group
项目组或命名空间(支持嵌套路径)
myteam
,
org/subgroup
project
仓库名称
my-project
id
合并请求编号(数字)
123

Supported URL Formats

支持的URL格式

Simple project path:
https://gitlab.com/mygroup/myproject/-/merge_requests/123
Nested group path (group/subgroup/project):
https://gitlab.com/org/team/subgroup/myproject/-/merge_requests/456
Self-hosted GitLab:
https://gitlab.company.io/engineering/backend/-/merge_requests/789
简单项目路径:
https://gitlab.com/mygroup/myproject/-/merge_requests/123
嵌套组路径(group/subgroup/project):
https://gitlab.com/org/team/subgroup/myproject/-/merge_requests/456
自托管GitLab:
https://gitlab.company.io/engineering/backend/-/merge_requests/789

Parsing Rules

解析规则

  1. The URL must be a valid HTTPS URL
  2. The URL must contain the
    /-/merge_requests/
    path segment
  3. The merge request ID must be a positive integer
  4. The project path is extracted as everything between the host and
    /-/merge_requests/
  5. Nested group paths are fully supported (e.g.,
    group/subgroup/project
    )
  1. URL必须是有效的HTTPS链接
  2. URL必须包含
    /-/merge_requests/
    路径段
  3. 合并请求ID必须是正整数
  4. 项目路径提取为域名和
    /-/merge_requests/
    之间的所有内容
  5. 完全支持嵌套组路径(例如:
    group/subgroup/project

Extracted Components

提取的组件

When parsing a valid URL, the skill extracts:
  • host: The GitLab instance domain (e.g.,
    gitlab.com
    )
  • projectPath: The full path to the project including groups (e.g.,
    org/team/myproject
    )
  • mergeRequestId: The numeric MR identifier (e.g.,
    123
    )
解析有效URL时,技能会提取以下信息:
  • host:GitLab实例域名(例如:
    gitlab.com
  • projectPath:包含组的完整项目路径(例如:
    org/team/myproject
  • mergeRequestId:数字格式的MR标识符(例如:
    123

URL Validation and Error Handling

URL验证与错误处理

The skill validates URLs and provides clear error messages for invalid inputs:
Error ConditionError Message
Empty or missing URL"Please provide a GitLab merge request URL."
Malformed URL (not a valid URL format)"The provided URL is not valid. Expected format:
https://<gitlab-host>/<group>/<project>/-/merge_requests/<id>
"
Non-GitLab URL (e.g., GitHub, Bitbucket)"Only GitLab merge request URLs are supported. Please provide a URL from a GitLab instance."
Missing
/-/merge_requests/
segment
"The URL does not appear to be a GitLab merge request. Ensure the URL contains
/-/merge_requests/
."
Non-numeric merge request ID"The merge request ID must be a number. Found invalid ID in URL."
Validation Order:
  1. Check if URL is provided (not empty)
  2. Validate URL format (must be a valid HTTPS URL)
  3. Verify the URL is from a GitLab instance (contains
    /-/merge_requests/
    )
  4. Extract and validate the merge request ID (must be numeric)

技能会验证URL,并为无效输入提供清晰的错误提示:
错误条件错误提示
URL为空或缺失"请提供GitLab合并请求URL。"
URL格式错误(非有效URL)"提供的URL无效。预期格式:
https://<gitlab-host>/<group>/<project>/-/merge_requests/<id>
"
非GitLab URL(如GitHub、Bitbucket)"仅支持GitLab合并请求URL。请提供来自GitLab实例的链接。"
缺少
/-/merge_requests/
路径段
"该URL并非GitLab合并请求链接。请确保URL包含
/-/merge_requests/
。"
合并请求ID非数字"合并请求ID必须为数字。在URL中发现无效ID。"
验证顺序:
  1. 检查是否提供了URL(非空)
  2. 验证URL格式(必须是有效的HTTPS URL)
  3. 验证URL来自GitLab实例(包含
    /-/merge_requests/
  4. 提取并验证合并请求ID(必须为数字)

Workflow

工作流程

The code review process follows these steps:
代码审查流程遵循以下步骤:

Step 1: Command Recognition and URL Extraction

步骤1:命令识别与URL提取

When you invoke the skill using
/code-review
,
/code-review <url>
, or natural language triggers like "review this MR", the skill activates and checks if a URL was provided. If no URL is included, you will be prompted to provide one.
当您使用
/code-review
/code-review <url>
或自然语言触发词(如"review this MR")调用技能时,技能会激活并检查是否提供了URL。如果未包含URL,会提示您提供。

Step 2: URL Validation and Parsing

步骤2:URL验证与解析

The provided URL is validated against the GitLab merge request pattern. The skill extracts:
  • Host (GitLab instance domain)
  • Project path (including any nested groups)
  • Merge request ID
If validation fails, a clear error message explains what went wrong and the expected format.
提供的URL会与GitLab合并请求格式进行验证。技能会提取:
  • 主机(GitLab实例域名)
  • 项目路径(包含所有嵌套组)
  • 合并请求ID
如果验证失败,会显示清晰的错误信息说明问题及预期格式。

Step 3: Guide User to Fetch Diff Content

步骤3:引导用户获取差异内容

Once the URL is validated, the skill provides instructions for retrieving the merge request data:
  • How to access the diff via GitLab web interface or API
  • What information to provide (title, description, changed files)
  • Troubleshooting tips if access issues occur
See the How to Retrieve Merge Request Data section below for detailed instructions.
URL验证通过后,技能会提供获取合并请求数据的说明:
  • 如何通过GitLab网页界面或API获取差异
  • 需要提供的信息(标题、描述、变更文件)
  • 访问问题的故障排除技巧
详细说明请见下方的如何获取合并请求数据部分。

Step 4: Receive and Process Diff

步骤4:接收并处理差异

After you provide the diff content, the skill processes all changed files in the merge request. Each file is analyzed regardless of file type, with appropriate handling for:
  • Source code files (full analysis)
  • Configuration files (relevant checks)
  • Binary files (noted but skipped)
您提供差异内容后,技能会处理合并请求中的所有变更文件。无论文件类型如何,都会进行分析,并针对以下类型做相应处理:
  • 源代码文件(全面分析)
  • 配置文件(相关检查)
  • 二进制文件(标记但跳过)

Step 5: Analyze Code and Generate Report

步骤5:代码分析与报告生成

The skill performs multi-category analysis on the code changes and generates a structured summary report containing:
  • Overall assessment
  • Findings categorized by severity (critical, warning, suggestion, positive)
  • File and line references for each issue
  • Actionable recommendations

技能会对代码变更执行多类别分析,并生成结构化总结报告,包含:
  • 整体评估
  • 按严重程度分类的发现(关键、警告、建议、好评)
  • 每个问题对应的文件和行号引用
  • 可执行的改进建议

How to Retrieve Merge Request Data

如何获取合并请求数据

After the merge request URL is validated, you need to provide the diff content for analysis. This section explains how to retrieve the required information.
合并请求URL验证通过后,您需要提供差异内容用于分析。本节说明如何获取所需信息。

Required Information

所需信息

To perform a thorough code review, please provide:
InformationDescriptionRequired
TitleThe merge request titleYes
DescriptionThe MR description explaining the changesYes
Diff ContentThe actual code changes (additions/deletions)Yes
Changed Files ListList of all files modified in the MRRecommended
为了执行全面的代码审查,请提供以下信息:
信息描述是否必填
标题合并请求标题
描述说明变更内容的MR描述
差异内容实际的代码变更(新增/删除)
变更文件列表MR中所有修改的文件列表推荐

Option 1: Using the GitLab Web Interface

选项1:使用GitLab网页界面

  1. Navigate to the Merge Request
    • Open the merge request URL in your browser
    • You should see the MR overview page with title and description
  2. Copy the Title and Description
    • The title is displayed at the top of the page
    • The description is shown below the title in the overview section
  3. Access the Changes Tab
    • Click on the "Changes" tab to view the diff
    • This shows all modified files with line-by-line changes
  4. Copy the Diff Content
    • Select and copy the diff content from the Changes view
    • Alternatively, click the "..." menu and select "Copy diff" if available
    • For large MRs, you may need to expand collapsed files first
  1. 导航到合并请求
    • 在浏览器中打开合并请求URL
    • 您会看到包含标题和描述的MR概览页面
  2. 复制标题和描述
    • 标题显示在页面顶部
    • 描述显示在概览区域的标题下方
  3. 访问变更标签页
    • 点击"Changes"标签页查看差异
    • 这里会显示所有修改的文件及逐行变更
  4. 复制差异内容
    • 选择并复制Changes视图中的差异内容
    • 或者点击"..."菜单并选择"Copy diff"(如果有此选项)
    • 对于大型MR,可能需要先展开折叠的文件

Option 2: Using the GitLab API

选项2:使用GitLab API

If you have API access, you can retrieve the merge request data programmatically:
Get Merge Request Details:
bash
curl --header "PRIVATE-TOKEN: <your_access_token>" \
  "https://<gitlab-host>/api/v4/projects/<project_id>/merge_requests/<mr_id>"
Get Merge Request Changes (Diff):
bash
curl --header "PRIVATE-TOKEN: <your_access_token>" \
  "https://<gitlab-host>/api/v4/projects/<project_id>/merge_requests/<mr_id>/changes"
Notes:
  • Replace
    <your_access_token>
    with your GitLab personal access token
  • Replace
    <project_id>
    with the URL-encoded project path (e.g.,
    mygroup%2Fmyproject
    )
  • Replace
    <mr_id>
    with the merge request number
  • The token needs at least
    read_api
    scope
如果您有API访问权限,可以通过编程方式获取合并请求数据:
获取合并请求详情:
bash
curl --header "PRIVATE-TOKEN: <your_access_token>" \
  "https://<gitlab-host>/api/v4/projects/<project_id>/merge_requests/<mr_id>"
获取合并请求变更(差异):
bash
curl --header "PRIVATE-TOKEN: <your_access_token>" \
  "https://<gitlab-host>/api/v4/projects/<project_id>/merge_requests/<mr_id>/changes"
注意:
  • <your_access_token>
    替换为您的GitLab个人访问令牌
  • <project_id>
    替换为URL编码的项目路径(例如:
    mygroup%2Fmyproject
  • <mr_id>
    替换为合并请求编号
  • 令牌至少需要
    read_api
    权限

Option 3: Using Git Commands

选项3:使用Git命令

If you have the repository cloned locally:
bash
undefined
如果您已本地克隆仓库:
bash
undefined

Fetch the merge request branch

获取合并请求分支

git fetch origin merge-requests/<mr_id>/head:mr-<mr_id>
git fetch origin merge-requests/<mr_id>/head:mr-<mr_id>

View the diff against the target branch

查看与目标分支的差异

git diff <target_branch>...mr-<mr_id>
undefined
git diff <target_branch>...mr-<mr_id>
undefined

Troubleshooting Access Issues

访问问题故障排除

IssuePossible CauseSolution
404 Not FoundMR doesn't exist or wrong URLVerify the merge request ID and project path are correct
401 UnauthorizedMissing or invalid authenticationEnsure you're logged in (web) or using a valid API token
403 ForbiddenInsufficient permissionsRequest access to the project or contact the project owner
Empty diffMR has no changes or is already mergedCheck if the MR is still open and has commits
Timeout on large MRsToo many changed filesTry fetching changes for specific files or use the API with pagination
问题可能原因解决方案
404 Not FoundMR不存在或URL错误验证合并请求ID和项目路径是否正确
401 Unauthorized缺少或无效的身份验证确保已登录(网页端)或使用有效的API令牌
403 Forbidden权限不足请求项目访问权限或联系项目所有者
空差异MR无变更或已合并检查MR是否仍处于打开状态且包含提交
大型MR超时变更文件过多尝试获取特定文件的变更,或使用带分页的API

Tips for Large Merge Requests

大型合并请求处理技巧

  • Break it down: If the MR has many files, consider providing the diff in batches
  • Focus on key files: Prioritize source code files over generated or configuration files
  • Exclude binary files: Binary file changes cannot be meaningfully reviewed
  • Use file filters: In the GitLab UI, use the file filter to focus on specific file types
  • 拆分处理:如果MR包含大量文件,考虑分批提供差异
  • 重点关注关键文件:优先提供源代码文件,而非生成文件或配置文件
  • 排除二进制文件:二进制文件的变更无法进行有意义的审查
  • 使用文件过滤器:在GitLab界面中,使用文件过滤器聚焦特定类型的文件

What to Provide

提交格式

Once you have the information, share it in the following format:
**Title:** [MR Title]

**Description:**
[MR Description]

**Changed Files:**
- file1.ts
- file2.ts
- ...

**Diff:**
[Paste the diff content here]

获取信息后,请按以下格式分享:
**Title:** [MR标题]

**Description:**
[MR描述]

**Changed Files:**
- file1.ts
- file2.ts
- ...

**Diff:**
[粘贴差异内容]

Code Analysis Categories

代码分析类别

When analyzing code changes, the skill evaluates the diff across multiple categories to provide comprehensive feedback. Each finding is categorized to help prioritize and address issues effectively.
分析代码变更时,技能会从多个类别评估差异,提供全面的反馈。每个发现都会分类,帮助优先处理问题。

Style

风格

Identifies formatting and naming convention issues that affect code readability and maintainability.
Issue TypeDescriptionExample
Formatting inconsistenciesIrregular indentation, spacing, or line breaksMixed tabs and spaces, inconsistent brace placement
Naming violationsNames that don't follow conventions
myFunc
instead of
myFunction
,
x
for a meaningful variable
Code organizationPoor structure or orderingRelated functions scattered across file
识别影响代码可读性和可维护性的格式与命名规范问题。
问题类型描述示例
格式不一致不规则的缩进、空格或换行混合使用制表符和空格,不一致的大括号位置
命名违规不符合规范的命名使用
myFunc
而非
myFunction
,用
x
表示有实际意义的变量
代码组织结构或顺序混乱相关函数分散在文件各处

Bugs

漏洞

Detects potential logic errors and runtime issues that could cause incorrect behavior.
Issue TypeDescriptionExample
Logic errorsIncorrect conditions or calculationsOff-by-one errors, inverted boolean logic
Null pointer risksPotential null/undefined accessAccessing property without null check
Type mismatchesIncompatible type operationsString concatenation instead of numeric addition
Race conditionsConcurrent access issuesUnsynchronized shared state modifications
检测可能导致错误行为的逻辑错误和运行时问题。
问题类型描述示例
逻辑错误错误的条件判断或计算差一错误,反转的布尔逻辑
空指针风险可能的空/未定义访问未做空值检查就访问属性
类型不匹配不兼容的类型操作字符串拼接代替数值相加
竞态条件并发访问问题未同步的共享状态修改

Security

安全性

Identifies vulnerabilities that could be exploited by malicious actors.
Issue TypeDescriptionExample
SQL injectionUnsanitized database queriesString concatenation in SQL queries
XSS vulnerabilitiesCross-site scripting risksUnescaped user input in HTML output
Hardcoded secretsCredentials in source codeAPI keys, passwords, tokens in code
Insecure dependenciesKnown vulnerable packagesOutdated libraries with CVEs
Path traversalUnsanitized file path accessUser input directly in file paths
识别可能被攻击者利用的漏洞。
问题类型描述示例
SQL注入未净化的数据库查询SQL查询中直接拼接字符串
XSS漏洞跨站脚本风险HTML输出中使用未转义的用户输入
硬编码密钥源代码中包含凭证代码中的API密钥、密码、令牌
不安全依赖已知存在漏洞的包包含CVE漏洞的过时库
路径遍历未净化的文件路径访问用户输入直接用于文件路径

Performance

性能

Highlights inefficiencies that could impact application speed or resource usage.
Issue TypeDescriptionExample
N+1 queriesRepeated database calls in loopsFetching related records one at a time
Unnecessary loopsRedundant iterationsLooping when a direct lookup suffices
Memory leaksUnreleased resourcesEvent listeners not removed, unclosed connections
Inefficient algorithmsSuboptimal complexityO(n²) when O(n) is possible
Excessive allocationsUnnecessary object creationCreating objects inside tight loops
突出可能影响应用速度或资源占用的低效代码。
问题类型描述示例
N+1查询循环中重复调用数据库逐个获取关联记录
不必要的循环冗余的迭代可以直接查找却使用循环
内存泄漏未释放的资源未移除的事件监听器,未关闭的连接
低效算法次优复杂度可用O(n)却使用O(n²)算法
过度分配不必要的对象创建在紧凑循环中创建对象

Error Handling

错误处理

Evaluates how the code handles exceptional conditions and failures.
Issue TypeDescriptionExample
Uncaught exceptionsMissing try-catch blocksAsync operations without error handling
Silent failuresErrors swallowed without actionEmpty catch blocks, ignored promise rejections
Missing validationUnvalidated inputsNo bounds checking, missing required field validation
Poor error messagesUnhelpful error informationGeneric "An error occurred" messages
评估代码处理异常情况和故障的方式。
问题类型描述示例
未捕获异常缺少try-catch块异步操作未处理错误
静默失败错误被吞噬未处理空的catch块,忽略Promise拒绝
缺少验证未验证输入无边界检查,缺少必填字段验证
错误信息不佳无帮助的错误提示通用的"发生错误"提示

Duplication

重复代码

Identifies repeated code patterns that could be consolidated.
Issue TypeDescriptionExample
Copy-paste codeIdentical or near-identical blocksSame logic repeated in multiple functions
Extractable functionsRepeated patterns that could be abstractedCommon validation logic duplicated
Magic numbers/stringsRepeated literals without constantsSame value hardcoded in multiple places
识别可合并的重复代码模式。
问题类型描述示例
复制粘贴代码完全或几乎完全相同的代码块相同逻辑在多个函数中重复
可提取函数可抽象的重复模式通用验证逻辑重复出现
魔法数字/字符串重复出现的字面量未定义为常量同一值在多处硬编码

Positive

好评

Recognizes good practices and well-written code to encourage continued quality.
Issue TypeDescriptionExample
Clean abstractionsWell-designed interfaces and modulesClear separation of concerns
Comprehensive testingGood test coverageUnit tests for edge cases
Clear documentationHelpful comments and docsWell-documented public APIs
Defensive codingProactive error preventionInput validation, null checks
Performance optimizationEfficient implementationsAppropriate caching, lazy loading

认可良好实践和编写规范的代码,鼓励持续提升质量。
问题类型描述示例
清晰的抽象设计良好的接口和模块关注点分离清晰
全面测试良好的测试覆盖率针对边缘情况的单元测试
清晰的文档有用的注释和文档文档完善的公共API
防御式编程主动预防错误输入验证,空值检查
性能优化高效的实现适当的缓存,懒加载

Severity Levels

严重程度等级

Each finding from the code review is assigned a severity level to help prioritize issues and focus attention on the most important items first.
代码审查的每个发现都会分配严重程度等级,帮助优先处理问题,聚焦最重要的事项。

Critical

关键

Issues that require immediate attention before the merge request can be approved.
CriteriaDescriptionExamples
Security vulnerabilitiesCode that could be exploited by attackersSQL injection, XSS, authentication bypass, exposed credentials
Data loss risksCode that could result in data corruption or lossUnprotected delete operations, missing transaction handling, race conditions on writes
Breaking changesChanges that would cause system failuresNull pointer exceptions in critical paths, infinite loops, resource exhaustion
合并请求批准前必须立即处理的问题。
标准描述示例
安全漏洞可能被攻击者利用的代码SQL注入、XSS、身份验证绕过、凭证泄露
数据丢失风险可能导致数据损坏或丢失的代码未受保护的删除操作,缺少事务处理,写入操作的竞态条件
破坏性变更会导致系统故障的变更关键路径中的空指针异常,无限循环,资源耗尽

Warning

警告

Issues that should be addressed but don't block the merge request.
CriteriaDescriptionExamples
Potential bugsCode that may cause incorrect behaviorOff-by-one errors, incorrect null handling, logic errors
Performance issuesCode that could degrade system performanceN+1 queries, inefficient algorithms, memory leaks
Error handling gapsMissing or inadequate error handlingUncaught exceptions, silent failures, missing validation
应处理但不阻止合并请求的问题。
标准描述示例
潜在漏洞可能导致错误行为的代码差一错误,不正确的空值处理,逻辑错误
性能问题可能降低系统性能的代码N+1查询,低效算法,内存泄漏
错误处理缺陷缺失或不足的错误处理未捕获异常,静默失败,缺少验证

Suggestion

建议

Recommendations for improvement that enhance code quality.
CriteriaDescriptionExamples
Style improvementsFormatting and convention issuesInconsistent naming, poor indentation, missing documentation
Refactoring opportunitiesCode that could be cleaner or more maintainableDuplicated code, overly complex functions, magic numbers
Best practice deviationsCode that doesn't follow established patternsMissing type annotations, hardcoded values, tight coupling
提升代码质量的改进建议,非强制要求。
标准描述示例
风格改进格式和规范问题不一致的命名,缩进混乱,缺少文档
重构机会可更简洁或易维护的代码重复代码,过于复杂的函数,魔法数字
偏离最佳实践未遵循既定模式的代码缺少类型注解,硬编码值,紧耦合

Positive

好评

Recognition of good practices to encourage continued quality.
CriteriaDescriptionExamples
Good practices observedCode that demonstrates quality patternsComprehensive error handling, clear naming, proper abstractions
Well-tested codeEvidence of thorough testingUnit tests for edge cases, integration test coverage
Clean designGood architectural decisionsSeparation of concerns, dependency injection, clear interfaces

认可良好实践,鼓励持续保持代码质量。
标准描述示例
良好实践体现质量模式的代码全面的错误处理,清晰的命名,适当的抽象
测试完善测试全面的代码针对边缘情况的单元测试,集成测试覆盖
设计清晰良好的架构决策关注点分离,依赖注入,清晰的接口

Report Structure

报告结构

The code review generates a structured markdown report containing all findings organized for easy consumption. This section documents the report format and each component.
代码审查会生成结构化的Markdown报告,包含所有发现,便于阅读。本节说明报告格式及各组件。

Report Sections Overview

报告章节概览

SectionDescriptionAlways Present
HeaderMR identification informationYes
Overall AssessmentHigh-level summary of the reviewYes
Findings SummaryCounts by severity categoryYes
Critical IssuesIssues requiring immediate attentionOnly if critical findings exist
WarningsPotential problems to addressOnly if warning findings exist
SuggestionsImprovement recommendationsOnly if suggestion findings exist
Positive ObservationsGood practices identifiedOnly if positive findings exist
RecommendationsActionable next stepsYes
章节描述是否始终存在
头部合并请求识别信息
整体评估审查的高级总结
发现汇总按严重程度分类的统计
关键问题需要立即处理的问题仅当存在关键发现时
警告需要关注的潜在问题仅当存在警告发现时
建议改进建议仅当存在建议发现时
好评识别的良好实践仅当存在好评发现时
建议可执行的下一步操作

Header

头部

The report header contains merge request identification information:
FieldDescriptionExample
URLFull merge request URL
https://gitlab.com/team/project/-/merge_requests/123
ProjectProject path including groups
team/project
MR IDMerge request number
#123
TitleMerge request title
Add user authentication feature
Format:
markdown
undefined
报告头部包含合并请求识别信息:
字段描述示例
URL完整的合并请求URL
https://gitlab.com/team/project/-/merge_requests/123
项目包含组的项目路径
team/project
MR ID合并请求编号
#123
标题合并请求标题
Add user authentication feature
格式:
markdown
undefined

Code Review: [MR Title]

代码审查:[MR标题]

Merge Request: [URL] Project: [Project Path] MR ID: #[ID]
undefined
合并请求: [URL] 项目: [项目路径] MR ID: #[编号]
undefined

Overall Assessment

整体评估

A brief summary providing the reviewer's high-level evaluation of the merge request quality and readiness.
Content includes:
  • General quality assessment (e.g., "well-structured", "needs work", "ready for merge")
  • Key concerns or highlights
  • Recommendation (approve, request changes, needs discussion)
Format:
markdown
undefined
简短总结审查者对合并请求质量和就绪度的高级评价。
内容包括:
  • 整体质量评估(如"结构清晰"、"需要改进"、"可合并")
  • 关键关注点或亮点
  • 建议(批准、要求修改、需要讨论)
格式:
markdown
undefined

Overall Assessment

整体评估

[1-3 sentences summarizing the overall quality and readiness of the changes]
undefined
[1-3句话总结变更的整体质量和就绪度]
undefined

Findings Summary

发现汇总

A statistical overview showing the count of findings in each severity category.
MetricDescription
Total FindingsSum of all findings across categories
CriticalCount of critical severity issues
WarningsCount of warning severity issues
SuggestionsCount of suggestion severity items
PositiveCount of positive observations
Files ReviewedNumber of files analyzed
Format:
markdown
undefined
统计概览,显示各严重程度类别的发现数量。
指标描述
总发现数所有类别的发现总数
关键严重程度为关键的问题数量
警告严重程度为警告的问题数量
建议建议类别的项数
好评好评类别的观察数量
已审查文件数分析的文件数量
格式:
markdown
undefined

Findings Summary

发现汇总

SeverityCount
🔴 Critical[N]
🟡 Warning[N]
🔵 Suggestion[N]
🟢 Positive[N]
Total[N]
Files Reviewed: [N]
undefined
严重程度数量
🔴 关键[N]
🟡 警告[N]
🔵 建议[N]
🟢 好评[N]
总计[N]
已审查文件数: [N]
undefined

Critical Issues

关键问题

A detailed list of critical severity findings that require immediate attention before the merge request can be approved.
Each finding includes:
  • File name and line number(s)
  • Issue title and category
  • Detailed description
  • Actionable recommendation
Format:
markdown
undefined
合并请求批准前必须立即处理的关键严重程度发现的详细列表。
每个发现包含:
  • 文件名和行号
  • 问题标题和类别
  • 详细描述
  • 可执行的改进建议
格式:
markdown
undefined

Critical Issues

关键问题

1. [Issue Title]

1. [问题标题]

File:
[filename]
| Line: [line number or range] Category: [Security/Bugs/etc.]
[Detailed description of the issue]
Recommendation: [Specific action to resolve the issue]

undefined
文件:
[文件名]
| 行号: [行号或范围] 类别: [安全/漏洞等]
[问题详细描述]
建议: [解决问题的具体操作]

undefined

Warnings

警告

A list of warning severity findings that should be addressed but don't block the merge.
Each finding includes:
  • File name and line number(s)
  • Issue title and category
  • Description of the concern
  • Suggested resolution
Format:
markdown
undefined
应处理但不阻止合并的警告严重程度发现列表。
每个发现包含:
  • 文件名和行号
  • 问题标题和类别
  • 问题描述
  • 建议的解决方案
格式:
markdown
undefined

Warnings

警告

1. [Issue Title]

1. [问题标题]

File:
[filename]
| Line: [line number or range] Category: [Bugs/Performance/Error Handling/etc.]
[Description of the potential issue]
Suggestion: [How to address the warning]

undefined
文件:
[文件名]
| 行号: [行号或范围] 类别: [漏洞/性能/错误处理等]
[潜在问题的描述]
建议: [处理警告的方法]

undefined

Suggestions

建议

A list of improvement recommendations that enhance code quality but are not required.
Each finding includes:
  • File name and line number(s) (when applicable)
  • Suggestion title and category
  • Explanation of the improvement
  • Example or guidance (optional)
Format:
markdown
undefined
提升代码质量的改进建议列表,非强制要求。
每个发现包含:
  • 文件名和行号(适用时)
  • 建议标题和类别
  • 改进说明
  • 示例或指导(可选)
格式:
markdown
undefined

Suggestions

建议

1. [Suggestion Title]

1. [建议标题]

File:
[filename]
| Line: [line number or range] Category: [Style/Duplication/etc.]
[Explanation of the suggested improvement]

undefined
文件:
[文件名]
| 行号: [行号或范围] 类别: [风格/重复代码等]
[改进建议的说明]

undefined

Positive Observations

好评

Recognition of good practices and well-written code to encourage continued quality.
Each observation includes:
  • File name (line numbers optional)
  • What was done well
  • Why it's a good practice
Format:
markdown
undefined
认可良好实践和编写规范的代码,鼓励持续提升质量。
每个观察包含:
  • 文件名(行号可选)
  • 做得好的地方
  • 为何是良好实践
格式:
markdown
undefined

Positive Observations

好评

1. [Observation Title]

1. [观察标题]

File:
[filename]
[Description of the good practice and why it's valuable]

undefined
文件:
[文件名]
[良好实践的描述及其价值]

undefined

Actionable Recommendations

可执行建议

A prioritized list of next steps for the merge request author, summarizing the key actions needed.
Content includes:
  • Prioritized action items based on findings
  • Grouped by urgency (must fix, should fix, consider)
  • Clear, specific guidance
Format:
markdown
undefined
合并请求作者的优先级下一步操作列表,总结关键需执行的动作。
内容包括:
  • 基于发现的优先级操作项
  • 按紧急程度分组(必须修复、应该修复、考虑修复)
  • 清晰、具体的指导
格式:
markdown
undefined

Recommendations

建议

Must Fix (Before Merge)

必须修复(合并前)

  1. [Action item from critical issues]
  2. [Action item from critical issues]
  1. [关键问题中的操作项]
  2. [关键问题中的操作项]

Should Fix

应该修复

  1. [Action item from warnings]
  2. [Action item from warnings]
  1. [警告中的操作项]
  2. [警告中的操作项]

Consider

考虑修复

  1. [Action item from suggestions]
  2. [Action item from suggestions]
undefined
  1. [建议中的操作项]
  2. [建议中的操作项]
undefined

Complete Report Example

完整报告示例

markdown
undefined
markdown
undefined

Code Review: Add user authentication feature

代码审查:Add user authentication feature

Merge Request: https://gitlab.com/team/project/-/merge_requests/123 Project: team/project MR ID: #123
合并请求: https://gitlab.com/team/project/-/merge_requests/123 项目: team/project MR ID: #123

Overall Assessment

整体评估

The authentication implementation is well-structured with good separation of concerns. However, there are critical security issues with password handling that must be addressed before merge. The error handling is comprehensive and the code follows project conventions.
身份验证实现结构清晰,关注点分离良好。但密码处理存在严重的安全问题,合并前必须解决。错误处理全面,代码遵循项目规范。

Findings Summary

发现汇总

SeverityCount
🔴 Critical2
🟡 Warning3
🔵 Suggestion4
🟢 Positive2
Total11
Files Reviewed: 6
严重程度数量
🔴 关键2
🟡 警告3
🔵 建议4
🟢 好评2
总计11
已审查文件数: 6

Critical Issues

关键问题

1. Plaintext Password Storage

1. 明文存储密码

File:
src/auth/userService.ts
| Line: 45-48 Category: Security
Passwords are being stored in plaintext in the database. This exposes user credentials if the database is compromised.
Recommendation: Use bcrypt or argon2 to hash passwords before storage. Never store plaintext passwords.

文件:
src/auth/userService.ts
| 行号: 45-48 类别: 安全
密码以明文形式存储在数据库中。如果数据库被攻破,用户凭证会泄露。
建议: 使用bcrypt或argon2在存储前哈希密码。绝不要存储明文密码。

2. SQL Injection Vulnerability

2. SQL注入漏洞

File:
src/auth/userRepository.ts
| Line: 23 Category: Security
User input is directly concatenated into SQL query without sanitization.
Recommendation: Use parameterized queries or an ORM to prevent SQL injection attacks.

文件:
src/auth/userRepository.ts
| 行号: 23 类别: 安全
用户输入直接拼接到SQL查询中,未做净化处理。
建议: 使用参数化查询或ORM防止SQL注入攻击。

Warnings

警告

1. Missing Rate Limiting

1. 缺少速率限制

File:
src/auth/loginController.ts
| Line: 15-30 Category: Security
The login endpoint has no rate limiting, making it vulnerable to brute force attacks.
Suggestion: Implement rate limiting using a middleware like express-rate-limit.

文件:
src/auth/loginController.ts
| 行号: 15-30 类别: 安全
登录端点未设置速率限制,易受暴力破解攻击。
建议: 使用express-rate-limit中间件实现速率限制。

2. Potential Null Reference

2. 潜在空引用

File:
src/auth/tokenService.ts
| Line: 12-15 Category: Bugs
The
user
object is accessed without checking if it exists, which could cause a runtime error if the user lookup fails.
Suggestion: Add a null check before accessing user properties:
if (!user) throw new UserNotFoundError();

文件:
src/auth/tokenService.ts
| 行号: 12-15 类别: 漏洞
未检查
user
对象是否存在就直接访问,用户查找失败时会导致运行时错误。
建议: 在访问用户属性前添加空值检查:
if (!user) throw new UserNotFoundError();

3. Missing Token Expiration Handling

3. 缺少令牌过期处理

File:
src/auth/tokenService.ts
| Line: 42-50 Category: Error Handling
The token refresh logic doesn't handle the case where the token has already expired, which could lead to silent authentication failures.
Suggestion: Add explicit expiration checking and return a clear error when the token cannot be refreshed.

文件:
src/auth/tokenService.ts
| 行号: 42-50 类别: 错误处理
令牌刷新逻辑未处理令牌已过期的情况,可能导致静默认证失败。
建议: 添加显式的过期检查,当令牌无法刷新时返回清晰的错误。

Suggestions

建议

1. Extract Validation Logic

1. 提取验证逻辑

File:
src/auth/userService.ts
| Line: 20-35 Category: Duplication
Email and password validation logic is duplicated in multiple methods.
Suggestion: Extract into a shared validation utility function.

文件:
src/auth/userService.ts
| 行号: 20-35 类别: 重复代码
邮箱和密码验证逻辑在多个方法中重复。
建议: 提取到共享的验证工具函数中。

2. Add JSDoc Comments

2. 添加JSDoc注释

File:
src/auth/userService.ts
| Line: 1-100 Category: Style
Public methods lack documentation comments, making it harder for other developers to understand the API.
Suggestion: Add JSDoc comments to all public methods describing parameters, return values, and potential errors.

文件:
src/auth/userService.ts
| 行号: 1-100 类别: 风格
公共方法缺少文档注释,其他开发者难以理解API。
建议: 为所有公共方法添加JSDoc注释,说明参数、返回值和可能的错误。

3. Consider Using Validation Library

3. 考虑使用验证库

File:
src/auth/validators.ts
| Line: 5-45 Category: Style
Custom validation logic could be replaced with a well-tested validation library for better maintainability.
Suggestion: Consider using a validation library like Zod or Joi for schema validation.

文件:
src/auth/validators.ts
| 行号: 5-45 类别: 风格
自定义验证逻辑可替换为经过充分测试的验证库,提升可维护性。
建议: 考虑使用Zod或Joi等验证库进行 schema 验证。

4. Magic String Constants

4. 魔法字符串常量

File:
src/auth/constants.ts
| Line: 8-12 Category: Duplication
The error message "Invalid credentials" appears in multiple files without a shared constant.
Suggestion: Define error messages as constants in a shared file to ensure consistency.

文件:
src/auth/constants.ts
| 行号: 8-12 类别: 重复代码
错误信息"Invalid credentials"在多个文件中出现,未定义为共享常量。
建议: 在共享文件中定义错误消息常量,确保一致性。

Positive Observations

好评

1. Comprehensive Error Handling

1. 全面的错误处理

File:
src/auth/loginController.ts
Excellent use of try-catch blocks with specific error types and meaningful error messages. This will make debugging much easier.

文件:
src/auth/loginController.ts
出色地使用try-catch块处理特定错误类型,并提供有意义的错误信息。这会让调试变得更简单。

2. Clear Function Naming

2. 清晰的函数命名

File:
src/auth/userService.ts
Function names clearly describe their purpose (e.g.,
validateUserCredentials
,
generateAuthToken
). This improves code readability.

文件:
src/auth/userService.ts
函数名称清晰描述其用途(例如
validateUserCredentials
generateAuthToken
)。提升了代码可读性。

Recommendations

建议

Must Fix (Before Merge)

必须修复(合并前)

  1. Implement password hashing in
    userService.ts
    (Critical: Security)
  2. Use parameterized queries in
    userRepository.ts
    (Critical: Security)
  1. userService.ts
    中实现密码哈希(关键:安全)
  2. userRepository.ts
    中使用参数化查询(关键:安全)

Should Fix

应该修复

  1. Add rate limiting to login endpoint (Warning: Security)
  2. Add null check for user object in
    tokenService.ts
    lines 12-15 (Warning: Bugs)
  3. Handle token expiration edge case in
    tokenService.ts
    (Warning: Error Handling)
  1. 为登录端点添加速率限制(警告:安全)
  2. tokenService.ts
    第12-15行添加用户对象的空值检查(警告:漏洞)
  3. tokenService.ts
    中处理令牌过期的边缘情况(警告:错误处理)

Consider

考虑修复

  1. Extract validation logic to reduce duplication in
    userService.ts
  2. Add JSDoc comments to public methods for better documentation
  3. Consider using a validation library like Zod for schema validation
  4. Define error message constants to ensure consistency
undefined
  1. 提取验证逻辑,减少
    userService.ts
    中的重复代码
  2. 为公共方法添加JSDoc注释,提升文档质量
  3. 考虑使用Zod等验证库进行schema验证
  4. 定义错误消息常量,确保一致性
undefined