介绍
GitHub Copilot 代码评审可以使用说明文件自定义,以便根据团队的需求和编码标准定制评审体验。 但是,编写有效的自定义指令需要了解 Copilot 如何处理这些指令以及哪些方法效果最佳。
在本教程中,您将学习如何编写清晰且有效的自定义说明,以帮助 Copilot 提供更相关的代码审查。 你将发现构建说明的最佳做法、避免的常见陷阱,以及跨不同文件组织说明的策略。
本教程介绍如何对 Copilot 代码评审使用自定义说明。 有关使用自定义说明的更一般介绍,请参阅 为 GitHub Copilot 配置自定义指令。
学习内容
在本教程结束时,你将了解:
- 如何编写简洁有效的代码评审自定义说明。
- 存储库范围说明与路径具体说明之间的差异。
- 适用于 Copilot 代码评审 的通用且有效的模式。
- 当前不支持哪些类型的指令。
- 如何构建和组织说明以获得最佳结果。
先决条件
- 访问 Copilot 代码评审。
- GitHub 存储库,您可以在其中创建自定义指令文件。
- 基本熟悉 Markdown 语法。
了解 GitHub Copilot 如何处理代码评审的指令
在编写自定义指令之前,了解 如何使用这些指令是有帮助的。 查看拉取请求时,Copilot 读取说明文件,并使用它们来指导其分析。 但是,与任何 AI 系统一样,它具有限制:
-
**非确定性行为**:Copilot 可能并不总是完美遵循每条指令。 -
**上下文限制**:很长的指令文件可能会导致某些指令被忽略。 -
**具体性很重要**:明确、具体的指令比模糊指令效果更好。
在编写说明时,请记住这些因素 - 它们将帮助你设置现实的期望,并编写更有效的指导。
编写有效的自定义说明
成功的自定义指令的关键是清晰、简洁和具体。 下面是要遵循的核心原则:
使说明保持简短并专注
较短的指令文件更有可能被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 代码评审 支持两种类型的说明文件:
-
** `copilot-instructions.md` **:适用于所有文件的存储库范围说明。 -
** `*.instructions.md` **:适用于特定文件或目录的路径特定说明。
使用特定于路径的说明使 Copilot 保持专注,并阻止它将特定于语言的规则应用于错误的文件。
何时使用全局性指示
用于 copilot-instructions.md :
-
常规团队标准和准则
-
通用安全要求
-
跨领域问题,如错误处理理念
-
文档要求
**示例结构:`copilot-instructions.md`**
# 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
何时使用路径特定指令
将 *.instructions.md 文件与 frontmatter 属性一起使用 applyTo ,用于:
-
特定于语言的编码标准
-
框架特定的模式
-
技术特定的安全问题
-
代码库不同部分的不同规则
**示例:特定于 Python 的说明**
在.github/instructions 目录中创建一个名为python.instructions.md的文件:
---
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的文件:
---
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 frontmatter。
建议的说明文件结构
基于 Copilot 代码评审 的成功经验,下面是建议用于构建说明的模板:
---
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 代码评审 当前不支持尝试执行以下操作的指令:
**更改用户体验或格式**:
-
Use bold text for critical issues -
Change the format of review comments -
Add emoji to comments**修改拉取请求概述注释**: -
Include a summary of security issues in the PR overview -
Add a testing checklist to the overview comment**更改 GitHub Copilot的核心功能**: -
Block a PR from merging unless all Copilot 代码评审 comments are addressed -
Generate a changelog entry for every PR**关注外部链接**: -
Review this code according to the standards at https://example.com/standards解决方法:将相关内容直接复制到说明文件中
**不明确质量改进**: -
Be more accurate -
Don't miss any issues -
Be consistent in your feedback
这类指令会增加噪声而不改进Copilot的有效性,因为该产品已优化为提供准确、一致的反馈。
对您的指导进行测试和迭代
创建有效的自定义指令的最佳方法是从小规模开始,并根据结果进行迭代。
从最小指令集开始
从 10-20 条特定说明开始,解决您最常见的评审需求,然后测试这些指令是否按照您的预期影响 Copilot 代码评审。
使用实际拉取请求进行测试
创建说明后,请按照以下步骤操作:
- 在你的存储库中创建一个 Pull Request。
- 向 Copilot请求评审。
- 观察它遵循哪些说明。
- 请注意持续被遗漏或误解的任何指令。
基于结果迭代
逐个或以小组为单位添加新说明:
- 确定 Copilot 可以更好地分析的模式。
- 为该模式添加特定说明。
- 使用新的拉取请求进行测试。
- 根据结果优化指令。
此迭代方法可帮助你了解哪些工作原理,并使指令文件保持专注。
示例:完成代码评审的自定义说明
下面是包含本教程中所有最佳做法的完整示例:
**文件: `.github/copilot-instructions.md`**
# General Code Review Standards
## Purpose
These instructions guide Copilot 代码评审 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`**
---
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 行)。
-
说明含糊不清或模棱两可。
-
指令相互冲突。
**解决方法**: -
通过删除不太重要的说明来缩短文件。
-
重写模糊的说明,以便更具体和更可行。
-
查看冲突说明并确定最重要的指令的优先级。
问题:应用于错误文件的语言特定规则
**可能的原因**:
-
缺少或不正确的
applyTofrontmatter。 -
适用于整个存储库的文件中的规则,而不是特定于路径的文件。
**解决方法**: -
将
applyTofrontmatter 添加到特定路径的指令文件。 -
将语言特定的规则从
copilot-instructions.md文件移到合适的*.instructions.md文件中。
问题:跨评审的行为不一致
**可能的原因**:
-
指令太多。
-
说明缺乏具体性。
-
AI 响应中的自然可变性。
**解决方法**: -
专注于最高优先级指令。
-
添加具体示例以阐明意向。
-
接受 AI 系统的一些可变性是正常的。
结论
有效的自定义说明有助于 Copilot 代码评审 提供更相关的、可执行的反馈,这些反馈是量身定制以符合团队标准的。 按照本教程中的原则(保持说明简洁、提供清晰结构、使用具体示例以及跨多个文件进行组织)可以显著提高代码评审体验。
请记住,创建有效的指令是一个迭代过程。 从一小组有针对性的指令开始,用实际的拉取请求对其进行测试,并根据对团队有效的方法逐步扩展。
后续步骤
- 查看 Awesome GitHub Copilot 库中的一些 示例自定义说明,寻找灵感。
- 阅读 关于自定义 GitHub Copilot 响应 ,了解各种自定义选项。
- 有关设置说明文件的技术详细信息,请浏览 为 GitHub Copilot 配置自定义指令 。