ปรับแต่งลักษณะการทํางานของฟีเจอร์ช่วยเขียนโค้ดของ Gemini ใน GitHub

หากมีชุดแนวทางปฏิบัติแนะนำหรือแบบแผนที่กำหนดเองที่คุณต้องการให้ Gemini Code Assist ตรวจสอบ คุณสามารถเพิ่มไฟล์ styleguide.md ลงในโฟลเดอร์รูท .gemini/ ของที่เก็บข้อมูล ระบบจะถือว่าไฟล์นี้เป็นไฟล์ข้อความธรรมดาและขยายพรอมต์มาตรฐานที่ Gemini Code Assist ใช้

รูปแบบการตรวจสอบโค้ดมาตรฐาน

หากไม่ได้ระบุคู่มือสไตล์ที่กำหนดเอง หมวดหมู่หลักของส่วนต่างๆ ที่ Gemini Code Assist จะมุ่งเน้นการตรวจสอบโค้ดมีดังนี้

  • ความถูกต้อง: ตรวจสอบว่าโค้ดทํางานตามที่ตั้งใจไว้และจัดการกรณีขอบ ตรวจหาข้อผิดพลาดด้านตรรกะ เงื่อนไขการแข่งขัน หรือการใช้ API ที่ไม่ถูกต้อง

  • ประสิทธิภาพ: ระบุจุดคอขวดด้านประสิทธิภาพที่อาจเกิดขึ้นหรือพื้นที่ที่ต้องการเพิ่มประสิทธิภาพ เช่น ลูปมากเกินไป หน่วยความจำรั่ว โครงสร้างข้อมูลที่มีประสิทธิภาพต่ำ การคํานวณซ้ำ การบันทึกมากเกินไป และการจัดการสตริงที่ไม่มีประสิทธิภาพ

  • ความสามารถในการบำรุงรักษา: ประเมินความอ่านง่ายของโค้ด ความเป็นโมดูล และการปฏิบัติตามนิพจน์ภาษาและแนวทางปฏิบัติแนะนำ มุ่งเน้นที่การตั้งชื่อตัวแปร ฟังก์ชัน และคลาสที่ไม่เหมาะสม ไม่มีความคิดเห็นหรือเอกสารประกอบ โค้ดที่ซับซ้อน โค้ดซ้ำ การจัดรูปแบบที่ไม่สอดคล้องกัน และตัวเลขที่ไม่แสดงความหมาย

  • ความปลอดภัย: ระบุช่องโหว่ที่อาจเกิดขึ้นในการจัดการข้อมูลหรือการตรวจสอบอินพุต เช่น การจัดเก็บข้อมูลที่ละเอียดอ่อนที่ไม่ปลอดภัย การโจมตีด้วยการแทรกโค้ด การควบคุมการเข้าถึงที่ไม่เพียงพอ การปลอมแปลงคําขอข้ามเว็บไซต์ (CSRF) และการอ้างอิงวัตถุโดยตรงที่ไม่ปลอดภัย (IDOR)

  • อื่นๆ: หัวข้ออื่นๆ ที่พิจารณาเมื่อตรวจสอบคำขอการดึงข้อมูล เช่น การทดสอบ ประสิทธิภาพ ความสามารถในการปรับขนาด ความเป็นโมดูลและความสามารถในการนำกลับมาใช้ซ้ำ รวมถึงการบันทึกและการตรวจสอบข้อผิดพลาด

เพิ่มไฟล์การกําหนดค่า

โฟลเดอร์ .gemini/ จะโฮสต์ไฟล์การกำหนดค่าที่เกี่ยวข้องกับ Gemini Code Assist เช่น config.yaml และ styleguide.md

ไฟล์ config.yaml มีฟีเจอร์ต่างๆ ที่กําหนดค่าได้ ซึ่งคุณเปิดหรือปิดใช้ได้ ไฟล์ข้อความ styleguide.md คือคู่มือสไตล์ ซึ่งจะบอกให้ Gemini Code Assist ใช้กฎบางอย่างที่คุณต้องการให้ทำตามเมื่อตรวจสอบโค้ด

หากต้องการเพิ่มไฟล์การกําหนดค่าเหล่านี้ ให้สร้างไฟล์ในโฟลเดอร์ .gemini/ ของที่เก็บข้อมูล และใช้ตารางต่อไปนี้เป็นข้อมูลอ้างอิง

ข้อมูลโค้ดต่อไปนี้เป็นตัวอย่างไฟล์ config.yaml ที่มีการตั้งค่าเริ่มต้น หากคุณไม่ได้ระบุการตั้งค่าใดๆ Gemini Code Assist จะใช้การตั้งค่าเริ่มต้น คุณสามารถใช้ข้อมูลโค้ดต่อไปนี้เป็นเทมเพลตเพื่อสร้างไฟล์ config.yaml ของคุณเอง

have_fun: true
code_review:
  disable: false
  comment_severity_threshold: MEDIUM
  max_review_comments: -1
  pull_request_opened:
    help: false
    summary: true
    code_review: true

ข้อมูลโค้ดต่อไปนี้เป็นตัวอย่างไฟล์ config.yaml ที่มีการตั้งค่าที่กำหนดเอง

$schema: "http://json-schema.org/draft-07/schema#"
title: RepoConfig
description: Configuration for Gemini Code Assist on a repository. All fields are optional and have default values.
type: object
properties:
  have_fun:
    type: boolean
    description: Enables fun features such as a poem in the initial pull request summary. Default: true.
  code_review:
    type: object
    description: Configuration for code reviews. All fields are optional and have default values.
    properties:
      disable:
        type: boolean
        description: Disables Gemini from acting on pull requests. Default: false.
      comment_severity_threshold:
        type: string
        enum:
          - LOW
          - MEDIUM
          - HIGH
          - CRITICAL
        description: The minimum severity of review comments to consider. Default: MEDIUM.
      max_review_comments:
        type: integer
        format: int64
        description: The maximum number of review comments to consider. Use -1 for unlimited. Default: -1.
      pull_request_opened:
        type: object
        description: Configuration for pull request opened events. All fields are optional and have default values.
        properties:
          help:
            type: boolean
            description: Posts a help message on pull request open. Default: false.
          summary:
            type: boolean
            description: Posts a pull request summary on the pull request open. Default: true.
          code_review:
            type: boolean
            description: Posts a code review on pull request open. Default: true.

ข้อมูลโค้ดต่อไปนี้เป็นตัวอย่างไฟล์ 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.

# Example
```python
"""Module for user authentication."""

import hashlib
import logging
import os

from companyx.db import user_database

LOGGER = logging.getLogger(__name__)

def hash_password(password: str) -> str:
  """Hashes a password using SHA-256.

  Args:
      password (str): The password to hash.

  Returns:
      str: The hashed password.
  """
  salt = os.urandom(16)
  salted_password = salt + password.encode('utf-8')
  hashed_password = hashlib.sha256(salted_password).hexdigest()
  return f"{salt.hex()}:{hashed_password}"

def authenticate_user(username: str, password: str) -> bool:
  """Authenticates a user against the database.

  Args:
      username (str): The user's username.
      password (str): The user's password.

  Returns:
      bool: True if the user is authenticated, False otherwise.
  """
  try:
      user = user_database.get_user(username)
      if user is None:
          LOGGER.warning("Authentication failed: User not found - %s", username)
          return False

      stored_hash = user.password_hash
      salt, hashed_password = stored_hash.split(':')
      salted_password = bytes.fromhex(salt) + password.encode('utf-8')
      calculated_hash = hashlib.sha256(salted_password).hexdigest()

      if calculated_hash == hashed_password:
          LOGGER.info("User authenticated successfully - %s", username)
          return True
      else:
          LOGGER.warning("Authentication failed: Incorrect password - %s", username)
          return False
  except Exception as e:
      LOGGER.error("An error occurred during authentication: %s", e)
      return False