コードレビュー スタイルガイド

コードレビューの実行時に Gemini Code Assist on GitHub でチェックまたは遵守するカスタムのベスト プラクティスまたは規則がある場合は、リポジトリの .gemini/ ルートフォルダに styleguide.md Markdown ファイルを追加できます。GitHub の Gemini Code Assist のエンタープライズ バージョンのユーザーは、Google Cloud コンソールを使用して、複数のリポジトリで使用するスタイルガイド情報を追加できます。どちらの場合も、スタイルガイドは通常の Markdown ファイルとして扱われ、GitHub の Gemini Code Assist が使用する標準プロンプトが拡張されます。

標準的なコードレビュー パターン

カスタム スタイルガイドが指定されていない場合、Gemini Code Assist がコードレビューの対象とする主なカテゴリは次のとおりです。

  • 正確性: コードが意図したとおりに機能し、エッジケースを処理することを確認します。論理エラー、競合状態、API の誤った使用がないかチェックします。

  • 効率: 過剰なループ、メモリリーク、非効率的なデータ構造、冗長な計算、過剰なロギング、非効率的な文字列操作など、パフォーマンスのボトルネックや最適化の対象となる領域を特定します。

  • 保守性: コードの読みやすさ、モジュール性、言語の慣用句とベスト プラクティスの遵守を評価します。変数、関数、クラスの命名が不適切である、コメントやドキュメントがない、コードが複雑である、コードの重複がある、形式が不整合である、マジック ナンバーがあるといった問題が対象となります。

  • セキュリティ: センシティブ データの安全でない保存、インジェクション攻撃、不十分なアクセス制御、クロスサイト リクエスト フォージェリ(CSRF)、安全でない直接オブジェクト参照(IDOR)など、データ処理や入力検証における潜在的な脆弱性を特定します。

  • その他: プルリクエストのレビュー時に、テスト、パフォーマンス、スケーラビリティ、モジュール性と再利用性、エラー ロギングとモニタリングなどの他のトピックが考慮されます。

スタイルガイドの例

styleguide.md ファイルに定義されたスキーマがありません。これは、Gemini Code Assist にコードレビューの構造をどのようにしてほしいかを自然言語で記述したものです。次のコード スニペットは、styleguide.md ファイルの例です。

# Company X Python Style Guide

## Introduction

This style guide outlines the coding conventions for Python code developed at
Company X. It's based on PEP 8, but with some modifications to address
specific needs and preferences within our organization.

## Key Principles

*   **Readability:** Code should be easy to understand for all team members.
*   **Maintainability:** Code should be easy to modify and extend.
*   **Consistency:** Adhering to a consistent style across all projects
    improves collaboration and reduces errors.
*   **Performance:** While readability is paramount, code should be efficient.

## Deviations from PEP 8

### Line Length

* **Maximum line length:** 100 characters (instead of PEP 8's 79).
    *   Modern screens allow for wider lines, improving code readability in
        many cases.
    *   Many common patterns in our codebase, like long strings or URLs, often
        exceed 79 characters.

### Indentation

*   **Use 4 spaces per indentation level.** (PEP 8 recommendation)

### Imports

*   **Group imports:**
    *   Standard library imports
    *   Related third party imports
    *   Local application/library specific imports
*   **Absolute imports:** Always use absolute imports for clarity.
*   **Import order within groups:**  Sort alphabetically.

### Naming Conventions

*   **Variables:** Use lowercase with underscores (snake_case): `user_name`, `total_count`
*   **Constants:**  Use uppercase with underscores: `MAX_VALUE`, `DATABASE_NAME`
*   **Functions:** Use lowercase with underscores (snake_case): `calculate_total()`, `process_data()`
*   **Classes:** Use CapWords (CamelCase): `UserManager`, `PaymentProcessor`
*   **Modules:** Use lowercase with underscores (snake_case): `user_utils`, `payment_gateway`

### Docstrings

*   **Use triple double quotes (`"""Docstring goes here."""`) for all docstrings.**
*   **First line:** Concise summary of the object's purpose.
*   **For complex functions/classes:** Include detailed descriptions of
    parameters, return values, attributes, and exceptions.
*   **Use Google style docstrings:** This helps with automated documentation generation.
    ```python
    def my_function(param1, param2):
        """Single-line summary.

        More detailed description, if necessary.

        Args:
            param1 (int): The first parameter.
            param2 (str): The second parameter.

        Returns:
            bool: The return value. True for success, False otherwise.

        Raises:
            ValueError: If `param2` is invalid.
        """
        # function body here
    ```

### Type Hints

*   **Use type hints:**  Type hints improve code readability and help catch
    errors early.
*   **Follow PEP 484:**  Use the standard type hinting syntax.

### Comments

*   **Write clear and concise comments:** Explain the "why" behind the code,
    not just the "what".
*   **Comment sparingly:** Well-written code should be self-documenting where
    possible.
*   **Use complete sentences:** Start comments with a capital letter and use
    proper punctuation.

### Logging

*   **Use a standard logging framework:**  Company X uses the built-in
    `logging` module.
*   **Log at appropriate levels:** DEBUG, INFO, WARNING, ERROR, CRITICAL
*   **Provide context:** Include relevant information in log messages to aid
    debugging.

### Error Handling

*   **Use specific exceptions:** Avoid using broad exceptions like `Exception`.
*   **Handle exceptions gracefully:** Provide informative error messages and
    avoid crashing the program.
*   **Use `try...except` blocks:**  Isolate code that might raise exceptions.

## Tooling

*   **Code formatter:**  [Specify formatter, e.g., Black] - Enforces
    consistent formatting automatically.
*   **Linter:**  [Specify linter, e.g., Flake8, Pylint] - Identifies potential
    issues and style violations.

複数のリポジトリにわたってスタイルガイドを管理する

GitHub の Gemini Code Assist のエンタープライズ バージョンを使用している場合は、複数のリポジトリに 1 つのスタイルガイドを適用できます。リポジトリは Developer Connect 接続ごとにグループ化され、その集合的なスタイルガイドの管理は Google Cloud コンソールで行われます。

リポジトリがグループの一部として管理され、独自に styleguide.md ファイルを持っている場合、リポジトリの styleguide.md はグループのスタイルガイドと組み合わされます。

次の手順では、エンタープライズ バージョンのユーザーが複数のリポジトリで 1 つのスタイルガイドを制御する方法について説明します。以下の手順は、GitHub で Gemini Code Assist を設定していることを前提としています。

  1. Google Cloud コンソールで、Gemini Code Assist の [エージェントとツール] ページに移動します。

    [エージェントとツール] に移動

  2. [エージェント] セクションで、[Code Assist ソースコード管理] カードを見つけて [詳細] をクリックします。

    [ソースコード管理用 Code Assist を編集] ペインが開きます。

  3. [接続] テーブルで、スタイルガイドを適用する接続の名前をクリックします。

    接続の詳細ページが開きます。

  4. [スタイルガイド] タブで、この接続に関連付けられたリポジトリで使用するスタイルガイドを追加します。

  5. [保存] をクリックします。

次のステップ