Nếu có một bộ quy ước hoặc phương pháp hay tuỳ chỉnh mà bạn muốn Gemini Code Assist trên GitHub kiểm tra, bạn có thể thêm tệp styleguide.md vào thư mục gốc .gemini/ của kho lưu trữ. Người dùng phiên bản dành cho doanh nghiệp của Gemini Code Assist trên GitHub có thể sử dụng bảng điều khiển Google Cloud để thêm thông tin về hướng dẫn về phong cách để sử dụng trên nhiều kho lưu trữ.
Trong cả hai trường hợp, hướng dẫn về phong cách đều được coi là một tệp Markdown thông thường và mở rộng câu lệnh tiêu chuẩn mà Gemini Code Assist trên GitHub sử dụng. Để biết hướng dẫn về cách thêm một bản hướng dẫn về phong cách, hãy xem phần thêm tệp cấu hình.
Các mẫu xem xét mã tiêu chuẩn
Khi bạn không chỉ định hướng dẫn về kiểu tuỳ chỉnh, đây là các danh mục chính về những khía cạnh mà Gemini Code Assist tập trung vào khi xem xét mã:
Tính chính xác: Đảm bảo mã hoạt động như dự kiến và xử lý các trường hợp đặc biệt, kiểm tra lỗi logic, điều kiện xung đột hoặc việc sử dụng API không chính xác.
Hiệu suất: Xác định các điểm nghẽn tiềm ẩn về hiệu suất hoặc các khía cạnh cần tối ưu hoá, chẳng hạn như vòng lặp dư thừa, rò rỉ bộ nhớ, cấu trúc dữ liệu không hiệu quả, tính toán dư thừa, ghi nhật ký quá mức và thao tác chuỗi không hiệu quả.
Khả năng duy trì: Đánh giá khả năng đọc mã, tính mô-đun và việc tuân thủ các thành ngữ và phương pháp hay nhất về ngôn ngữ. Nhắm đến việc đặt tên không phù hợp cho các biến, hàm và lớp, thiếu chú thích hoặc tài liệu, mã phức tạp, trùng lặp mã, định dạng không nhất quán và số ma thuật.
Bảo mật: Xác định các lỗ hổng bảo mật tiềm ẩn trong quá trình xử lý dữ liệu hoặc xác thực dữ liệu đầu vào, chẳng hạn như việc lưu trữ dữ liệu nhạy cảm không an toàn, các cuộc tấn công chèn mã, chế độ kiểm soát quyền truy cập không đầy đủ, giả mạo yêu cầu trên nhiều trang web (CSRF) và tham chiếu trực tiếp đến đối tượng không an toàn (IDOR).
Khác: Các chủ đề khác cũng được cân nhắc khi xem xét yêu cầu kéo, chẳng hạn như thử nghiệm, hiệu suất, khả năng mở rộng, tính mô-đun và khả năng sử dụng lại, cũng như nhật ký lỗi và hoạt động giám sát.
Thêm tệp cấu hình
Bạn có thể sửa đổi hành vi của Gemini Code Assist bằng cách thêm các tệp cấu hình được hỗ trợ vào thư mục .gemini/ nằm trong thư mục gốc của kho lưu trữ. Gemini Code Assist sử dụng các tệp sau đây nếu bạn đã thêm chúng vào thư mục .gemini/:
config.yaml: Một tệp chứa nhiều tính năng có thể định cấu hình mà bạn có thể bật hoặc tắt, bao gồm cả việc chỉ định các tệp cần bỏ qua bằng cách sử dụng mẫu glob.styleguide.md: Một tệp Markdown hướng dẫn Gemini Code Assist bằng một số quy tắc cụ thể mà bạn muốn công cụ này tuân theo khi thực hiện quy trình đánh giá mã.
Ví dụ về config.yaml
Đoạn mã sau đây là một ví dụ về tệp config.yaml. Trong ví dụ này, mỗi thuộc tính được đặt thành giá trị mặc định mà Gemini Code Assist sử dụng. Bạn có thể sử dụng đoạn mã này làm mẫu để tạo tệp config.yaml của riêng mình:
have_fun: false
code_review:
disable: false
comment_severity_threshold: MEDIUM
max_review_comments: -1
pull_request_opened:
help: false
summary: true
code_review: true
include_drafts: true
ignore_patterns: []
config.yaml giản đồ
Đoạn mã sau đây là giản đồ cho tệp config.yaml. Tệp này xác định tất cả các lựa chọn cấu hình có thể có và các giá trị được chấp nhận:
$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: false. ignore_patterns: type: array items: type: string description: A list of glob patterns for files and directories that Gemini Code Assist should ignore. Files matching any pattern in this list will be skipped during interactions. Default: []. 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. include_drafts: type: boolean description: Enables agent functionality on draft pull requests. Default: true.
styleguide.md
Tệp styleguide.md không có giản đồ xác định. Thay vào đó, đây là nội dung mô tả bằng ngôn ngữ tự nhiên về cách bạn muốn Gemini Code Assist cấu trúc các quy trình đánh giá mã. Đoạn mã sau đây là một ví dụ về tệp 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
```
Quản lý các tệp cấu hình trên nhiều kho lưu trữ
Nếu có phiên bản Gemini Code Assist dành cho doanh nghiệp trên GitHub, bạn có thể sử dụng bảng điều khiển Google Cloud để áp dụng một bộ cấu hình và một hướng dẫn về phong cách cho tất cả các kho lưu trữ được liên kết trong một kết nối Developer Connect.
Xin lưu ý rằng nếu một kho lưu trữ được quản lý theo cách này cũng có config.yaml hoặc styleguide.md riêng, thì sẽ xảy ra hành vi sau:
Chế độ cài đặt
config.yamlcủa kho lưu trữ sẽ ghi đè chế độ cài đặt của Google Cloud Console.styleguide.mdcủa kho lưu trữ được kết hợp với hướng dẫn về kiểu chữ của bảng điều khiển Google Cloud.
Các bước sau đây cho thấy cách kiểm soát một bộ cấu hình và một hướng dẫn về kiểu trên nhiều kho lưu trữ. Các bước này giả định rằng trước đây bạn đã thiết lập phiên bản dành cho doanh nghiệp.
Trong Google Cloud Console, hãy chuyển đến trang Agents & Tools (Các tác nhân và công cụ) của Gemini Code Assist.
Trong phần Agents (Tác nhân), hãy tìm thẻ Code Assist Source Code Management (Quản lý mã nguồn của Trợ lý viết mã) rồi nhấp vào Nâng cao.
Ngăn Chỉnh sửa tính năng Quản lý mã nguồn của Trợ lý mã sẽ mở ra.
Trong bảng Connections (Kết nối), hãy nhấp vào tên của mối kết nối mà bạn muốn áp dụng cấu hình hoặc hướng dẫn về kiểu.
Trang chi tiết về mối kết nối sẽ mở ra.
Trong thẻ Cài đặt, hãy cập nhật các chế độ cài đặt mà bạn muốn thay đổi.
Trong thẻ Hướng dẫn về kiểu, hãy thêm hướng dẫn về kiểu mà bạn muốn các kho lưu trữ liên kết với mối kết nối này sử dụng.
Nhấp vào Lưu.