Skip to main content

Copilot を使用して最適化されたレビュー プロセスを構築する

Copilot を使用してレビューを自動化し、レビュー プロセスを最適化および改善します。

この機能を使用できるユーザーについて

Copilot コード レビュー is available for Copilot Pro, GitHub Copilot Pro+, Copilot Business 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.

次のセクションでは、サンプルのカスタム命令が pull request に対して提供するレビュー コメント Copilot にプラスの影響を与える方法について説明します。

2. スタイルの規則とパフォーマンスに対処するためのレビューを自動化する

Copilot コード レビュー が自動的に有効になっている場合、Copilot は、ドラフト モードから外れると、プル要求を自動的に確認します。

注文処理システムのインベントリを更新する次の関数を含む pull request を送信するとします。

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 コード レビュー はセキュリティのベストプラクティスの提案を提供しますが、Copilotの自動修正 は code scanning に関してさらに一歩進んでいます。 code scanning と CodeQL 分析の機能を利用して、 GitHub リポジトリ内のコードを分析し、セキュリティの脆弱性とコーディング エラーを見つけることができます。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 コード レビュー も、一意の塩を生成する必要性を強調するかもしれません。

ご覧のように、脆弱性を自動的に特定し、修正するための推奨事項を示します。これは、セキュリティを優先するのに役立ちます。 Copilotの自動修正 を使用すると、セキュアなコーディングを理解し、コードベースとプロジェクトに最適な修正に集中できます。

Copilot による最適化されたレビュー

自動レビュー コメントは、エクスペリエンスのレベルに関係なく、レビューを最適化し、コードをより効率的にセキュリティで保護するのに役立ちます。

  • カスタム命令は、Copilot コード レビュー からの応答を絞り込むのに役立ち、プロジェクトとユーザーのニーズに固有であり、フィードバックで提供される Copilot の説明量を調整する方法についても説明しました。
  • Copilot コード レビュー は、エラー ログを迅速に改善し、それが重要な理由を理解するのに役立ちました。
  • code scanning の Copilotの自動修正 は、不十分なパスワードハッシュアプローチの使用を防ぎ、ユーザーデータを守るのに役立ちました。

次のステップ

Copilotのレビュー機能を使用してレビューをより効率的かつ効果的にするには、次の手順に従って作業を開始します。

  1. プロジェクトとリポジトリに固有のカスタム命令を作成します。 あなた自身で書くか、例のライブラリを参考にする。 「カスタム指示」を参照してください。
  2. リポジトリで自動の Copilot コード レビュー を有効にするには、GitHub Copilot による自動コード レビューの構成 を参照してください。
  3. リポジトリに Copilotの自動修正 を構成するには、 code scanning を有効にする必要があります。 CodeQL 分析を有効にした code scanning が有効になると、Copilotの自動修正 が既定で有効になります。 最も簡単なセットアップについては、 コード スキャンの既定セットアップの構成 を参照してください。

詳細については、次を参照してください。

AI によって生成されたコードの詳細については、 AI によって生成されたコードを確認する を参照してください。