{"meta":{"title":"を使用して最適化されたレビュー プロセスを構築する Copilot","intro":"Copilotを使用してレビューを自動化し、レビュー プロセスを最適化および改善します。","product":"GitHub Copilot","breadcrumbs":[{"href":"/ja/copilot","title":"GitHub Copilot"},{"href":"/ja/copilot/tutorials","title":"チュートリアル"},{"href":"/ja/copilot/tutorials/optimize-code-reviews","title":"コード レビューを最適化する"}],"documentType":"article"},"body":"# を使用して最適化されたレビュー プロセスを構築する Copilot\n\nCopilotを使用してレビューを自動化し、レビュー プロセスを最適化および改善します。\n\n## イントロダクション\n\nコード レビューは、名前付けやスタイル規則などの小規模な実装の詳細に費やす時間を減らし、代わりにユーザーのニーズを満たすより高いレベルの設計、問題解決、機能に重点を置くと、より効率的になります。\n\nこの記事では、 Copilot からの自動レビューがレビュー プロセスの最適化にどのように役立つかについて説明します。これにより、わずかな変更に費やす時間が減り、微妙な問題解決に時間を費やし、実装に対する理解が深まるだけでなく、ユーザーのニーズを巧みに満たすことができます。\n\n## 1. Copilot からのレビュー品質の向上\n\nCopilot code review では、リポジトリ内のすべてのプル要求に対して自動レビューを提供し、コードで不要な変更をキャッチすることで、レビューをより効率的にすることができます。 カスタム命令と組み合わせた場合、 Copilot code review は、チームの作業方法、使用するツール、またはプロジェクトの詳細に合わせて調整された応答を提供できるため、より効果的です。\n\nカスタム命令を記述するためのベスト プラクティスは次のとおりです。\n\n* 個別の見出し\n* 箇条書き\n* 簡単で直接的な手順\n\n例を見てみましょう。 Pythonを使用して注文処理システムを構築する場合、カスタム命令には、Python固有の書式設定、パフォーマンス、セキュリティで保護されたコーディングプラクティス、およびプロジェクトに直接関連するガイダンスが含まれる場合があります。 次の例は、カスタム命令のいくつかの行の外観を示しています。\n\n```markdown\n## Repository context\n- This repository implements an order processing system (order intake, payment, fulfillment) where correctness, security, and auditability are critical. \n\n## Style and conventions\n- Follow the PEP 8 and PEP 257 style guide for Python.\n- Use clear, domain-relevant names (orders, payments, inventory, customers, shipments).\n- Prefer small, focused functions and methods with clearly defined responsibilities.\n\n## Secure coding \n- Verify proper input validation and sanitization.\n- Review authentication and authorization logic.\n\n## Error handling guidelines\n- Handle timeouts and network errors gracefully.\n- Ensure failures are logged with enough detail for debugging.\n\n## Order processing context\n- Ensure order creation, payment handling, and updates are idempotent to avoid duplicate orders or duplicate charges.\n- Validate and normalize all order, payment, and customer data before persisting or acting on it.\n- Do not log or persist sensitive data (passwords, raw payment details, full identifiers) without hashing, encryption, or redaction.\n- 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.\n\n## Review style\n- Be concise, specific and actionable.\n- Explain the \"why\" behind recommendations using bullet points.\n```\n\n次のセクションでは、サンプルのカスタム命令が pull request に対して提供 Copilot レビュー コメントにプラスの影響を与える方法について説明します。\n\n## 2. スタイルの規則とパフォーマンスに対処するためのレビューを自動化する\n\n自動 Copilot code review が有効になっている場合、 Copilot はドラフト モードから外れると、プル要求を自動的に確認します。\n\n注文処理システムのインベントリを更新する次の関数を含む pull request を送信するとします。\n\n```python\ndef notify_inventory(product_id, quantity):\n    requests.post(\"http://inventory-service/update\", json={\"product_id\": product_id, \"quantity\": quantity})\n```\n\nこれは機能的ですが、明確さと堅牢性に欠けています。 型の意図は暗黙的であり、ドキュメント文字列はなく、エラー処理やログ記録は含まれていないため、通知が実際に機能したかどうかは不明です。\n\nCopilot はコードを確認し、次のコメントとコード提案を行うことができます。\n\n> \\[!NOTE] 次の応答は例です。 Copilot Chat の応答は非決定的であるため、ここで示したものとは異なる応答が返される可能性があります。\n\n```copilot\nMissing error handling for network calls\n\nThe notify_inventory function makes a synchronous network call without any error handling for timeouts, connection failures, or non-200 responses.\n\nWhy this matters:\n\n- Network failures will cause unhandled exceptions and crash the order processing flow\n- Orders could be marked as CONFIRMED but inventory never gets updated\n- This violates the requirement to \"handle timeouts and network errors gracefully\"\n- Failures won't be logged with enough detail for debugging\n\nRecommendation: Add proper error handling with timeout and logging:\n```\n\n```python\ndef notify_inventory(product_id: str, quantity: int) -> bool:\n    \"\"\"Notify the inventory service of order placement.\n\n    Args:\n        product_id: The product identifier.\n        quantity: The quantity ordered.\n\n    Returns:\n        True if the notification succeeded; False otherwise.\n    \"\"\"\n    try:\n        response = requests.post(\n            \"http://inventory-service/update\",\n            json={\"product_id\": product_id, \"quantity\": quantity},\n            timeout=5,\n        )\n        response.raise_for_status()\n        logger.info(\n            \"Inventory notified for product %s, quantity %d (status %d)\",\n            product_id,\n            quantity,\n            response.status_code,\n        )\n        return True\n    except requests.exceptions.Timeout:\n        logger.error(\n            \"Timeout notifying inventory for product %s, quantity %d\",\n            product_id,\n            quantity,\n            exc_info=True,\n        )\n    except requests.exceptions.RequestException:\n        logger.error(\n            \"Failed to notify inventory for product %s, quantity %d\",\n            product_id,\n            quantity,\n            exc_info=True,\n        )\n    return False\n```\n\nCopilot からの応答では、その推奨事項の内容は、カスタム指示のガイダンスに従っています。 この例では、Pythonの PEP 8 および 257 スタイルのガイダンスに従い、タイムアウトとエラー ログをより適切に処理するための改善を提案すると同時に、提案の背後にある理由を簡潔に説明します。\n\n> \\[!NOTE] 受け入れてコミットする前に、常に Copilotの提案を慎重に確認してください。\n\nこのような自動レビュー コメントは、コーディング時に独自の理解を構築するのに役立ちます。また、レビュー時に他のユーザーに与えられたフィードバックに集中して絞り込むのに役立ちます。\n\n## 3. セキュリティの脆弱性にフラグを設定して修正する\n\n次に、注文処理システムにパスワードを格納する方法を改善するタスクを任されたとします。 念入りにユーザー パスワードを保護できるようにハッシュしたと思われるコードを含むプルリクエストを送信しました。\n\n```python\ndef get_password_hash(password: str, salt: str) -> str:\n    \"\"\"Hash a password with the given salt using SHA-256.\n\n    Returns the hexadecimal representation of the hashed password.\n    \"\"\"\n    return hashlib.sha256((password + salt).encode()).hexdigest()\n\nclass User:\n    \"\"\"Represents a user in the order processing system.\"\"\"\n\n    def __init__(self, username: str, password: str, salt: str):\n        \"\"\"Initialize a User with username, password, and salt.\n\n        The password is hashed and stored for authentication.\n        \"\"\"\n        self.username = username\n        self.salt = salt\n        self.password_hash = get_password_hash(password, self.salt)\n\n    def verify_password(self, password: str) -> bool:\n        \"\"\"Verify a plain-text password against the stored hash.\"\"\"\n        return get_password_hash(password, self.salt) == self.password_hash\n```\n\nただし、この例では、SHA-256 を使用することは許容できません。これは、ユーザー パスワードを保護するのに十分な計算コストがかからないためです。\n\nCopilot code reviewはセキュリティのベスト プラクティスの提案を行うことができますが、Copilot Autofixのcode scanningはさらに一歩進みます。\ncode scanning リポジトリ内のコードを分析し、セキュリティの脆弱性とコーディング エラーを見つけるために、CodeQL分析を使用してGitHubの機能を利用Copilot Autofix、アラートの修正プログラムを提案し、脆弱性の防止と軽減をより効率的に行うことができます。\n\nたとえば、 Copilot Autofix コードに次のコメントを付けます。\n\n```copilot\nUsing SHA-256 for password hashing is insecure for authentication systems. SHA-256 is designed to be fast, making it vulnerable to brute-force attacks. \n\nTo 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.\n```\n\nCopilot Autofix は、確認する脆弱性の潜在的な修正に関するコード提案も行います。 この場合、次のようなコード提案を行ってパッケージをインポートし、パスワードのハッシュに関連するコードを更新します。\n\n```python\nfrom argon2 import PasswordHasher\n```\n\n```python\ndef get_initial_hash(password: str):\n    ph = PasswordHasher()\n    return ph.hash(password)\n\ndef check_password(password: str, known_hash):\n    ph = PasswordHasher()\n    return ph.verify(known_hash, password)\n```\n\n> \\[!NOTE]\n>\n> * 変更を受け入れる前に、常に Copilot が提案する変更を確認して検証します。\n> * この例では、 Copilot code review も固有の塩を生成する必要性を強調するかもしれません。\n\nご覧のように、脆弱性を自動的に特定し、修正するための推奨事項を示します。これは、セキュリティを優先するのに役立ちます。\nCopilot Autofix を使用すると、セキュリティで保護されたコーディングを理解し、コード ベースとプロジェクトに最適な修正に集中できます。\n\n## 4. 信頼性、保守性、および網羅性チェックを追加する\n\nこれまで、Copilot code reviewはスタイルとデザインに関するプル要求ごとのフィードバックを提供しており、Copilot Autofixのcode scanningにはフラグが設定され、セキュリティの脆弱性が修正されています。 コードの長期的な正常性に重点を置くために、 GitHub Code Quality は信頼性、保守容易性、およびコード カバレッジ チェックを追加します。 明確に定義されたアンチパターンを検出するために、決定論的なルールベースの CodeQL 分析を使用します。\n\nCode Quality を有効にすると、信頼性と保守容易性に関する指摘事項がプルリクエストにインラインコメントとして投稿され、各指摘には、ワンクリックでそのまま適用できる Copilot による自動修正が付きます。 また、変更によってテスト スイートから報告されたコード カバレッジが既定のブランチと比較して維持されるか減少するかを示すカバレッジ メトリックも報告されます。 これらの標準への準拠を強制する場合、ルールセットによっては、マージ前にルールベースの検出結果を解消し、カバレッジのしきい値を満たすことを必須にできます。\n\n詳細については、「[GitHub のコード品質](/ja/code-security/concepts/code-quality/code-quality)」を参照してください。\n\n## Copilotを使用してレビューを最適化しました。\n\n自動レビュー コメントは、エクスペリエンスのレベルに関係なく、レビューを最適化し、コードをより効率的にセキュリティで保護するのに役立ちます。\n\n* カスタム命令は、プロジェクトとユーザーのニーズに固有の Copilot code review からの応答を絞り込むのに役立ち、フィードバックで提供 Copilot 説明の量を調整する方法についても説明しました。\n* Copilot code review  は、エラーログを迅速に改善し、それが重要な理由を理解するのに役立ちました。\n* Copilot Autofix for code scanning は、不十分なパスワード ハッシュアプローチの使用を防ぎ、ユーザー データを保護するのに役立ちました。\n* GitHub Code Quality は信頼性と保守容易性の問題を指摘し、プルリクエストでコードカバレッジを報告しました。また、ルールセットにより、マージ前にそれらの指摘事項が解決され、カバレッジしきい値を満たすことを必須にできます。\n\n## 次のステップ\n\nCopilotのレビュー機能を使用してレビューをより効率的かつ効果的にするには、次の手順に従って作業を開始します。\n\n1. projectとリポジトリに固有のカスタム命令を作成します。 あなた自身で書くか、例のライブラリを参考にする。 「[カスタム指示](/ja/copilot/tutorials/customization-library/custom-instructions)」を参照してください。\n2. リポジトリの自動 Copilot code review を有効にするには、 [Configuring code review by GitHub Copilot](/ja/copilot/how-tos/copilot-on-github/set-up-copilot/configure-automatic-review) を参照してください。\n3. リポジトリの Copilot Autofix を構成するには、 code scanningを有効にする必要があります。\n   code scanning分析を使用したCodeQLが有効になると、Copilot Autofixは既定で有効になります。 最も簡単なセットアップについては、 [コード スキャンの既定セットアップの構成](/ja/code-security/how-tos/find-and-fix-code-vulnerabilities/configure-code-scanning/configure-code-scanning) を参照してください。\n4. 信頼性、保守容易性、カバレッジ チェックをプル要求に追加するには、リポジトリの GitHub Code Quality を有効にします。 「[GitHub Code Quality の有効化](/ja/code-security/how-tos/maintain-quality-code/enable-code-quality)」を参照してください。\n\n## 詳細については、次を参照してください。\n\nAI によって生成されたコードの詳細については、 [AI によって生成されたコードを確認する](/ja/copilot/tutorials/review-ai-generated-code) を参照してください。"}