Gemini Code Assist에서 확인할 맞춤 권장사항 또는 규칙이 있는 경우 저장소의 .gemini/
루트 폴더에 styleguide.md
파일을 추가하면 됩니다. 이 파일은 일반 텍스트 파일로 취급되며 Gemini Code Assist에서 사용하는 표준 프롬프트를 확장합니다.
표준 코드 검토 패턴
맞춤 스타일 가이드가 지정되지 않은 경우 Gemini Code Assist에서 코드 검토에 중점을 두는 주요 카테고리 영역은 다음과 같습니다.
정확성: 코드가 의도한 대로 작동하고 특이 사례를 처리하는지 확인하고 로직 오류, 경합 상태 또는 잘못된 API 사용을 확인합니다.
효율성: 과도한 루프, 메모리 누수, 비효율적인 데이터 구조, 중복 계산, 과도한 로깅, 비효율적인 문자열 조작과 같은 잠재적인 성능 병목 현상 또는 최적화 영역을 식별합니다.
유지관리성: 코드 가독성, 모듈성, 언어 관용구 및 권장사항 준수를 평가합니다. 변수, 함수, 클래스의 이름 지정 불량, 주석 또는 문서 없음, 복잡한 코드, 코드 중복, 일관되지 않은 형식 지정, 매직 숫자를 타겟팅합니다.
보안: 민감한 정보의 안전하지 않은 저장소, 삽입 공격, 액세스 제어 부족, 크로스 사이트 요청 위조 (CSRF), 안전하지 않은 직접 객체 참조 (IDOR)와 같은 데이터 처리 또는 입력 유효성 검사의 잠재적 취약점을 식별합니다.
기타: 테스트, 성능, 확장성, 모듈성 및 재사용성, 오류 로깅 및 모니터링과 같은 다른 주제는 풀 요청을 검토할 때 고려됩니다.
구성 파일 추가
.gemini/
폴더는 config.yaml
및 styleguide.md
와 같은 Gemini Code Assist 관련 구성 파일을 호스팅합니다.
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