跳至主要内容

使用自定义指令解锁 Copilot 代码审查的强大功能

了解如何编写有效的自定义指令,帮助 GitHub Copilot 提供更相关且可操作的代码审查。

简介

可以使用指令文件自定义 GitHub Copilot 代码审查,以便将审查体验调整为符合团队需求和编码规范。但编写有效的自定义指令需要了解 Copilot 如何处理这些指令以及哪些方法最为有效。

在本教程中,您将学习如何编写清晰、有效的自定义指令,以帮助 Copilot 提供更相关的代码审查。您将了解指令结构的最佳实践、常见陷阱以及跨不同文件组织指令的策略。

本教程介绍了在 Copilot 代码审查中使用自定义指令。欲了解更一般的自定义指令使用介绍,请参阅为 GitHub Copilot 配置自定义指令

您将学到的内容

在本教程结束时,您将了解

  • 如何编写简洁、有效的代码审查自定义指令。
  • 仓库范围指令与路径特定指令的区别。
  • 在 Copilot 代码审查中效果良好的常见模式。
  • 当前不支持的指令类型。
  • 如何构建和组织指令以获得最佳效果。

先决条件

  • 获取 Copilot 代码审查的权限。
  • 一个可以创建自定义指令文件的 GitHub 仓库。
  • 对 Markdown 语法有基本了解。

了解 GitHub Copilot 代码审查如何处理指令

在编写自定义指令之前,了解 Copilot 代码审查如何使用这些指令是有帮助的。当审查拉取请求时,Copilot 会读取您的指令文件并以此指导其分析。然而,和任何 AI 系统一样,它也有局限性。

  • 非确定性行为:Copilot 可能并非每次都完美遵循每条指令。
  • 上下文限制:非常长的指令文件可能导致部分指令被忽略。
  • 具体性很重要:清晰、具体的指令比模糊的指令更有效。

在编写指令时请记住这些因素——它们将帮助您设定合理的期望并撰写更有效的指导。

注意

  • Copilot 代码审查仅读取任何自定义指令文件的前 4,000 个字符。超出此限制的任何指令都不会影响 Copilot 代码审查生成的审查。此限制不适用于 Copilot Chat 或 Copilot 云代理。
  • 审查拉取请求时,Copilot 使用拉取请求基础分支中的自定义指令。例如,如果您的拉取请求旨在将 my-feature-branch 合并到 main 中,则 Copilot 将使用 main 中的自定义指令。

编写有效的自定义指令

成功的自定义指令关键在于清晰、简洁且具体。以下是需要遵循的核心原则:

保持指令短小且聚焦

较短的指令文件更有可能被 Copilot 完全处理。请从最小的指令集开始,并根据效果逐步添加。

最佳实践:将单个指令文件限制在约 1,000 行以内。超过此长度,回复质量可能下降。

使用清晰的结构和格式

Copilot 能够从结构良好的指令中受益,包括

  • 明确的标题,用于区分不同主题。
  • 项目符号,便于快速浏览和引用。
  • 简短的祈使句指令,而不是冗长的叙述段落。

例如,与其写

When you're reviewing code, it would be good if you could try to look for
situations where developers might have accidentally left in sensitive
information like passwords or API keys, and also check for security issues.

写入

## Security Critical Issues

- Check for hardcoded secrets, API keys, or credentials
- Look for SQL injection and XSS vulnerabilities
- Verify proper input validation and sanitization

提供具体示例

就像向同事解释概念时一样,示例有助于 Copilot 理解您的意图。请在指令中包含展示正确和错误模式的代码片段。

例如

## Naming Conventions

Use descriptive, intention-revealing names.

```javascript
// Avoid
const d = new Date();
const x = users.filter(u => u.active);

// Prefer
const currentDate = new Date();
const activeUsers = users.filter(user => user.isActive);
```

跨文件组织指令

Copilot 代码审查支持两种类型的指令文件

  1. copilot-instructions.md:适用于所有文件的仓库范围指令。
  2. *.instructions.md:适用于特定文件或目录的路径特定指令。

使用路径特定指令可让 Copilot 保持专注,防止其将语言特定规则错误地应用于不相关文件。

何时使用仓库范围指令

使用 copilot-instructions.md 用于

  • 通用的团队标准和指南
  • 通用的安全需求
  • 跨领域关注点,如错误处理理念
  • 文档预期

copilot-instructions.md 的示例结构:

Markdown
# General Code Review Standards

## Code Quality Essentials

- Functions should be focused and appropriately sized
- Use clear, descriptive naming conventions
- Ensure proper error handling throughout

## Security Standards

- Never hardcode credentials or API keys
- Validate all user inputs
- Use parameterized queries to prevent SQL injection

## Documentation Expectations

- All public functions must include doc comments
- Complex algorithms should have explanatory comments
- README files must be kept up to date

何时使用路径特定指令

使用带有 applyTo 前置属性的 *.instructions.md 文件,用于

  • 语言特定的编码标准
  • 框架特定的模式
  • 技术特定的安全关注点
  • 针对代码库不同部分的不同规则

示例:Python 特定指令

.github/instructions 目录下创建名为 python.instructions.md 的文件

Text
---
applyTo: "**/*.py"
---

# Python Coding Conventions

## Naming Conventions

- Use snake_case for variables and functions
- Use PascalCase for class names
- Use UPPERCASE for constants

## Code Style

- Follow PEP 8 style guidelines
- Limit line length to 88 characters (Black formatter standard)
- Use type hints for function signatures

## Best Practices

- Use list comprehensions for simple transformations
- Prefer f-strings for string formatting
- Use context managers (with statements) for resource management

```python
# Avoid
file = open('data.txt')
content = file.read()
file.close()

# Prefer
with open('data.txt') as file:
    content = file.read()
```

示例:前端特定指令

.github/instructions 目录下创建名为 frontend.instructions.md 的文件

Text
---
applyTo: "src/components/**/*.{tsx,jsx}"
---

# React Component Guidelines

## Component Structure

- Use functional components with hooks
- Keep components small and focused (under 200 lines)
- Extract reusable logic into custom hooks

## State Management

- Use useState for local component state
- Use useContext for shared state across components
- Avoid prop drilling beyond 2-3 levels

## Accessibility

- All interactive elements must be keyboard accessible
- Include appropriate ARIA labels
- Ensure color contrast meets WCAG AA standards

拆分复杂的指令集

对于关注点众多的大型仓库,请将指令拆分为多个聚焦的文件

.github/
  copilot-instructions.md          # General standards

.github/instructions/
  python.instructions.md           # Python-specific
  javascript.instructions.md       # JavaScript-specific
  security.instructions.md         # Security-specific
  api.instructions.md              # API-specific

每个文件应有明确、具体的目的,并在需要时使用合适的 applyTo 前置属性。

基于在 Copilot 代码审查中表现良好的经验,以下是推荐的指令结构模板

Text
---
applyTo: "**/*.{js,ts}"  # If this is a path-specific file
---

# [Title: Technology or Domain Name] Guidelines

## Purpose

Brief statement of what this file covers and when these instructions apply.

## Naming Conventions

- Rule 1
- Rule 2
- Rule 3

## Code Style

- Style rule 1
- Style rule 2

```javascript
// Example showing correct pattern
```

## Error Handling

- How to handle errors
- What patterns to use
- What to avoid

## Security Considerations

- Security rule 1
- Security rule 2

## Testing Guidelines

- Testing expectation 1
- Testing expectation 2

## Performance

- Performance consideration 1
- Performance consideration 2

请根据具体需求调整此结构,但保持明确的分区和项目符号格式。

自定义指令中不应包含的内容

了解 Copilot 代码审查当前不支持的内容,可帮助您避免在无效指令上浪费时间。

不受支持的指令类型

Copilot 代码审查目前不支持尝试以下操作的指令:

更改用户体验或格式:

  • 使用粗体文本标记关键问题
  • 更改审查评论的格式
  • 在评论中添加表情符号

修改拉取请求概览评论:

  • 在 PR 概览中包含安全问题摘要
  • 在概览评论中添加测试检查清单

更改 GitHub Copilot 的核心功能:

  • 阻止 PR 合并,除非所有 Copilot 代码审查评论均已处理
  • 为每个 PR 生成变更日志条目

跟随外部链接:

  • 根据 https://example.com/standards 中的标准审查此代码

    变通方法:直接将相关内容复制到指令文件中

模糊的质量改进:

  • 更加准确
  • 不遗漏任何问题
  • 反馈保持一致

这些类型的指令只会产生噪声,却并未提升 Copilot 的效果,因为它已经被优化为提供准确、一致的审查。

测试并迭代您的指令

创建有效自定义指令的最佳方法是从小处起步,并根据结果迭代。

从最小指令集开始

先制定 10–20 条针对最常见审查需求的具体指令,然后测试它们是否按预期影响 Copilot 代码审查。

使用真实的拉取请求进行测试

在创建指令后

  1. 在仓库中打开一个拉取请求。
  2. 请求 Copilot 进行审查。
  3. 观察它有效遵循了哪些指令。
  4. 记录任何始终被遗漏或误解的指令。

根据结果进行迭代

一次添加一条或少量新指令

  1. 识别 Copilot 可以更好审查的模式。
  2. 为该模式添加具体指令。
  3. 使用新的拉取请求进行测试。
  4. 根据结果完善指令。

这种迭代方式帮助您了解哪些有效,并保持指令文件的专注性。

示例:完整的代码审查自定义指令

以下是一个完整示例,融合了本教程的所有最佳实践

文件:.github/copilot-instructions.md

Markdown
# General Code Review Standards

## Purpose

These instructions guide Copilot code review across all files in this repository.
Language-specific rules are in separate instruction files.

## Security Critical Issues

- Check for hardcoded secrets, API keys, or credentials
- Look for SQL injection and XSS vulnerabilities
- Verify proper input validation and sanitization
- Review authentication and authorization logic

## Performance Red Flags

- Identify N+1 database query problems
- Spot inefficient loops and algorithmic issues
- Check for memory leaks and resource cleanup
- Review caching opportunities for expensive operations

## Code Quality Essentials

- Functions should be focused and appropriately sized (under 50 lines)
- Use clear, descriptive naming conventions
- Ensure proper error handling throughout
- Remove dead code and unused imports

## Review Style

- Be specific and actionable in feedback
- Explain the "why" behind recommendations
- Acknowledge good patterns when you see them
- Ask clarifying questions when code intent is unclear

## Testing Standards

- New features require unit tests
- Tests should cover edge cases and error conditions
- Test names should clearly describe what they test

Always prioritize security vulnerabilities and performance issues that could impact users.

文件:.github/instructions/typescript.instructions.md

Text
---
applyTo: "**/*.{ts,tsx}"
---

# TypeScript Development Standards

## Type Safety

- Avoid using `any` type—use `unknown` or specific types instead
- Use strict null checks (no `null` or `undefined` without explicit handling)
- Define interfaces for all object shapes

```typescript
// Avoid
function processData(data: any) {
    return data.value;
}

// Prefer
interface DataShape {
    value: string;
}

function processData(data: DataShape): string {
    return data.value;
}
```

## Naming Conventions

- Use PascalCase for types, interfaces, and classes
- Use camelCase for variables, functions, and methods
- Use UPPER_CASE for constants

## Modern TypeScript Patterns

- Use optional chaining (`?.`) and nullish coalescing (`??`)
- Prefer `const` over `let`; never use `var`
- Use arrow functions for callbacks and short functions

## React-Specific (for .tsx files)

- Use functional components with TypeScript props interfaces
- Type all props and state explicitly
- Use proper event types (e.g., `React.ChangeEvent<HTMLInputElement>`)

常见问题排查

如果 Copilot 代码审查未按预期遵循您的指令,请尝试以下解决方案

问题:指令被忽略

可能原因:

  • 指令文件过长(超过 1,000 行)。
  • 指令模糊或含糊不清。
  • 指令之间相互冲突。

解决方案:

  • 通过删除不重要的指令来缩短文件。
  • 将模糊的指令重写为更具体且可操作的。
  • 检查指令冲突,并优先考虑最重要的指令。

问题:语言特定规则被错误地应用到文件上

可能原因:

  • applyTo 前置属性缺失或不正确。
  • 规则位于仓库范围文件而非路径特定文件中。

解决方案:

  • 为路径特定指令文件添加 applyTo 前置属性。
  • 将语言特定规则从 copilot-instructions.md 移动到相应的 *.instructions.md 文件中。

问题:审查之间行为不一致

可能原因:

  • 指令数量过多。
  • 指令缺乏具体性。
  • AI 响应的自然变动。

解决方案:

  • 聚焦于最高优先级的指令。
  • 添加具体示例以阐明意图。
  • 接受一定的变动性是 AI 系统的正常现象。

结论

有效的自定义指令帮助 Copilot 代码审查提供更相关、可操作的反馈,符合团队标准。遵循本教程中的原则——保持指令简洁、提供清晰结构、使用具体示例,并跨多个文件组织——您即可显著提升代码审查体验。

请记住,创建有效指令是一个迭代过程。先从一小套聚焦的指令开始,在真实的拉取请求中测试,根据团队的实际效果逐步扩展。

后续步骤

© . This site is unofficial and not affiliated with GitHub, Inc.