介绍
在减少对次要实现细节(如命名和样式约定)花费的时间时,代码评审更高效,而是将精力集中在满足用户需求的更高级别设计、解决问题和功能上。
在本文中,我们将展示如何通过 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 将审阅代码,并可能会提出以下注释和代码建议。
示例响应是一个范例
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 代码评审功能可以提出安全最佳实践建议,但code scanning的Copilot Autofix功能更进一步。 利用 code scanning 的功能与 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 for code scanning 帮助我们防止使用不足的密码哈希方法,并保护用户数据。
后续步骤
为了更高效和有效地利用 Copilot 的评审功能,请按照以下步骤开始。
- 创建自定义说明,特定于项目和存储库。 自行编写,或从我们的示例库中获取灵感。 请参阅“自定义说明”。
- 若要为存储库启用自动 Copilot 代码评审,请参阅 配置 GitHub Copilot 的自动代码评审。
- 若要为存储库配置 Copilot Autofix,需要启用 code scanning。 启用 code scanning 时,伴随 CodeQL 分析的启用,Copilot Autofix 将默认启用。 有关最简单的设置,请参阅 配置代码扫描的默认设置。
延伸阅读
若要更深入地查看 AI 生成的代码,请参阅 查看 AI 生成的代码。