소개
코드 검토는 이름 지정 및 스타일 규칙과 같은 사소한 구현 세부 정보에 더 적은 시간을 소비하는 대신 사용자 요구를 충족하는 더 높은 수준의 디자인, 문제 해결 및 기능에 집중하는 경우 더 효율적입니다.
이 문서에서는 Copilot의 자동 검토가 검토 프로세스를 최적화하는 데 어떻게 도움이 되는지 보여 주므로 사소한 변경에 대한 시간을 줄이고 미묘한 문제 해결에 더 많은 시간을 할애하고 단순히 적절하지는 않지만 사용자 요구를 능숙하게 충족하는 구현에 대한 심층적인 이해를 제공합니다.
1. Copilot를 통한 리뷰 품질 향상
Copilot 코드 검토은(는) 리포지토리의 모든 끌어오기 요청에 대해 자동화된 검토를 제공하고 코드에서 원하지 않는 변경 내용을 catch하여 검토 효율성을 높일 수 있습니다. 사용자 지정 지침과 함께 사용할 때 은(는) 팀의 작업 방식, 사용 중인 도구, 프로젝트의 특성에 맞춘 맞춤형 응답을 제공하므로 더욱 효과적입니다.
사용자 지정 지침을 작성하는 모범 사례는 다음과 같습니다.
- 고유 제목
- 글머리 기호
- 짧고 직접적인 지침
예를 살펴보겠습니다. Python을 사용하여 주문 처리 시스템을 빌드하는 경우 사용자 지정 지침에는 프로젝트와 직접 관련된 지침뿐만 아니라 Python 관련 서식, 성능 및 보안 코딩 사례가 포함될 수 있습니다. 다음 예제에서는 사용자 지정 지침의 몇 줄이 어떻게 표시되는지 보여 줍니다.
## Repository context
- This repository implements an order processing system (order intake, payment, fulfillment) where correctness, security, and auditability are critical.
## Style and conventions
- Follow the PEP 8 and PEP 257 style guide for Python.
- Use clear, domain-relevant names (orders, payments, inventory, customers, shipments).
- Prefer small, focused functions and methods with clearly defined responsibilities.
## Secure coding
- Verify proper input validation and sanitization.
- Review authentication and authorization logic.
## Error handling guidelines
- Handle timeouts and network errors gracefully.
- Ensure failures are logged with enough detail for debugging.
## Order processing context
- Ensure order creation, payment handling, and updates are idempotent to avoid duplicate orders or duplicate charges.
- Validate and normalize all order, payment, and customer data before persisting or acting on it.
- Do not log or persist sensitive data (passwords, raw payment details, full identifiers) without hashing, encryption, or redaction.
- 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.
## Review style
- Be concise, specific and actionable.
- Explain the "why" behind recommendations using bullet points.
다음 섹션에서는 사용자 지정 지침 예시를 통해 Copilot가 생성하는 풀 리퀘스트 검토 코멘트의 품질을 어떻게 향상시킬 수 있는지 알아봅니다.
2. 스타일 규칙 및 성능을 고려하기 위한 리뷰 자동화
자동 Copilot 코드 검토 기능을 활성화하면, Copilot가 초안 모드를 종료하는 즉시 풀 리퀘스트에 대한 검토가 자동으로 수행됩니다.
주문 처리 시스템에서 인벤토리를 업데이트하기 위해 다음 함수가 포함된 끌어오기 요청을 제출한다고 상상해 보십시오.
def notify_inventory(product_id, quantity):
requests.post("http://inventory-service/update", json={"product_id": product_id, "quantity": quantity})
이는 기능적이지만 명확성과 견고성이 부족합니다. 형식의 의도는 암시적이고, 문서 문자열이 없으며, 오류 처리 또는 로깅을 포함하지 않으므로 알림이 실제로 작동했는지 여부를 불분명하게 만듭니다.
Copilot은 코드를 검토하여 주석과 코드 개선 제안을 제공할 수 있습니다.
참고 항목
다음 응답이 예제입니다. Copilot 채팅 응답은 비결정적이므로 여기에 표시된 응답과 다른 응답을 얻을 수 있습니다.
Missing error handling for network calls
The notify_inventory function makes a synchronous network call without any error handling for timeouts, connection failures, or non-200 responses.
Why this matters:
- Network failures will cause unhandled exceptions and crash the order processing flow
- Orders could be marked as CONFIRMED but inventory never gets updated
- This violates the requirement to "handle timeouts and network errors gracefully"
- Failures won't be logged with enough detail for debugging
Recommendation: Add proper error handling with timeout and logging:
def notify_inventory(product_id: str, quantity: int) -> bool:
"""Notify the inventory service of order placement.
Args:
product_id: The product identifier.
quantity: The quantity ordered.
Returns:
True if the notification succeeded; False otherwise.
"""
try:
response = requests.post(
"http://inventory-service/update",
json={"product_id": product_id, "quantity": quantity},
timeout=5,
)
response.raise_for_status()
logger.info(
"Inventory notified for product %s, quantity %d (status %d)",
product_id,
quantity,
response.status_code,
)
return True
except requests.exceptions.Timeout:
logger.error(
"Timeout notifying inventory for product %s, quantity %d",
product_id,
quantity,
exc_info=True,
)
except requests.exceptions.RequestException:
logger.error(
"Failed to notify inventory for product %s, quantity %d",
product_id,
quantity,
exc_info=True,
)
return False
Copilot는 사용자 지정 권장 사항 지침을 따라 응답을 생성합니다. 이 예제에서는 Python에 대한 PEP 8 및 257 스타일 지침을 따르고 제안 뒤에 있는 추론을 간결하게 설명하면서 시간 제한 및 오류 로깅을 더 잘 처리할 수 있도록 개선 사항을 제안합니다.
참고 항목
수락하고 커밋하기 전에 Copilot의 제안을 항상 신중하게 검토하세요.
이와 같은 자동 검토 주석은 코딩할 때 사용자 고유의 이해를 구축하도록 지원하거나 검토할 때 다른 사용자에게 주어진 피드백을 집중하고 좁히는 데 도움이 될 수 있습니다.
3. 보안 취약성을 발견하고 수정하다
다음으로, 주문 처리 시스템에 암호가 저장되는 방식을 개선하는 임무를 수행했다고 상상해 보십시오. 사용자 암호를 충분히 해시하여 보호할 수 있다고 생각되는 코드를 사용하여 끌어오기 요청을 제출합니다.
def get_password_hash(password: str, salt: str) -> str:
"""Hash a password with the given salt using SHA-256.
Returns the hexadecimal representation of the hashed password.
"""
return hashlib.sha256((password + salt).encode()).hexdigest()
class User:
"""Represents a user in the order processing system."""
def __init__(self, username: str, password: str, salt: str):
"""Initialize a User with username, password, and salt.
The password is hashed and stored for authentication.
"""
self.username = username
self.salt = salt
self.password_hash = get_password_hash(password, self.salt)
def verify_password(self, password: str) -> bool:
"""Verify a plain-text password against the stored hash."""
return get_password_hash(password, self.salt) == self.password_hash
그러나 이 예제에서는 사용자 암호를 보호할 만큼 계산 비용이 많이 들지 않으므로 SHA-256을 사용하는 것은 허용되지 않습니다.
Copilot 코드 검토가 보안 모범 사례를 제안하는 반면, code scanning의 Copilot Autofix는 한 단계 더 나아갑니다. code scanning을 CodeQL 분석과 함께 사용하면 리포지토리의 코드에서 보안 취약성과 코딩 오류를 발견할 수 있으며, Copilot Autofix는 이러한 경고에 대한 수정 사항을 제안하여 취약성을 더욱 효과적으로 예방하고 해결할 수 있도록 지원합니다.
예를 들어, Copilot Autofix를 사용하면 코드에 다음과 같은 주석을 작성할 수 있습니다.
Using SHA-256 for password hashing is insecure for authentication systems. SHA-256 is designed to be fast, making it vulnerable to brute-force attacks.
To 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.
Copilot Autofix는 발견된 취약성에 대해 검토 가능한 코드 수정안을 제시합니다. 이 경우 아래와 같이 코드를 제안하여 패키지를 가져오고 암호 해시와 관련된 코드를 업데이트할 수 있습니다.
from argon2 import PasswordHasher
def get_initial_hash(password: str):
ph = PasswordHasher()
return ph.hash(password)
def check_password(password: str, known_hash):
ph = PasswordHasher()
return ph.verify(known_hash, password)
참고 항목
- 변경 내용을 수락하기 전에 항상 Copilot 제안 사항을 확인하고 유효성을 검사합니다.
- 이 예제에서 Copilot 코드 검토는 고유한 솔트를 생성해야 한다는 점을 강조할 수 있습니다.
볼 수 있듯이 취약성을 수정하기 위한 제안과 함께 자동으로 식별하면 보안을 최우선으로 하는 데 도움이 됩니다. Copilot Autofix를 활용하면 프로젝트와 코드베이스에 최적화된 수정 사항을 신속하게 파악하고, 안전한 코딩 원칙을 학습하는 데 집중할 수 있습니다.
Copilot를 활용한 최적화된 리뷰
자동 검토 주석은 경험 수준에 관계없이 검토를 최적화하고 코드를 보다 효율적으로 보호하는 데 도움이 됩니다.
- 사용자 지정 지침은 Copilot 코드 검토의 응답을 프로젝트 및 사용자 요구 사항에 맞춰 구체적으로 조정하는 데 도움이 되었습니다. 또한, 피드백에서 Copilot가 제공하는 설명의 정도를 어떻게 조정할 수 있는지도 확인했습니다.
- Copilot 코드 검토 덕분에 오류 로깅의 중요성을 파악하고 이를 신속하게 개선할 수 있었습니다.
- Copilot Autofix은(는) code scanning 내에서 취약한 암호화 해싱 기법을 차단함으로써 사용자 data를 안전하게 보호하는 데 기여했습니다.
다음 단계
Copilot의 검토 기능을 활용하여 더욱 효율적이고 효과적인 검토를 진행하려면 다음 단계부터 시작하세요.
- 프로젝트 및 리포지토리와 관련된 사용자 지정 지침을 만듭니다. 직접 작성하거나 예제 라이브러리에서 영감을 얻으세요. 사용자 지정 지침을(를) 참조하세요.
- 리포지토리에서 자동 Copilot 코드 검토를 활성화하는 방법은 GitHub Copilot에서 자동 코드 검토 구성을 참고하시기 바랍니다.
- code scanning을(를) 활성화해야 리포지토리에서 Copilot Autofix을(를) 구성할 수 있습니다. CodeQL 분석을 통해 code scanning이(가) 활성화되면, Copilot Autofix은(는) 자동으로 활성화됩니다. 가장 쉬운 설정은 코드 검사에 대한 기본 설정 구성을 참조하세요.
추가 읽기
AI 생성 코드를 검토하는 방법을 자세히 알아보려면 AI 생성 코드 검토을 참조하세요.