Skip to main content

使用 Copilot 生成优化的审查流程

使用 Copilot 自动进行审查,以优化和改进审查流程。

谁可以使用此功能?

Copilot代码审查 is available for Copilot Pro, GitHub Copilot Pro+, Copilot业务 and Copilot Enterprise. See Copilot plans.

介绍

在减少对次要实现细节(如命名和样式约定)花费的时间时,代码评审更高效,而是将精力集中在满足用户需求的更高级别设计、解决问题和功能上。

在本文中,我们将演示如何通过 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对话 的回答是不确定的,因此你可能会得到与这里所显示的不同的回答。

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自动修复 有所改善。 通过将 code scanning 的功能与 CodeQL 分析结合使用,以便分析 存储库中的代码,并找到安全漏洞和代码缺陷,Copilot自动修复 可以建议警报的解决方案,以便更高效地预防和减少漏洞。

例如,Copilot自动修复 可能会对代码进行以下说明。

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自动修复 还将提出漏洞潜在解决方法的代码建议供你审查。 在这种情况下,它可能会提出代码建议(如下所示)导入包并更新与哈希密码相关的代码。

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代码审查 也可能会重点表明需要生成唯一的 salt。

如你所看到的,自动识别漏洞以及修复漏洞的建议有助于确保安全成为优先事项。 利用 Copilot自动修复,可重点关注了解安全编码,以及最适合代码库和项目的解决方法。

使用 Copilot 优化审查

自动审阅注释可帮助你优化评论并更有效地保护代码,而不管你的体验级别如何。

  • 自定义指令有助于优化 Copilot代码审查 的响应,使其可满足我们项目和用户的具体需求。我们还了解到如何定制 Copilot 在反馈中提供的解释量。
  • Copilot代码审查 帮助我们快速改进了错误日志记录,并了解为什么这很重要。
  • code scanning 的 Copilot自动修复 帮助我们防止了使用不足的密码哈希方法,并保护用户数据。

后续步骤

为了更高效和有效地利用 Copilot 的评审功能,请按照以下步骤开始。

  1. 创建自定义说明,特定于项目和存储库。 自行编写,或从我们的示例库中获取灵感。 请参阅“自定义说明”。
  2. 若要为存储库启用自动 Copilot代码审查,请参阅 配置 GitHub Copilot 的自动代码评审
  3. 若要为存储库配置 Copilot自动修复,需要启用 code scanning。 启用 code scanning 与 CodeQL 后,默认情况下将启用 Copilot自动修复。 有关最简单的设置,请参阅 配置代码扫描的默认设置

延伸阅读

若要更深入地查看 AI 生成的代码,请参阅 查看 AI 生成的代码