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

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

## イントロダクション

コード レビューは、名前付けやスタイル規則などの小規模な実装の詳細に費やす時間を減らし、代わりにユーザーのニーズを満たすより高いレベルの設計、問題解決、機能に重点を置くと、より効率的になります。

この記事では、 Copilot からの自動レビューがレビュー プロセスの最適化にどのように役立つかについて説明します。これにより、わずかな変更に費やす時間が減り、微妙な問題解決に時間を費やし、実装に対する理解が深まるだけでなく、ユーザーのニーズを巧みに満たすことができます。

## 1. Copilot からのレビュー品質の向上

Copilot code review では、リポジトリ内のすべてのプル要求に対して自動レビューを提供し、コードで不要な変更をキャッチすることで、レビューをより効率的にすることができます。 カスタム命令と組み合わせた場合、 Copilot code review は、チームの作業方法、使用するツール、またはプロジェクトの詳細に合わせて調整された応答を提供できるため、より効果的です。

カスタム命令を記述するためのベスト プラクティスは次のとおりです。

* 個別の見出し
* 箇条書き
* 簡単で直接的な手順

例を見てみましょう。 Pythonを使用して注文処理システムを構築する場合、カスタム命令には、Python固有の書式設定、パフォーマンス、セキュリティで保護されたコーディングプラクティス、およびプロジェクトに直接関連するガイダンスが含まれる場合があります。 次の例は、カスタム命令のいくつかの行の外観を示しています。

```markdown
## 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 code review が有効になっている場合、 Copilot はドラフト モードから外れると、プル要求を自動的に確認します。

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

```python
def notify_inventory(product_id, quantity):
    requests.post("http://inventory-service/update", json={"product_id": product_id, "quantity": quantity})
```

これは機能的ですが、明確さと堅牢性に欠けています。 型の意図は暗黙的であり、ドキュメント文字列はなく、エラー処理やログ記録は含まれていないため、通知が実際に機能したかどうかは不明です。

Copilot はコードを確認し、次のコメントとコード提案を行うことができます。

> \[!NOTE] 次の応答は例です。 Copilot Chat の応答は非決定的であるため、ここで示したものとは異なる応答が返される可能性があります。

```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:
```

```python
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 スタイルのガイダンスに従い、タイムアウトとエラー ログをより適切に処理するための改善を提案すると同時に、提案の背後にある理由を簡潔に説明します。

> \[!NOTE] 受け入れてコミットする前に、常に Copilotの提案を慎重に確認してください。

このような自動レビュー コメントは、コーディング時に独自の理解を構築するのに役立ちます。また、レビュー時に他のユーザーに与えられたフィードバックに集中して絞り込むのに役立ちます。

## 3. セキュリティの脆弱性にフラグを設定して修正する

次に、注文処理システムにパスワードを格納する方法を改善するタスクを任されたとします。 念入りにユーザー パスワードを保護できるようにハッシュしたと思われるコードを含むプルリクエストを送信しました。

```python
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 reviewはセキュリティのベスト プラクティスの提案を行うことができますが、Copilot Autofixのcode scanningはさらに一歩進みます。
code scanning リポジトリ内のコードを分析し、セキュリティの脆弱性とコーディング エラーを見つけるために、CodeQL分析を使用してGitHubの機能を利用Copilot Autofix、アラートの修正プログラムを提案し、脆弱性の防止と軽減をより効率的に行うことができます。

たとえば、 Copilot Autofix コードに次のコメントを付けます。

```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 Autofix は、確認する脆弱性の潜在的な修正に関するコード提案も行います。 この場合、次のようなコード提案を行ってパッケージをインポートし、パスワードのハッシュに関連するコードを更新します。

```python
from argon2 import PasswordHasher
```

```python
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)
```

> \[!NOTE]
>
> * 変更を受け入れる前に、常に Copilot が提案する変更を確認して検証します。
> * この例では、 Copilot code review も固有の塩を生成する必要性を強調するかもしれません。

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

## 4. 信頼性、保守性、および網羅性チェックを追加する

これまで、Copilot code reviewはスタイルとデザインに関するプル要求ごとのフィードバックを提供しており、Copilot Autofixのcode scanningにはフラグが設定され、セキュリティの脆弱性が修正されています。 コードの長期的な正常性に重点を置くために、 GitHub Code Quality は信頼性、保守容易性、およびコード カバレッジ チェックを追加します。 明確に定義されたアンチパターンを検出するために、決定論的なルールベースの CodeQL 分析を使用します。

Code Quality を有効にすると、信頼性と保守容易性に関する指摘事項がプルリクエストにインラインコメントとして投稿され、各指摘には、ワンクリックでそのまま適用できる Copilot による自動修正が付きます。 また、変更によってテスト スイートから報告されたコード カバレッジが既定のブランチと比較して維持されるか減少するかを示すカバレッジ メトリックも報告されます。 これらの標準への準拠を強制する場合、ルールセットによっては、マージ前にルールベースの検出結果を解消し、カバレッジのしきい値を満たすことを必須にできます。

詳細については、「[GitHub のコード品質](/ja/code-security/concepts/code-quality/code-quality)」を参照してください。

## Copilotを使用してレビューを最適化しました。

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

* カスタム命令は、プロジェクトとユーザーのニーズに固有の Copilot code review からの応答を絞り込むのに役立ち、フィードバックで提供 Copilot 説明の量を調整する方法についても説明しました。
* Copilot code review  は、エラーログを迅速に改善し、それが重要な理由を理解するのに役立ちました。
* Copilot Autofix for code scanning は、不十分なパスワード ハッシュアプローチの使用を防ぎ、ユーザー データを保護するのに役立ちました。
* GitHub Code Quality は信頼性と保守容易性の問題を指摘し、プルリクエストでコードカバレッジを報告しました。また、ルールセットにより、マージ前にそれらの指摘事項が解決され、カバレッジしきい値を満たすことを必須にできます。

## 次のステップ

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

1. projectとリポジトリに固有のカスタム命令を作成します。 あなた自身で書くか、例のライブラリを参考にする。 「[カスタム指示](/ja/copilot/tutorials/customization-library/custom-instructions)」を参照してください。
2. リポジトリの自動 Copilot code review を有効にするには、 [Configuring code review by GitHub Copilot](/ja/copilot/how-tos/copilot-on-github/set-up-copilot/configure-automatic-review) を参照してください。
3. リポジトリの Copilot Autofix を構成するには、 code scanningを有効にする必要があります。
   code scanning分析を使用したCodeQLが有効になると、Copilot Autofixは既定で有効になります。 最も簡単なセットアップについては、 [コード スキャンの既定セットアップの構成](/ja/code-security/how-tos/find-and-fix-code-vulnerabilities/configure-code-scanning/configure-code-scanning) を参照してください。
4. 信頼性、保守容易性、カバレッジ チェックをプル要求に追加するには、リポジトリの GitHub Code Quality を有効にします。 「[GitHub Code Quality の有効化](/ja/code-security/how-tos/maintain-quality-code/enable-code-quality)」を参照してください。

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

AI によって生成されたコードの詳細については、 [AI によって生成されたコードを確認する](/ja/copilot/tutorials/review-ai-generated-code) を参照してください。