Copilot 最常用的功能是"写注释/代码 → 等待补全 → 按 Tab"。这个流程很简单,但只用了 Copilot 内联补全能力的 30%。
今天讲进阶技巧,把 Copilot 变成真正的编程搭档。
Copilot 的补全不是随机生成,而是基于上下文预测"你接下来最可能写什么"。
上下文来源包括:
理解这一点,就能明白:优化 Copilot 输出 = 优化上下文质量。
在项目根目录创建 .github/copilot-instructions.md:
# Project Overview
This is a REST API for a task management app.
- Language: Python, FastAPI
- Database: PostgreSQL with SQLAlchemy ORM
- Auth: JWT tokens
# Coding Standards
- Use type hints for all function parameters and return values
- All API endpoints must include docstrings
- Error handling: raise HTTPException with status code, never bare exceptions
Copilot 会自动读取这个文件,参考项目规范补全代码。
在补全某个文件前,先打开与它相关的文件。
例如要写 user_service.py,先打开 models/user.py 和 schemas/user.py。Copilot 能看到这些文件的内容,补全时会自动参考其中的类型定义和数据结构。
变量名、函数名、参数名越清晰,Copilot 越能准确补全。
# 差的命名
def process(d, k):
r = fetch(d)
return r.get(k)
# 好的命名
def get_user_by_id(user_id: int) -> dict:
user_record = fetch_user_from_database(user_id)
return user_record.get('profile')
按 Tab 接受补全,但 Copilot 提供了多种补全方式:
Copilot 给出单行或多行建议,按 Tab 接受。
Copilot 可以同时生成多个候选方案:
遇到不满意的补全,先试试切换候选,再考虑手动写。
如果 Copilot 正在生成一个很长的补全,但你想自己写,按 Esc 暂停,然后继续手动输入。Copilot 不会消失,会在你停下的地方重新开始预测。
有时 Copilot 的补全前半部分是你想要的,后半部分不对。
Copilot 显示的灰色文本(ghost text)不只是最终答案——你可以引导它。
接受补全后,按 Ctrl+Enter,Copilot 会打开一个面板,显示更多候选方案。适合在多个可行方案中选最优。
对补全不满意,按 Alt+/ 让 Copilot 重新生成一个方案。多次重试能找到更合适的补全。
删除光标前的代码,重新写注释引导 Copilot:
def calculate_discount(original_price, customer_tier):
# Apply tier-based discount:
# - 'gold': 20% off
# - 'silver': 10% off
# - 'bronze': 5% off
# - 'regular': no discount
# Return final price rounded to 2 decimal places
详细的业务规则注释,让 Copilot 生成准确的分层折扣逻辑。
# 在测试文件中,让 Copilot 补全测试用例
# 先写一个示例测试,让它理解测试风格和结构
def test_user_signup_success():
'Test successful user signup with valid data.'
# Copilot 会自动补全后续测试用例
# 在 SQL 文件中写注释,Copilot 能生成复杂查询
-- Get the top 10 users by total order amount,
-- including their name, email, and order count
SELECT
# Validate email format
# Pattern: local@domain.tld, allow subdomains
email_pattern = "" # Copilot will suggest regex
# docker-compose.yml
# Define a web service with:
# - Python FastAPI app
# - Port 8000
# - PostgreSQL dependency
# - Environment variables from .env file
下期预告:GitHub Copilot 实战指南⑤——调试与错误处理,让 Copilot 帮你快速定位和修复 Bug。
评论区