简介
当您在命名和风格约定等细小实现细节上花费的时间更少,而将精力集中在更高层次的设计、问题解决以及满足用户需求的功能上时,代码审查会更加高效。
在本文中,我们将展示 Copilot 的自动审查如何帮助优化您的审查流程,让您在细微改动上花费更少时间,而在细致的问题解决和更深入的实现理解上投入更多时间,使实现不仅仅是合格,而是巧妙地满足用户需求。
1. 提升 Copilot 的审查质量
Copilot 代码审查可以为您仓库中的所有拉取请求提供自动审查,通过捕获您不希望出现在代码中的更改,使审查更加高效。结合自定义指令后,Copilot 代码审查的效果更佳,因为它可以提供针对您团队工作方式、使用的工具或项目具体情况量身定制的响应。
编写自定义指令的最佳实践包括
- 清晰的标题
- 项目符号
- 简短、直接的指令
让我们看一个例子。如果您使用 Python 构建订单处理系统,您的自定义指令可能包括针对 Python 的格式化、性能和安全编码实践,以及与项目直接相关的指导。以下示例展示了自定义指令的几行可能是什么样子。
## Repository context
- This repository implements an order processing system (order intake, payment, fulfillment) where correctness, security, and auditability are critical.
## Style and conventions
- Follow the PEP 8 and PEP 257 style guide for Python.
- Use clear, domain-relevant names (orders, payments, inventory, customers, shipments).
- Prefer small, focused functions and methods with clearly defined responsibilities.
## Secure coding
- Verify proper input validation and sanitization.
- Review authentication and authorization logic.
## Error handling guidelines
- Handle timeouts and network errors gracefully.
- Ensure failures are logged with enough detail for debugging.
## Order processing context
- Ensure order creation, payment handling, and updates are idempotent to avoid duplicate orders or duplicate charges.
- Validate and normalize all order, payment, and customer data before persisting or acting on it.
- Do not log or persist sensitive data (passwords, raw payment details, full identifiers) without hashing, encryption, or redaction.
- Call out obvious performance issues in core order workflows (e.g., N+1 queries, per-order synchronous network calls) and suggest simpler, more efficient alternatives.
## Review style
- Be concise, specific and actionable.
- Explain the "why" behind recommendations using bullet points.
在下一节中,我们将逐步演示示例自定义指令如何积极影响 Copilot 为拉取请求提供的审查评论。
2. 自动化审查以处理代码风格约定和性能
启用自动 Copilot 代码审查后,Copilot 将在拉取请求脱离草稿模式后自动进行审查。
假设您提交了一个拉取请求,其中包含以下用于在订单处理系统中更新库存的函数。
def notify_inventory(product_id, quantity):
requests.post("http://inventory-service/update", json={"product_id": product_id, "quantity": quantity})
虽然该函数可工作,但缺乏清晰性和健壮性。类型意图是隐式的,没有文档字符串,也未包含错误处理或日志记录,这导致无法确定通知是否实际生效。
Copilot 会审查代码并可能给出以下评论和代码建议。
注意
以下响应为示例。Copilot Chat 的回复具有不确定性,您可能会得到与此处显示的不同的响应。
Missing error handling for network calls
The notify_inventory function makes a synchronous network call without any error handling for timeouts, connection failures, or non-200 responses.
Why this matters:
- Network failures will cause unhandled exceptions and crash the order processing flow
- Orders could be marked as CONFIRMED but inventory never gets updated
- This violates the requirement to "handle timeouts and network errors gracefully"
- Failures won't be logged with enough detail for debugging
Recommendation: Add proper error handling with timeout and logging:
def notify_inventory(product_id: str, quantity: int) -> bool:
"""Notify the inventory service of order placement.
Args:
product_id: The product identifier.
quantity: The quantity ordered.
Returns:
True if the notification succeeded; False otherwise.
"""
try:
response = requests.post(
"http://inventory-service/update",
json={"product_id": product_id, "quantity": quantity},
timeout=5,
)
response.raise_for_status()
logger.info(
"Inventory notified for product %s, quantity %d (status %d)",
product_id,
quantity,
response.status_code,
)
return True
except requests.exceptions.Timeout:
logger.error(
"Timeout notifying inventory for product %s, quantity %d",
product_id,
quantity,
exc_info=True,
)
except requests.exceptions.RequestException:
logger.error(
"Failed to notify inventory for product %s, quantity %d",
product_id,
quantity,
exc_info=True,
)
return False
Copilot 的响应遵循您自定义指令中的指导进行推荐。在本例中,它遵循 Python 的 PEP 8 与 257 风格指南,并建议改进以更好地处理超时和错误日志,同时简要说明建议背后的原因。
注意
在接受并提交之前,请务必仔细审查 Copilot 的建议。
此类自动审查评论可帮助您在编码时建立自己的理解,或在审查他人代码时聚焦并精简反馈。
3. 标记安全漏洞并修复
接下来,假设您被指派改进订单处理系统中密码的存储方式。您提交了一个拉取请求,代码中您认为已足够对用户密码进行哈希以保护它们。
def get_password_hash(password: str, salt: str) -> str:
"""Hash a password with the given salt using SHA-256.
Returns the hexadecimal representation of the hashed password.
"""
return hashlib.sha256((password + salt).encode()).hexdigest()
class User:
"""Represents a user in the order processing system."""
def __init__(self, username: str, password: str, salt: str):
"""Initialize a User with username, password, and salt.
The password is hashed and stored for authentication.
"""
self.username = username
self.salt = salt
self.password_hash = get_password_hash(password, self.salt)
def verify_password(self, password: str) -> bool:
"""Verify a plain-text password against the stored hash."""
return get_password_hash(password, self.salt) == self.password_hash
然而,在本例中,使用 SHA-256 并不可接受,因为它的计算成本不足以保护用户密码。
虽然 Copilot 代码审查可以提供安全最佳实践建议,但 Copilot Autofix 用于代码扫描更进一步。它利用 CodeQL 分析对 GitHub 仓库中的代码进行扫描,查找安全漏洞和编码错误,然后 Copilot Autofix 可以为警报提供修复建议,使您更高效地防止和减少漏洞。
例如,Copilot Autofix 可能会对代码给出以下评论。
Using SHA-256 for password hashing is insecure for authentication systems. SHA-256 is designed to be fast, making it vulnerable to brute-force attacks.
To fix the problem, use a password-specific hashing algorithm like bcrypt, scrypt, or argon2 (e.g., `argon2-cffi` from the PyPI package) which are designed to be slow and include built-in salting mechanisms.
Copilot Autofix 还会为潜在的漏洞修复提供代码建议,供您审查。在此情况下,它可能会给出如下代码建议,导入相应的包并更新与密码哈希相关的代码。
from argon2 import PasswordHasher
def get_initial_hash(password: str):
ph = PasswordHasher()
return ph.hash(password)
def check_password(password: str, known_hash):
ph = PasswordHasher()
return ph.verify(known_hash, password)
注意
- 在接受之前,请始终验证和确认 Copilot 建议的任何更改。
- 在本例中,Copilot 代码审查也可能强调需要生成唯一的盐值。
如您所见,自动识别漏洞并提供修复建议,可帮助您将安全置于首位。Copilot Autofix 让您专注于了解安全编码以及针对代码库和项目最佳的修复方案。
使用 Copilot 的优化审查
自动审查评论帮助您更高效地优化审查并保障代码安全,无论您的经验水平如何。
- 自定义指令帮助细化 Copilot 代码审查的响应,使其针对我们的项目和用户需求,并且我们也看到可以自行调节 Copilot 在反馈中提供的解释程度。
- Copilot 代码审查帮助我们迅速改进错误日志并了解其重要性。
- Copilot Autofix 用于代码扫描帮助我们避免使用不足的密码哈希方法,保护用户数据。
后续步骤
要使用 Copilot 的审查功能让审查更高效、更有效,请按照以下步骤开始。
- 为您的项目和仓库创建特定的自定义指令。自行编写,或从我们的示例库中获取灵感。请参阅 自定义指令。
- 要为您的仓库启用自动 Copilot 代码审查,请参阅 GitHub Copilot 自动代码审查配置指南。
- 要为您的仓库配置 Copilot Autofix,您需要先启用代码扫描。启用带 CodeQL 分析的代码扫描后,Copilot Autofix 将默认启用。想要快速设置,请参阅 代码扫描默认配置指南。
延伸阅读
要深入了解审查 AI 生成的代码,请参阅 审查 AI 生成的代码。