Skip to main content

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

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

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

Copilot 코드 검토 is available for Copilot Pro, GitHub Copilot Pro+, Copilot Business and Copilot Enterprise. See Copilot plans.

소개

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

이 문서에서는 자동 검토 Copilot 가 검토 프로세스를 최적화하는 데 어떻게 도움이 되는지 보여 주므로 사소한 변경에 더 적은 시간을 할애하고 미묘한 문제 해결에 더 많은 시간을 할애하고 단순히 적절하지는 않지만 사용자 요구를 능숙하게 충족하는 구현에 대한 심층적인 이해를 제공합니다.

1. Copilot로부터 검토 품질 향상

          Copilot 코드 검토 는 리포지토리의 모든 끌어오기 요청에 대해 자동화된 검토를 제공하고 코드에서 원하지 않는 변경 내용을 catch하여 검토를 보다 효율적으로 수행할 수 있습니다. 사용자 지정 지침과 쌍을 이루는 경우 팀 작동 방식, Copilot 코드 검토 사용하는 도구 또는 프로젝트의 세부 사항에 맞게 조정된 응답을 제공할 수 있으므로 더 효과적입니다. 

사용자 지정 지침을 작성하는 모범 사례는 다음과 같습니다.

  • 고유 제목
  • 글머리 기호
  • 짧고 직접적인 지침

예를 살펴보겠습니다. 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 코드 검토
          Copilot Autofix 이 보안 모범 사례를 제안할 수 있는 반면, code scanning는 한 단계 더 발전시킵니다. 분석 기능을 활용하여 리포지토리에서 code scanningCodeQLGitHub 코드를 분석하고 보안 취약성 및 코딩 오류를 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 Autofix 를 사용하면 코드 베이스 및 프로젝트에 가장 적합한 수정 사항 및 보안 코딩을 이해하는 데 집중할 수 있습니다.

          Copilot을 사용하여 검토 최적화

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

  • 사용자 지정 지침은 프로젝트 및 사용자 요구에 특정하도록 응답을 구체화하는 데 도움이 되었으며 피드백에서 Copilot 코드 검토 제공하는 설명 Copilot 의 양을 조정하는 방법도 확인했습니다.
  •         Copilot 코드 검토  오류 로깅을 신속하게 개선하고 중요한 이유를 이해하는 데 도움이 됩니다. 
    
  •         Copilot Autofix
            code scanning 덕분에 불충분한 암호 해싱 방법의 사용을 막고 사용자 데이터를 보호할 수 있었습니다.   
    

다음 단계

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

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

추가 읽기

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