Skip to main content

Copilot를 사용하여 최적화된 검토 프로세스 빌드

Copilot를 사용하여 검토를 자동화하여 검토 프로세스를 최적화하고 개선합니다.

누가 이 기능을 사용할 수 있나요?

Copilot 코드 검토 is available for Copilot Pro, GitHub Copilot Pro+, 코파일럿 사업 and Copilot Enterprise. See Copilot plans.

소개

코드 검토는 이름 지정 및 스타일 규칙과 같은 사소한 구현 세부 정보에 더 적은 시간을 소비하는 대신 사용자 요구를 충족하는 더 높은 수준의 디자인, 문제 해결 및 기능에 집중하는 경우 더 효율적입니다.

이 문서에서는 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은 코드를 검토하고 다음과 같은 주석 및 코드 제안을 할 수 있습니다.

참고 항목

다음 응답이 예제입니다. 부조종사 채팅 응답은 비결정적이므로 여기에 표시된 응답과 다른 응답을 얻을 수 있습니다.

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에 대한 코파일럿 자동 수정은(는) 한 단계 더 발전합니다. code scanning의 기능을 CodeQL 분석과 함께 활용하여 GitHub 리포지토리의 코드를 분석하고 보안 취약성 및 코딩 오류를 찾을 수 있습니다. 이후, 코파일럿 자동 수정는 경고에 대한 수정 사항을 제안하여, 보다 효율적으로 취약성을 방지하고 줄일 수 있도록 도와줍니다.

예를 들어 코파일럿 자동 수정는 다음과 같은 주석을 코드에 작성할 수 있습니다.

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.

코파일럿 자동 수정은(는) 귀하가 검토할 수 있도록 취약성에 대한 잠재적인 수정을 위한 코드를 제안합니다. 이 경우 아래와 같이 코드를 제안하여 패키지를 가져오고 암호 해시와 관련된 코드를 업데이트할 수 있습니다.

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을 사용하여 최적화된 리뷰

자동 검토 주석은 경험 수준에 관계없이 검토를 최적화하고 코드를 보다 효율적으로 보호하는 데 도움이 됩니다.

  • 사용자 지정 지침은 Copilot 코드 검토의 응답을 프로젝트 및 사용자 요구 사항에 맞춰 구체적으로 조정하는 데 도움이 되었습니다. 또한, 피드백에서 Copilot가 제공하는 설명의 정도를 어떻게 조정할 수 있는지도 확인했습니다.
  • Copilot 코드 검토은(는) 오류 로깅을 신속하게 개선하고 왜 중요한지를 이해하는 데 도움을 주었습니다.
  • 코파일럿 자동 수정은(는) code scanning에서 충분하지 않은 암호 해시 방식을 방지하고 사용자 데이터를 보호하는 데 도움을 주었습니다.

다음 단계

Copilot의 검토 기능을 사용하여 검토를 보다 효율적이고 효과적으로 만들려면 다음 단계를 수행하여 시작하세요.

  1. 프로젝트 및 리포지토리와 관련된 사용자 지정 지침을 만듭니다. 직접 작성하거나 예제 라이브러리에서 영감을 얻으세요. 사용자 지정 지침을(를) 참조하세요.
  2. 리포지토리에 대해 자동 Copilot 코드 검토를 사용하도록 설정하려면 GitHub Copilot에서 자동 코드 검토 구성을 참조하세요.
  3. 리포지토리에서 코파일럿 자동 수정을(를) 구성하려면 code scanning을(를) 활성화해야 합니다. code scanning이(가) CodeQL 분석을 사용하여 활성화되면, 코파일럿 자동 수정이(가) 기본적으로 활성화됩니다. 가장 쉬운 설정은 코드 검사에 대한 기본 설정 구성을 참조하세요.

추가 읽기

AI 생성 코드를 검토하는 방법을 자세히 알아보려면 AI 생성 코드 검토을 참조하세요.