diff --git a/00-quick-start/README.zh-CN.md b/00-quick-start/README.zh-CN.md new file mode 100644 index 0000000..4fdc5bb --- /dev/null +++ b/00-quick-start/README.zh-CN.md @@ -0,0 +1,260 @@ +![第 00 章:快速开始](images/chapter-header.png) + +欢迎!在本章中,你将安装 GitHub Copilot CLI(命令行界面),用你的 GitHub 账号登录,并确认一切可以正常运行。这是一个快速配置章节。准备完成后,真正的演示会从第 01 章开始。 + +## 🎯 学习目标 + +完成本章后,你将能够: + +- 安装 GitHub Copilot CLI +- 使用你的 GitHub 账号登录 +- 通过一个简单测试确认它可以正常工作 + +> ⏱️ **预计用时**:约 10 分钟(阅读 5 分钟 + 动手 5 分钟) + +--- + +## ✅ 前置条件 + +- **具备 Copilot 访问权限的 GitHub 账号**。[查看订阅选项](https://github.com/features/copilot/plans)。学生和教师可通过 [GitHub Education](https://education.github.com/pack) 免费使用 Copilot Pro。 +- **终端基础**:熟悉 `cd` 和 `ls` 这类命令 + +### “Copilot 访问权限”是什么意思 + +GitHub Copilot CLI 需要有效的 Copilot 订阅。你可以在 [github.com/settings/copilot](https://github.com/settings/copilot) 查看自己的状态。你应该会看到以下其中一种: + +- **Copilot Individual** - 个人订阅 +- **Copilot Business** - 通过组织提供 +- **Copilot Enterprise** - 通过企业提供 +- **GitHub Education** - 面向已验证学生/教师的免费资格 + +如果你看到 “You don't have access to GitHub Copilot”,那就需要使用免费选项、订阅某个方案,或者加入一个提供访问权限的组织。 + +--- + +## Installation + +> ⏱️ **Time estimate**: Installation takes 2-5 minutes. Authentication adds another 1-2 minutes. + +### 推荐:GitHub Codespaces(零配置) + +如果你不想安装任何前置依赖,可以使用 GitHub Codespaces。它已经准备好了 GitHub Copilot CLI(你仍然需要登录),并预装了 Python 3.13、pytest 和 GitHub CLI。 + +1. [Fork this repository](https://github.com/github/copilot-cli-for-beginners/fork) to your GitHub account +2. Select **Code** > **Codespaces** > **Create codespace on main** +3. Wait a few minutes for the container to build +4. You're ready to go! The terminal will open automatically in the Codespace environment. + +> 💡 **Verify in Codespace**: Run `cd samples/book-app-project && python book_app.py help` to confirm Python and the sample app are working. + +### 备选:本地安装 + +> 💡 **不确定该选哪个?** 如果你已经安装了 Node.js,就用 `npm`。否则选择最适合你系统的方式。 + +> 💡 **演示需要 Python**:课程使用了一个 Python 示例应用。如果你是在本地操作,请在开始演示前先安装 [Python 3.10+](https://www.python.org/downloads/)。 + +> **注意:** 虽然课程中的主要示例使用 Python(`samples/book-app-project`),但如果你更习惯 JavaScript(`samples/book-app-project-js`)或 C#(`samples/book-app-project-cs`),也提供了相应版本。每个示例都带有 README,说明如何在对应语言中运行应用。 + +选择适合你系统的方法: + +### All Platforms (npm) + +```bash +# If you have Node.js installed, this is a quick way to get the CLI +npm install -g @github/copilot +``` + +### macOS/Linux (Homebrew) + +```bash +brew install copilot-cli +``` + +### Windows (WinGet) + +```bash +winget install GitHub.Copilot +``` + +### macOS/Linux (Install Script) + +```bash +curl -fsSL https://gh.io/copilot-install | bash +``` + +--- + +## Authentication + +在 `copilot-cli-for-beginners` 仓库根目录打开一个终端窗口,启动 CLI,并允许它访问当前文件夹。 + +```bash +copilot +``` + +系统会提示你信任包含该仓库的文件夹(如果之前还没有信任过)。你可以选择只信任这一次,或者让之后的所有会话都默认信任。 + +在 Copilot CLI 中信任文件夹内的文件 + +信任文件夹后,就可以使用 GitHub 账号登录了。 + +``` +> /login +``` + +**接下来会发生什么:** + +1. Copilot CLI 会显示一个一次性代码(例如 `ABCD-1234`) +2. 浏览器会打开 GitHub 的设备授权页面。如果你还没有登录 GitHub,需要先登录。 +3. 按提示输入该代码 +4. 选择 “Authorize”,为 GitHub Copilot CLI 授权 +5. 回到终端,此时你已经登录完成 + +设备授权流程,展示从终端登录到确认登录的 5 个步骤 + +*设备授权流程:终端生成代码,你在浏览器中完成验证,Copilot CLI 随后通过认证。* + +**提示**:登录状态会在多个会话之间持续保留。除非令牌过期,或者你主动登出,否则通常只需要操作一次。 + +--- + +## Verify It Works + +### Step 1: Test Copilot CLI + +现在你已经登录了,接下来确认 Copilot CLI 是否真的可用。如果 CLI 还没启动,就在终端中启动它: + +```bash +> Say hello and tell me what you can help with +``` + +收到响应后,你可以退出 CLI: + +```bash +> /exit +``` + +--- + +
+🎬 See it in action! + +![Hello Demo](images/hello-demo.gif) + +*Demo output varies. Your model, tools, and responses will differ from what's shown here.* + +
+ +--- + +**预期输出**:一段友好的响应,列出 Copilot CLI 能提供哪些帮助。 + +### Step 2: Run the Sample Book App + +课程提供了一个示例应用,你会在整门课程中使用 CLI 去探索和改进它。*(对应代码位于 /samples/book-app-project)* 在开始之前,先确认这个 *Python 图书收藏终端应用* 能正常运行。根据你的系统使用 `python` 或 `python3`。 + +> **注意:** 虽然课程中的主要示例使用 Python(`samples/book-app-project`),但如果你更习惯 JavaScript(`samples/book-app-project-js`)或 C#(`samples/book-app-project-cs`),也提供了相应版本。每个示例都带有 README,说明如何在对应语言中运行应用。 + +```bash +cd samples/book-app-project +python book_app.py list +``` + +**预期输出**:列出 5 本书,其中包括 “The Hobbit”、“1984” 和 “Dune”。 + +### Step 3: Try Copilot CLI with the Book App + +如果你执行了步骤 2,请先返回仓库根目录: + +```bash +cd ../.. # Back to the repository root if needed +copilot +> What does @samples/book-app-project/book_app.py do? +``` + +**预期输出**:对这个图书应用主要功能和命令的简要总结。 + +如果看到错误,请查看下面的 [troubleshooting section](#troubleshooting)。 + +完成后,你可以退出 Copilot CLI: + +```bash +> /exit +``` + +--- + +## ✅ 你已经准备好了! + +安装部分到这里就完成了。真正有意思的内容会在第 01 章开始,在那里你会: + +- 看到 AI 立即审查图书应用并找出代码质量问题 +- 学会使用 Copilot CLI 的三种不同方式 +- 从自然语言直接生成可运行的代码 + +**[继续阅读第 01 章:First Steps →](../01-setup-and-first-steps/README.zh-CN.md)** + +--- + +## Troubleshooting + +### "copilot: command not found" + +说明 CLI 还没有安装成功。尝试其他安装方式: + +```bash +# If brew failed, try npm: +npm install -g @github/copilot + +# Or the install script: +curl -fsSL https://gh.io/copilot-install | bash +``` + +### "You don't have access to GitHub Copilot" + +1. 在 [github.com/settings/copilot](https://github.com/settings/copilot) 确认你确实拥有 Copilot 订阅 +2. 如果你使用的是工作账号,检查你的组织是否允许 CLI 访问 + +### "Authentication failed" + +重新进行认证: + +```bash +copilot +> /login +``` + +### 浏览器没有自动打开 + +手动访问 [github.com/login/device](https://github.com/login/device),然后输入终端中显示的代码。 + +### Token expired + +只需要再次运行 `/login`: + +```bash +copilot +> /login +``` + +### 还是卡住了? + +- 查看 [GitHub Copilot CLI documentation](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) +- 搜索 [GitHub Issues](https://github.com/github/copilot-cli/issues) + +--- + +## 🔑 关键要点 + +1. **GitHub Codespaces 是一种很快的起步方式**:Python、pytest 和 GitHub Copilot CLI 都已预装好,可以直接进入演示环节 +2. **安装方式不止一种**:选择适合你系统的方式(Homebrew、WinGet、npm 或安装脚本) +3. **认证通常只需一次**:登录状态会一直保留到令牌过期 +4. **图书应用可以正常运行**:整门课程都会围绕 `samples/book-app-project` 展开 + +> 📚 **官方文档**:[Install Copilot CLI](https://docs.github.com/copilot/how-tos/copilot-cli/cli-getting-started) 了解安装选项和要求。 + +> 📋 **快速参考**:参见 [GitHub Copilot CLI command reference](https://docs.github.com/en/copilot/reference/cli-command-reference),查看完整命令和快捷方式列表。 + +--- + +**[继续阅读第 01 章:First Steps →](../01-setup-and-first-steps/README.zh-CN.md)** diff --git a/01-setup-and-first-steps/README.zh-CN.md b/01-setup-and-first-steps/README.zh-CN.md new file mode 100644 index 0000000..1b4c6a3 --- /dev/null +++ b/01-setup-and-first-steps/README.zh-CN.md @@ -0,0 +1,639 @@ +![第 01 章:初上手](images/chapter-header.png) + +> **看 AI 即时发现 Bug、解释令人困惑的代码并生成可运行的脚本。然后学会三种不同的 GitHub Copilot CLI 使用方式。** + +魔法从这章开始!你将亲身体验为何开发者将 GitHub Copilot CLI 描述为"随时待命的高级工程师"。你将看到 AI 在几秒内发现安全漏洞、用简洁的语言解释复杂代码,并即时生成可运行的脚本。然后你将掌握三种交互模式(交互式、计划式和编程式),了解何时使用哪种模式。 + +> ⚠️ **前置条件**:请确认已完成 **[第 00 章:快速入门](../00-quick-start/README.zh-CN.md)**。运行以下演示前需要安装并认证 GitHub Copilot CLI。 + +## 🎯 学习目标 + +完成本章后,你将能够: + +- 通过动手演示体验 GitHub Copilot CLI 带来的生产力提升 +- 针对不同任务选择正确的模式(交互式、计划式或编程式) +- 使用斜杠命令控制会话 + +> ⏱️ **预计用时**:约 45 分钟(阅读 15 分钟 + 动手 30 分钟) + +--- + +# 你的第一次 Copilot CLI 体验 + +开发者坐在桌前,显示器上显示代码,发光粒子代表 AI 辅助 + +直接上手,看看 Copilot CLI 能做什么。 + +--- + +## 上手体验:第一批提示词 + +在深入精彩演示之前,先从一些简单的提示词开始。**不需要任何代码仓库**!只需打开终端并启动 Copilot CLI: + +```bash +copilot +``` + +尝试这些适合初学者的提示词: + +``` +> Explain what a dataclass is in Python in simple terms + +> Write a function that sorts a list of dictionaries by a specific key + +> What's the difference between a list and a tuple in Python? + +> Give me 5 best practices for writing clean Python code +``` + +不用 Python?没问题!只需提问你所用语言相关的问题。 + +注意这种方式有多自然。就像和同事交流一样,直接提问就行。探索完毕后,输入 `/exit` 退出会话。 + +**核心洞察**:GitHub Copilot CLI 是对话式的。入门不需要特殊语法,用自然语言提问即可。 + +## 实际演示 + +现在来看看为何开发者将其称为"随时待命的高级工程师"。 + +> 📖 **阅读示例说明**:以 `>` 开头的行是你在交互式 Copilot CLI 会话中输入的提示词。没有 `>` 前缀的行是你在终端中运行的 Shell 命令。 + +> 💡 **关于示例输出**:课程中的示例输出仅供参考。由于 Copilot CLI 每次响应都会有所不同,你的结果在措辞、格式和细节上都会有差异。关注**返回信息的类型**,而不是具体文字。 + +### 演示 1:即时代码审查 + +课程包含带有预设代码质量问题的示例文件。来审查一下: + +```bash +# 如果本地工作且尚未克隆,先克隆课程仓库 +git clone https://github.com/github/copilot-cli-for-beginners +cd copilot-cli-for-beginners + +# 启动 Copilot +copilot +``` + +进入交互式会话后: + +``` +> Review @samples/book-app-project/book_app.py for code quality issues and suggest improvements +``` + +> 💡 **`@` 是什么?** `@` 符号告诉 Copilot CLI 读取某个文件。你将在第 02 章全面了解它。现在只需完整复制命令即可。 + +--- + +
+🎬 看实际演示! + +![Code Review Demo](images/code-review-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +**核心要点**:几秒钟内完成专业代码审查。手动审查要花的时间……嗯,肯定比这长! + +--- + +### 演示 2:解释令人困惑的代码 + +曾经盯着代码发愣,不知道它在做什么?在你的 Copilot CLI 会话中试试: + +``` +> Explain what @samples/book-app-project/books.py does in simple terms +``` + +--- + +
+🎬 看实际演示! + +![Explain Code Demo](images/explain-code-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +**发生了什么**:(你的输出可能不同)Copilot CLI 读取文件,理解代码,用简洁的语言进行解释。 + +``` +This is a book collection management module using Python dataclasses. + +Think of it like a digital bookshelf: +- Book is a dataclass - a simple way to store book information (title, author, year, read status) +- BookCollection manages the entire collection and handles saving/loading + +Key components: + +1. @dataclass decorator (line 8) + - Automatically creates __init__, __repr__, etc. + - Clean way to define data structures in Python + +2. BookCollection class (line 16) + - Maintains a list of Book objects + - Handles persistence with JSON file I/O + - load_books() reads from data.json + - save_books() writes to data.json using asdict() + +3. Book operations: + - add_book() - creates and saves new books + - find_book_by_title() - searches collection + - mark_as_read() - updates read status + - find_by_author() - filters by author name + +Common pattern: Read from JSON → Work with Python objects → Write back to JSON +``` + +**核心要点**:复杂代码得到如耐心导师般的讲解。 + +--- + +### 演示 3:生成可运行代码 + +需要一个原本要花 15 分钟 Google 的函数?继续在你的会话中: + +``` +> Write a Python function that takes a list of books and returns statistics: + total count, number read, number unread, oldest and newest book +``` + +--- + +
+🎬 看实际演示! + +![Generate Code Demo](images/generate-code-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +**发生了什么**:几秒钟内生成完整、可运行的函数,可以直接复制粘贴运行。 + +探索完毕后,退出会话: + +``` +> /exit +``` + +**核心要点**:即时满足,而且整个过程始终在一个连续的会话中进行。 + +--- + +# 模式与命令 + +充满未来感的控制面板,带有发光屏幕、表盘和均衡器,代表 Copilot CLI 的模式和命令 + +你刚刚看到了 Copilot CLI 的能力。现在来了解*如何*有效使用这些功能。关键在于知道对不同情况使用三种交互模式中的哪一种。 + +> 💡 **注意**:Copilot CLI 还有一种 **Autopilot** 模式,它会在无需等待你输入的情况下完成任务。它功能强大,但需要授予完整权限并自主使用高级请求。本课程重点介绍以下三种模式。等你熟悉这三种模式后,我们会指引你了解 Autopilot。 + +--- + +## 🧩 现实类比:外出就餐 + +把使用 GitHub Copilot CLI 想象成外出就餐。从计划出行到点菜,不同情况有不同的方式: + +| 模式 | 就餐类比 | 使用时机 | +|------|---------|---------| +| **计划式** | 去餐厅的 GPS 路线 | 复杂任务——规划路线、确认节点、达成共识,然后出发 | +| **交互式** | 与服务员交谈 | 探索与迭代——提问、自定义、获取实时反馈 | +| **编程式** | 得来速点餐 | 快速、具体的任务——在你的环境中,快速得到结果 | + +就像外出就餐一样,你会自然而然地学会何时使用哪种方式。 + +使用 GitHub Copilot CLI 的三种方式——计划模式(GPS 路线)、交互模式(与服务员交谈)、编程模式(得来速) + +*根据任务选择模式:计划式用于事先规划,交互式用于来回协作,编程式用于快速一次性结果* + +### 从哪种模式开始? + +**从交互式模式开始。** +- 可以实验并提出后续问题 +- 上下文在对话中自然积累 +- 错误可以用 `/clear` 轻松纠正 + +熟悉后,尝试: +- **编程模式**(`copilot -p "<提示词>"`)用于快速一次性问题 +- **计划模式**(`/plan`)在需要在编码前详细规划时使用 + +--- + +## 三种模式 + +### 模式 1:交互式模式(从这里开始) + +交互式模式——像与能回答问题并调整订单的服务员交谈 + +**适用于**:探索、迭代、多轮对话。就像与服务员交谈,可以提问、获得反馈并随时调整。 + +启动交互式会话: + +```bash +copilot +``` + +如你至今已经体验到的,你会看到一个可以自然输入的提示符。要获取可用命令帮助,只需输入: + +``` +> /help +``` + +**核心洞察**:交互式模式保持上下文。每条消息都建立在之前内容之上,就像真实的对话。 + +#### 交互式模式示例 + +```bash +copilot + +> Review @samples/book-app-project/utils.py and suggest improvements + +> Add type hints to all functions + +> Make the error handling more robust + +> /exit +``` + +注意每个提示词如何建立在前一个答案之上。你在进行对话,而不是每次重新开始。 + +--- + +### 模式 2:计划模式 + +计划模式——像出行前用 GPS 规划路线 + +**适用于**:在执行前想要审查方案的复杂任务。类似于出行前用 GPS 规划路线。 + +计划模式帮助你在编写任何代码之前创建逐步计划。使用 `/plan` 命令或按 **Shift+Tab** 切换到计划模式: + +> 💡 **提示**:**Shift+Tab** 循环切换模式:交互式 → 计划式 → Autopilot。在交互式会话中随时按下即可切换模式,无需输入命令。 + +```bash +copilot + +> /plan Add a "mark as read" command to the book app +``` + +**计划模式输出**:(你的输出可能不同) + +``` +📋 Implementation Plan + +Step 1: Update the command handler in book_app.py + - Add new elif branch for "mark" command + - Create handle_mark_as_read() function + +Step 2: Implement the handler function + - Prompt user for book title + - Call collection.mark_as_read(title) + - Display success/failure message + +Step 3: Update help text + - Add "mark" to available commands list + - Document the command usage + +Step 4: Test the flow + - Add a book + - Mark it as read + - Verify status changes in list output + +Proceed with implementation? [Y/n] +``` + +**核心洞察**:计划模式让你在编写任何代码之前审查和修改方案。计划完成后,你甚至可以让 Copilot CLI 将其保存到文件中以供日后参考。例如,"Save this plan to `mark_as_read_plan.md`"会创建一个包含计划详情的 Markdown 文件。 + +> 💡 **想要更复杂的?** 试试:`/plan Add search and filter capabilities to the book app`。计划模式可以从简单功能扩展到完整应用。 + +> 📚 **Autopilot 模式**:你可能注意到 Shift+Tab 还会循环到第三种叫做 **Autopilot** 的模式。在 Autopilot 模式下,Copilot 会完成整个计划而不需要你在每个步骤后提供输入——就像委托给同事并说"完成后告诉我"。典型工作流是:计划 → 确认 → Autopilot,这意味着你需要先擅长写计划。熟悉交互式和计划模式后,查看[官方文档](https://docs.github.com/copilot/concepts/agents/copilot-cli/autopilot)了解更多。 + +--- + +### 模式 3:编程模式 + +编程模式——像使用得来速快速点餐 + +**适用于**:自动化、脚本、CI/CD、单次命令。就像使用得来速快速点餐,无需与服务员交谈。 + +使用 `-p` 标志执行不需要交互的一次性命令: + +```bash +# 生成代码 +copilot -p "Write a function that checks if a number is even or odd" + +# 快速获取帮助 +copilot -p "How do I read a JSON file in Python?" +``` + +**核心洞察**:编程模式给你快速答案后就退出。没有对话,只有输入 → 输出。 + +
+📚 进阶:在脚本中使用编程模式(点击展开) + +熟悉后,可以在 Shell 脚本中使用 `-p`: + +```bash +#!/bin/bash + +# 自动生成提交信息 +COMMIT_MSG=$(copilot -p "Generate a commit message for: $(git diff --staged)") +git commit -m "$COMMIT_MSG" + +# 审查文件 +copilot --allow-all -p "Review @myfile.py for issues" +``` +> ⚠️ **关于 `--allow-all`**:此标志跳过所有权限提示,允许 Copilot CLI 无需询问即可读取文件、运行命令和访问 URL。这在编程模式(`-p`)中是必需的,因为没有交互式会话来批准操作。仅在你自己编写的提示词和信任的目录中使用 `--allow-all`。切勿在不受信任的输入或敏感目录中使用。 + +
+ +--- + +## 基本斜杠命令 + +这些命令在交互模式下有效。**先掌握这四个** — 它们覆盖 90% 的日常使用场景: + +| 命令 | 功能 | 使用时机 | +|------|------|---------| +| `/help` | 显示所有可用命令 | 忘记某个命令时 | +| `/clear` | 清除对话并重新开始 | 切换话题时 | +| `/plan` | 在编码前规划工作 | 处理较复杂的功能时 | +| `/research` | 使用 GitHub 和网络资源进行深度研究 | 需要在编码前调查某个主题时 | +| `/model` | 显示或切换 AI 模型 | 想要更换 AI 模型时 | +| `/exit` | 结束会话 | 完成工作时 | + +入门就这些!随着你逐渐熟练,可以探索更多命令。 + +> 📚 **官方文档**:[CLI 命令参考](https://docs.github.com/copilot/reference/cli-command-reference) 获取完整的命令和标志列表。 + +
+📚 更多命令(点击展开) + +> 💡 上面五个命令覆盖了大量日常使用场景。这里的参考供你准备好进一步探索时使用。 + +### 智能体环境 + +| 命令 | 功能 | +|------|------| +| `/init` | 初始化仓库的 Copilot 指令 | +| `/agent` | 浏览并选择可用的智能体 | +| `/skills` | 管理技能以增强能力 | +| `/mcp` | 管理 MCP 服务器配置 | + +> 💡 技能在[第 05 章](../05-skills/README.zh-CN.md)详细介绍。MCP 服务器在[第 06 章](../06-mcp-servers/README.zh-CN.md)介绍。 + +### 模型和子智能体 + +| 命令 | 功能 | +|------|------| +| `/model` | 显示或切换 AI 模型 | +| `/delegate` | 将任务移交给 GitHub 上的 Copilot 编码智能体(云端智能体)| +| `/fleet` | 将复杂任务拆分为并行子任务以加快完成速度 | +| `/tasks` | 查看后台子智能体和独立 Shell 会话 | + +### 代码 + +| 命令 | 功能 | +|------|------| +| `/diff` | 审查当前目录中的更改 | +| `/review` | 运行代码审查智能体来分析更改 | +| `/research` | 使用 GitHub 和网络资源进行深度研究 | +| `/terminal-setup` | 启用多行输入支持(shift+enter 和 ctrl+enter)| + +### 权限 + +| 命令 | 功能 | +|------|------| +| `/allow-all` | 自动批准本次会话的所有权限提示 | +| `/add-dir <目录>` | 将目录添加到允许列表 | +| `/list-dirs` | 显示所有允许的目录 | +| `/cwd`、`/cd [目录]` | 查看或更改工作目录 | + +> ⚠️ **谨慎使用**:`/allow-all` 跳过确认提示。对于受信任的项目很方便,但处理不受信任的代码时要小心。 + +### 会话 + +| 命令 | 功能 | +|------|------| +| `/resume` | 切换到不同的会话(可选择指定会话 ID)| +| `/rename` | 重命名当前会话 | +| `/context` | 显示上下文窗口令牌使用情况和可视化 | +| `/usage` | 显示会话使用指标和统计 | +| `/session` | 显示会话信息和工作区摘要 | +| `/compact` | 总结对话以减少上下文使用 | +| `/share` | 将会话导出为 Markdown 文件或 GitHub Gist | + +### 帮助与反馈 + +| 命令 | 功能 | +|------|------| +| `/help` | 显示所有可用命令 | +| `/changelog` | 显示 CLI 版本变更日志 | +| `/feedback` | 向 GitHub 提交反馈 | +| `/theme` | 查看或设置终端主题 | + +### 快速 Shell 命令 + +在命令前加 `!` 直接运行 Shell 命令,绕过 AI: + +```bash +copilot + +> !git status +# 直接运行 git status,绕过 AI + +> !python -m pytest tests/ +# 直接运行 pytest +``` + +### 切换模型 + +Copilot CLI 支持来自 OpenAI、Anthropic、Google 等的多种 AI 模型。你可用的模型取决于你的订阅级别和地区。使用 `/model` 查看选项并切换: + +```bash +copilot +> /model + +# 显示可用模型并让你选择。选择 Sonnet 4.5。 +``` + +> 💡 **提示**:有些模型比其他模型消耗更多"高级请求"。标记为 **1x** 的模型(如 Claude Sonnet 4.5)是很好的默认选择。它们功能强大且高效。倍率更高的模型会更快消耗你的高级请求配额,所以留到真正需要时使用。 + +
+ +--- + +# 动手练习 + +温馨的桌面环境,显示器显示代码,台灯、咖啡杯和耳机,准备好动手实践 + +将所学付诸实践。 + +--- + +## ▶️ 自己试试 + +### 交互式探索 + +启动 Copilot 并使用后续提示词迭代改进书籍应用: + +```bash +copilot + +> Review @samples/book-app-project/book_app.py - what could be improved? + +> Refactor the if/elif chain into a more maintainable structure + +> Add type hints to all the handler functions + +> /exit +``` + +### 计划一个功能 + +使用 `/plan` 让 Copilot CLI 在编写任何代码之前规划实现方案: + +```bash +copilot + +> /plan Add a search feature to the book app that can find books by title or author + +# 审查计划 +# 批准或修改 +# 观察逐步实现 +``` + +### 用编程模式自动化 + +`-p` 标志让你直接从终端运行 Copilot CLI 而无需进入交互模式。从仓库根目录将以下脚本复制粘贴到终端(不是 Copilot 内部)以审查书籍应用中的所有 Python 文件。 + +```bash +# 审查书籍应用中的所有 Python 文件 +for file in samples/book-app-project/*.py; do + echo "Reviewing $file..." + copilot --allow-all -p "Quick code quality review of @$file - critical issues only" +done +``` + +**PowerShell(Windows):** + +```powershell +# 审查书籍应用中的所有 Python 文件 +Get-ChildItem samples/book-app-project/*.py | ForEach-Object { + $relativePath = "samples/book-app-project/$($_.Name)"; + Write-Host "Reviewing $relativePath..."; + copilot --allow-all -p "Quick code quality review of @$relativePath - critical issues only" +} +``` + +--- + +完成演示后,尝试这些变体: + +1. **交互式挑战**:启动 `copilot` 并探索书籍应用。询问 `@samples/book-app-project/books.py` 并连续请求改进 3 次。 + +2. **计划模式挑战**:运行 `/plan Add rating and review features to the book app`。仔细阅读计划。它有意义吗? + +3. **编程模式挑战**:运行 `copilot --allow-all -p "List all functions in @samples/book-app-project/book_app.py and describe what each does"`。第一次尝试就成功了吗? + +--- + +## 📝 作业 + +### 主要挑战:改进书籍应用工具 + +动手示例专注于审查和重构 `book_app.py`。现在在另一个文件 `utils.py` 上练习相同的技能: + +1. 启动交互式会话:`copilot` +2. 请求 Copilot CLI 总结文件:`@samples/book-app-project/utils.py What does each function in this file do?` +3. 请求添加输入验证:"Add validation to `get_user_choice()` so it handles empty input and non-numeric entries" +4. 请求改进错误处理:"What happens if `get_book_details()` receives an empty string for the title? Add guards for that." +5. 请求 docstring:"Add a comprehensive docstring to `get_book_details()` with parameter descriptions and return values" +6. 观察上下文如何在提示词之间传递。每次改进都建立在前一次的基础上 +7. 用 `/exit` 退出 + +**成功标准**:你应该通过多轮对话得到一个改进后的 `utils.py`,包含输入验证、错误处理和 docstring。 + +
+💡 提示(点击展开) + +**可以尝试的示例提示词:** +```bash +> @samples/book-app-project/utils.py What does each function in this file do? +> Add validation to get_user_choice() so it handles empty input and non-numeric entries +> What happens if get_book_details() receives an empty string for the title? Add guards for that. +> Add a comprehensive docstring to get_book_details() with parameter descriptions and return values +``` + +**常见问题:** +- 如果 Copilot CLI 提出澄清性问题,自然地回答就行 +- 上下文会延续,所以每个提示词都建立在前一个基础上 +- 如果想重新开始,使用 `/clear` + +
+ +### 附加挑战:比较三种模式 + +示例使用了 `/plan` 来规划搜索功能,使用 `-p` 进行批量审查。现在在单个新任务上尝试三种模式:向 `BookCollection` 类添加 `list_by_year()` 方法: + +1. **交互式**:`copilot` → 请求它逐步设计和构建方法 +2. **计划式**:`/plan Add a list_by_year(start, end) method to BookCollection that filters books by publication year range` +3. **编程式**:`copilot --allow-all -p "@samples/book-app-project/books.py Add a list_by_year(start, end) method that returns books published between start and end year inclusive"` + +**反思**:哪种模式感觉最自然?什么时候会使用哪种模式? + +--- + +
+🔧 常见错误与故障排除(点击展开) + +### 常见错误 + +| 错误 | 发生了什么 | 解决方法 | +|------|-----------|---------| +| 输入 `exit` 而不是 `/exit` | Copilot CLI 将"exit"视为提示词,而不是命令 | 斜杠命令总是以 `/` 开头 | +| 用 `-p` 进行多轮对话 | 每次 `-p` 调用都是独立的,不会记住前一次内容 | 需要上下文延续的对话请使用交互模式(`copilot`) | +| 提示词里包含 `$` 或 `!` 却忘了加引号 | Shell 会在 Copilot CLI 看到之前先解释这些特殊字符 | 把提示词放进引号中:`copilot -p "What does $HOME mean?"` | + +### 故障排除 + +**"Model not available"** - 你的订阅可能不包含所有模型。运行 `/model` 查看你当前可用的模型。 + +**"Context too long"** - 当前对话已经用满了上下文窗口。运行 `/clear` 重置,或者开启一个新会话。 + +**"Rate limit exceeded"** - 等几分钟后再试。对于批量操作,可以考虑使用带延迟的编程模式。 + +
+ +--- + +## 🔑 关键要点 + +1. **交互模式**适合探索和迭代,前文上下文会持续保留。它就像和一个记得你刚才说过什么的人对话。 +2. **计划模式**通常适合更复杂的任务。在真正实现之前先审查方案。 +3. **编程模式**适合自动化。不需要交互。 +4. **四个核心命令**:`/help`、`/clear`、`/plan` 和 `/exit`,已经覆盖大多数日常场景。 + +> 📋 **快速参考**:查看 [GitHub Copilot CLI 命令参考](https://docs.github.com/en/copilot/reference/cli-command-reference) 获取完整的命令和快捷键列表。 + +--- + +## ➡️ 下一步 + +现在你已经了解了三种模式,接下来就该学习如何为 Copilot CLI 提供与你代码相关的上下文。 + +在 **[第 02 章:上下文与对话](../02-context-conversations/README.zh-CN.md)** 中,你将学习: + +- 使用 `@` 语法引用文件和目录 +- 使用 `--resume` 和 `--continue` 管理会话 +- 为什么上下文管理会让 Copilot CLI 变得真正强大 + +--- + +**[← 返回课程首页](../README.zh-CN.md)** | **[继续第 02 章 →](../02-context-conversations/README.zh-CN.md)** diff --git a/02-context-conversations/README.zh-CN.md b/02-context-conversations/README.zh-CN.md new file mode 100644 index 0000000..1e82120 --- /dev/null +++ b/02-context-conversations/README.zh-CN.md @@ -0,0 +1,871 @@ +![第 02 章:上下文与对话](images/chapter-header.png) + +> **如果 AI 能看到你的整个代码库,而不是一次只看一个文件呢?** + +在本章中,你将解锁 GitHub Copilot CLI 的真正强大之处:上下文。你将学会使用 `@` 语法引用文件和目录,让 Copilot CLI 深入理解你的代码库。你将了解如何跨会话维持对话,隔几天后精确地从上次中断的地方继续工作,并看到跨文件分析如何发现单文件审查完全无法发现的 Bug。 + +## 🎯 学习目标 + +完成本章后,你将能够: + +- 使用 `@` 语法引用文件、目录和图片 +- 使用 `--resume` 和 `--continue` 恢复之前的会话 +- 理解[上下文窗口](../GLOSSARY.md#context-window)的工作原理 +- 编写有效的多轮对话 +- 管理多项目工作流的目录权限 + +> ⏱️ **预计用时**:约 50 分钟(阅读 20 分钟 + 动手 30 分钟) + +--- + +## 🧩 现实类比:与同事协作 + +上下文至关重要——没有上下文 vs 有上下文的对比 + +*就像你的同事一样,Copilot CLI 不会读心术。提供更多信息能帮助人类和 Copilot 一样提供有针对性的支持!* + +想象一下,向同事解释一个 Bug: + +> **没有上下文**:"书籍应用运行不了。" + +> **有上下文**:"看一下 `books.py`,特别是 `find_book_by_title` 函数。它没有做到大小写不敏感的匹配。" + +要向 Copilot CLI 提供上下文,使用 *`@` 语法* 将 Copilot CLI 指向特定的文件。 + +--- + +# 基础:基本上下文 + +发光的代码块由光线轨迹连接,代表上下文如何在 Copilot CLI 对话中流动 + +本节涵盖有效使用上下文所需的一切。先掌握这些基础知识。 + +--- + +## @ 语法 + +`@` 符号在你的提示词中引用文件和目录。它告诉 Copilot CLI"看这个文件"。 + +> 💡 **注意**:本课程中的所有示例都使用此仓库中的 `samples/` 文件夹,因此你可以直接尝试每个命令。 + +### 立即尝试(无需设置) + +你可以用计算机上的任何文件试试: + +```bash +copilot + +# 指向你拥有的任何文件 +> Explain what @package.json does +> Summarize @README.md +> What's in @.gitignore and why? +``` + +> 💡 **没有现成的项目?** 快速创建一个测试文件: +> ```bash +> echo "def greet(name): return 'Hello ' + name" > test.py +> copilot +> > What does @test.py do? +> ``` + +### 基本 @ 模式 + +| 模式 | 功能 | 使用示例 | +|------|------|---------| +| `@file.py` | 引用单个文件 | `Review @samples/book-app-project/books.py` | +| `@folder/` | 引用目录中的所有文件 | `Review @samples/book-app-project/` | +| `@file1.py @file2.py` | 引用多个文件 | `Compare @samples/book-app-project/book_app.py @samples/book-app-project/books.py` | + +### 引用单个文件 + +```bash +copilot + +> Explain what @samples/book-app-project/utils.py does +``` + +--- + +
+🎬 看实际演示! + +![File Context Demo](images/file-context-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +### 引用多个文件 + +```bash +copilot + +> Compare @samples/book-app-project/book_app.py and @samples/book-app-project/books.py for consistency +``` + +### 引用整个目录 + +```bash +copilot + +> Review all files in @samples/book-app-project/ for error handling +``` + +--- + +## 跨文件智能分析 + +这里是上下文成为超级能力的地方。单文件分析很有用;跨文件分析则能改变一切。 + +跨文件智能——将单文件与跨文件分析进行对比,展示如何通过一起分析文件来发现孤立分析中无法发现的 Bug、数据流和模式 + +### 演示:发现跨多个文件的 Bug + +```bash +copilot + +> @samples/book-app-project/book_app.py @samples/book-app-project/books.py +> +> How do these files work together? What's the data flow? +``` + +> 💡 **进阶选项**:对于安全相关的跨文件分析,可以尝试 Python 安全示例: +> ```bash +> > @samples/buggy-code/python/user_service.py @samples/buggy-code/python/payment_processor.py +> > Find security vulnerabilities that span BOTH files +> ``` + +--- + +
+🎬 看实际演示! + +![Multi-File Demo](images/multi-file-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +**Copilot CLI 的发现**: + +``` +Cross-Module Analysis +===================== + +1. DATA FLOW PATTERN + book_app.py creates BookCollection instance and calls methods + books.py defines BookCollection class and manages data persistence + + Flow: book_app.py (UI) → books.py (business logic) → data.json (storage) + +2. DUPLICATE DISPLAY FUNCTIONS + book_app.py:9-21 show_books() function + utils.py:28-36 print_books() function + + Impact: Two nearly identical functions doing the same thing. If you update + one (like changing the format), you must remember to update the other. + +3. INCONSISTENT ERROR HANDLING + book_app.py handles ValueError from year conversion + books.py silently returns None/False on errors + + Pattern: No unified approach to error handling across modules +``` + +**为什么这很重要**:单文件审查会错过更大的视角。只有跨文件分析才能揭示: +- **重复代码**,应该整合 +- **数据流模式**,展示组件如何交互 +- **架构问题**,影响可维护性 + +--- + +### 演示:60 秒了解一个代码库 + +分屏对比,左边显示手动代码审查需要 1 小时,右边显示 AI 辅助分析仅需 10 秒 + +对某个项目陌生?使用 Copilot CLI 快速了解它。 + +```bash +copilot + +> @samples/book-app-project/ +> +> In one paragraph, what does this app do and what are its biggest quality issues? +``` + +**你得到的**: +``` +This is a CLI book collection manager that lets users add, list, remove, and +search books stored in a JSON file. The biggest quality issues are: + +1. Duplicate display logic - show_books() and print_books() do the same thing +2. Inconsistent error handling - some errors raise exceptions, others return False +3. No input validation - year can be 0, empty strings accepted for title/author +4. Missing tests - no test coverage for critical functions like find_book_by_title + +Priority fix: Consolidate duplicate display functions and add input validation. +``` + +**结果**:原本需要一小时阅读代码的工作,压缩到 10 秒内完成。你准确地知道该关注哪里。 + +--- + +## 实际示例 + +### 示例 1:带上下文的代码审查 + +```bash +copilot + +> @samples/book-app-project/books.py Review this file for potential bugs + +# Copilot CLI 现在拥有完整的文件内容,可以提供具体反馈: +# "Line 49: Case-sensitive comparison may miss books..." +# "Line 29: JSON decode errors are caught but data corruption isn't logged..." + +> What about @samples/book-app-project/book_app.py? + +# 现在审查 book_app.py,但仍然了解 books.py 的上下文 +``` + +### 示例 2:了解代码库 + +```bash +copilot + +> @samples/book-app-project/books.py What does this module do? + +# Copilot CLI 读取 books.py 并理解 BookCollection 类 + +> @samples/book-app-project/ Give me an overview of the code structure + +# Copilot CLI 扫描目录并总结 + +> How does the app save and load books? + +# Copilot CLI 可以追踪它已经看过的代码 +``` + +
+🎬 看多轮对话的实际演示! + +![Multi-Turn Demo](images/multi-turn-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +### 示例 3:多文件重构 + +```bash +copilot + +> @samples/book-app-project/book_app.py @samples/book-app-project/utils.py +> I see duplicate display functions: show_books() and print_books(). Help me consolidate these. + +# Copilot CLI 看到两个文件,可以建议如何合并重复代码 +``` + +--- + +## 会话管理 + +会话在工作期间自动保存。你可以恢复之前的会话,从上次停止的地方继续。 + +### 会话自动保存 + +每次对话会自动保存。正常退出即可: + +```bash +copilot + +> @samples/book-app-project/ Let's improve error handling across all modules + +[... 做一些工作 ...] + +> /exit +``` + +### 恢复最近的会话 + +```bash +# 从上次停止的地方继续 +copilot --continue +``` + +### 恢复特定会话 + +```bash +# 从会话列表中交互式选择 +copilot --resume + +# 或通过 ID 恢复特定会话 +copilot --resume abc123 +``` + +> 💡 **如何找到会话 ID?** 你不需要记住它们。不带 ID 运行 `copilot --resume` 会显示你之前会话的交互列表,包括名称、ID 和最后活跃时间。只需选择你想要的会话即可。 +> +> **多个终端呢?** 每个终端窗口都是带有独立上下文的独立会话。如果在三个终端中打开了 Copilot CLI,那就是三个独立的会话。从任何终端运行 `--resume` 可以浏览所有会话。`--continue` 标志会抓取最近关闭的会话,无论它在哪个终端。 +> +> **不重启能切换会话吗?** 可以。从活跃会话中使用 `/resume` 斜杠命令: +> ``` +> > /resume +> # 显示可切换的会话列表 +> ``` + +### 整理你的会话 + +给会话起有意义的名称,方便以后查找: + +```bash +copilot + +> /rename book-app-review +# 会话已重命名,便于识别 +``` + +### 检查和管理上下文 + +随着添加文件和对话,Copilot CLI 的[上下文窗口](../GLOSSARY.md#context-window)会逐渐填满。两个命令帮你掌控: + +```bash +copilot + +> /context +Context usage: 45,000 / 128,000 tokens (35%) + +> /clear +# 清除上下文并重新开始。切换话题时使用 +``` + +> 💡 **何时使用 `/clear`**:如果你一直在审查 `books.py` 并想切换到讨论 `utils.py`,先运行 `/clear`。否则来自旧话题的过时上下文可能会干扰新的响应。 + +--- + +### 从上次停止的地方继续 + +时间线显示 GitHub Copilot CLI 会话如何跨天持久保存——周一开始,周三继续时完整恢复上下文 + +*退出时会话自动保存。几天后恢复时,文件、问题和进度都被记住。* + +想象一个跨多天的工作流: + +```bash +# 周一:开始书籍应用审查 +copilot + +> /rename book-app-review +> @samples/book-app-project/books.py +> Review and number all code quality issues + +Quality Issues Found: +1. Duplicate display functions (book_app.py & utils.py) - MEDIUM +2. No input validation for empty strings - MEDIUM +3. Year can be 0 or negative - LOW +4. No type hints on all functions - LOW +5. Missing error logging - LOW + +> Fix issue #1 (duplicate functions) +# 处理修复... + +> /exit +``` + +```bash +# 周三:从上次停止的地方精确继续 +copilot --continue + +> What issues remain unfixed from our book app review? + +Remaining issues from our book-app-review session: +2. No input validation for empty strings - MEDIUM +3. Year can be 0 or negative - LOW +4. No type hints on all functions - LOW +5. Missing error logging - LOW + +Issue #1 (duplicate functions) was fixed on Monday. + +> Let's tackle issue #2 next +``` + +**强大之处**:几天后,Copilot CLI 仍然记得: +- 你正在处理的确切文件 +- 问题的编号列表 +- 你已经解决了哪些 +- 你的对话上下文 + +--- + +🎉 **你现在已经掌握了基础知识!** `@` 语法、会话管理(`--continue`/`--resume`/`/rename`)和上下文命令(`/context`/`/clear`)足以让你高效工作。以下内容都是可选的,准备好后再阅读。 + +--- + +# 可选:深入探索 + +蓝紫色调的抽象水晶洞穴,代表对上下文概念的更深入探索 + +以下主题以上述基础为基础。**选择你感兴趣的,或直接跳到[动手练习](#动手练习)。** + +| 我想了解... | 跳转到 | +|------------|--------| +| 通配符模式和高级会话命令 | [其他 @ 模式和会话命令](#additional-patterns) | +| 跨多轮提示词构建上下文 | [上下文感知对话](#context-aware-conversations) | +| 令牌限制和 `/compact` | [了解上下文窗口](#understanding-context-windows) | +| 如何选择要引用的文件 | [选择要引用的内容](#choosing-what-to-reference) | +| 分析截图和原型图 | [处理图片](#working-with-images) | + +
+其他 @ 模式和会话命令 + + +### 其他 @ 模式 + +对于高级用户,Copilot CLI 支持通配符模式和图片引用: + +| 模式 | 功能 | +|------|------| +| `@folder/*.py` | 文件夹中的所有 .py 文件 | +| `@**/test_*.py` | 递归通配符:查找任意位置的所有测试文件 | +| `@image.png` | 用于 UI 审查的图片文件 | + +```bash +copilot + +> Find all TODO comments in @samples/book-app-project/**/*.py +``` + +### 查看会话信息 + +```bash +copilot + +> /session +# 显示当前会话详情和工作区摘要 + +> /usage +# 显示会话指标和统计 +``` + +### 分享你的会话 + +```bash +copilot + +> /share file ./my-session.md +# 将会话导出为 Markdown 文件 + +> /share gist +# 创建包含会话的 GitHub Gist +``` + +
+ +
+上下文感知对话 + + +### 上下文感知对话 + +魔法发生在你进行相互建立的多轮对话时。 + +#### 示例:渐进式增强 + +```bash +copilot + +> @samples/book-app-project/books.py Review the BookCollection class + +Copilot CLI: "The class looks functional, but I notice: +1. Missing type hints on some methods +2. No validation for empty title/author +3. Could benefit from better error handling" + +> Add type hints to all methods + +Copilot CLI: "Here's the class with complete type hints..." +[显示类型注解版本] + +> Now improve error handling + +Copilot CLI: "Building on the typed version, here's improved error handling..." +[添加验证和正确的异常] + +> Generate tests for this final version + +Copilot CLI: "Based on the class with types and error handling..." +[生成全面的测试] +``` + +注意每个提示词如何建立在之前的工作上。这就是上下文的强大之处。 + +
+ +
+了解上下文窗口 + + +### 了解上下文窗口 + +你已经从基础知识中了解了 `/context` 和 `/clear`。这里是上下文窗口如何工作的更深层面貌。 + +每个 AI 都有一个"上下文窗口",即它一次可以考虑的文本量。 + +上下文窗口可视化 + +*上下文窗口就像一张桌子:一次只能放这么多东西。文件、对话历史和系统提示词都占用空间。* + +#### 达到限制时发生什么 + +```bash +copilot + +> /context + +Context usage: 45,000 / 128,000 tokens (35%) + +# 随着添加更多文件和对话,这个数字会增长 + +> @large-codebase/ + +Context usage: 120,000 / 128,000 tokens (94%) + +# 警告:接近上下文限制 + +> @another-large-file.py + +Context limit reached. Older context will be summarized. +``` + +#### `/compact` 命令 + +当上下文快满但不想丢失对话时,`/compact` 会总结历史记录以释放令牌: + +```bash +copilot + +> /compact +# 总结对话历史,释放上下文空间 +# 保留关键发现和决策 +``` + +#### 上下文效率技巧 + +| 情况 | 操作 | 原因 | +|------|------|------| +| 开始新话题 | `/clear` | 删除不相关的上下文 | +| 长时间对话 | `/compact` | 总结历史,释放令牌 | +| 需要特定文件 | `@file.py` 而不是 `@folder/` | 只加载需要的内容 | +| 达到限制 | 开始新会话 | 全新的 128K 上下文 | +| 多个话题 | 每个话题用 `/rename` | 便于恢复正确的会话 | + +#### 大型代码库的最佳实践 + +1. **具体指定**:`@samples/book-app-project/books.py` 而不是 `@samples/book-app-project/` +2. **话题之间清除**:切换焦点时使用 `/clear` +3. **使用 `/compact`**:总结对话以释放上下文 +4. **使用多个会话**:每个功能或话题一个会话 + +
+ +
+选择要引用的内容 + + +### 选择要引用的内容 + +在上下文方面,并非所有文件都是平等的。以下是明智选择的方法: + +#### 文件大小考量 + +| 文件大小 | 约计[令牌](../GLOSSARY.md#token)数 | 策略 | +|---------|----------------------|------| +| 小(< 100 行)| 约 500-1,500 令牌 | 自由引用 | +| 中(100-500 行)| 约 1,500-7,500 令牌 | 引用特定文件 | +| 大(500+ 行)| 7,500+ 令牌 | 选择性引用 | +| 超大(1000+ 行)| 15,000+ 令牌 | 考虑拆分或针对特定部分 | + +**具体示例:** +- 书籍应用的 4 个 Python 文件合计 ≈ 2,000-3,000 令牌 +- 典型 Python 模块(200 行)≈ 3,000 令牌 +- Flask API 文件(400 行)≈ 6,000 令牌 +- 你的 package.json ≈ 200-500 令牌 +- 短提示词 + 响应 ≈ 500-1,500 令牌 + +> 💡 **代码的快速估算:** 将代码行数乘以约 15 得到大致令牌数。请注意这只是估算。 + +#### 包含什么 vs 排除什么 + +**高价值**(包含这些): +- 入口点(`book_app.py`、`main.py`、`app.py`) +- 你正在询问的特定文件 +- 目标文件直接导入的文件 +- 配置文件(`requirements.txt`、`pyproject.toml`) +- 数据模型或数据类 + +**低价值**(考虑排除): +- 生成的文件(编译输出、打包资源) +- node_modules 或 vendor 目录 +- 大型数据文件或 fixtures +- 与你的问题无关的文件 + +#### 特异性范谱 + +``` +不够具体 ────────────────────────► 非常具体 +@samples/book-app-project/ @samples/book-app-project/books.py:47-52 + │ │ + └─ 扫描所有内容 └─ 只要你需要的 + (使用更多上下文) (保留上下文) +``` + +**何时宽泛引用**(`@samples/book-app-project/`): +- 初始代码库探索 +- 查找跨多个文件的模式 +- 架构审查 + +**何时具体引用**(`@samples/book-app-project/books.py`): +- 调试特定问题 +- 审查特定文件 +- 询问单个函数 + +#### 实际示例:分阶段加载上下文 + +```bash +copilot + +# 步骤 1:从结构开始 +> @package.json What frameworks does this project use? + +# 步骤 2:根据答案缩小范围 +> @samples/book-app-project/ Show me the project structure + +# 步骤 3:专注于重要内容 +> @samples/book-app-project/books.py Review the BookCollection class + +# 步骤 4:仅在需要时添加相关文件 +> @samples/book-app-project/book_app.py @samples/book-app-project/books.py How does the CLI use the BookCollection? +``` + +这种分阶段方法使上下文保持聚焦和高效。 + +
+ +
+处理图片 + + +### 处理图片 + +你可以使用 `@` 语法在对话中包含图片,或直接**从剪贴板粘贴**(Cmd+V / Ctrl+V)。Copilot CLI 可以分析截图、原型图和图表,帮助进行 UI 调试、设计实现和错误分析。 + +```bash +copilot + +> @images/screenshot.png What is happening in this image? + +> @images/mockup.png Write the HTML and CSS to match this design. Place it in a new file called index.html and put the CSS in styles.css. +``` + +> 📖 **了解更多**:查看[其他上下文功能](../appendices/additional-context.zh-CN.md#working-with-images)了解支持的格式、实际使用案例,以及如何把图片与代码结合起来使用。 + +
+ +--- + +# 动手练习 + +温馨的桌面环境,显示器显示代码,台灯、咖啡杯和耳机,准备好动手实践 + +是时候应用你的上下文和会话管理技能了。 + +--- + +## ▶️ 自己试试 + +### 完整项目审查 + +课程包含可以直接审查的示例文件。启动 copilot 并运行以下提示词: + +```bash +copilot + +> @samples/book-app-project/ Give me a code quality review of this project + +# Copilot CLI 将识别如下问题: +# - 重复的显示函数 +# - 缺少输入验证 +# - 不一致的错误处理 +``` + +> 💡 **想用你自己的文件试试?** 创建一个小型 Python 项目(`mkdir -p my-project/src`),添加一些 .py 文件,然后使用 `@my-project/src/` 来审查它们。如果需要,可以让 copilot 为你创建示例代码! + +### 会话工作流 + +```bash +copilot + +> /rename book-app-review +> @samples/book-app-project/books.py Let's add input validation for empty titles + +[Copilot CLI 建议验证方式] + +> Implement that fix +> Now consolidate the duplicate display functions in @samples/book-app-project/ +> /exit + +# 稍后——从上次停下的地方继续 +copilot --continue + +> Generate tests for the changes we made +``` + +--- + +完成演示后,尝试这些变体: + +1. **跨文件挑战**:分析 book_app.py 和 books.py 如何协同工作: + ```bash + copilot + > @samples/book-app-project/book_app.py @samples/book-app-project/books.py + > What's the relationship between these files? Are there any code smells? + ``` + +2. **会话挑战**:启动一个会话,用 `/rename my-first-session` 命名它,做一些工作,用 `/exit` 退出,然后运行 `copilot --continue`。它还记得你在做什么吗? + +3. **上下文挑战**:在会话中途运行 `/context`。你使用了多少令牌?尝试 `/compact` 然后再检查一次。(更多关于 `/compact` 的内容,请参阅[了解上下文窗口](#understanding-context-windows)。) + +**自我检验**:当你能解释为何 `@folder/` 比逐个打开文件更强大时,说明你理解了上下文。 + +--- + +## 📝 作业 + +### 主要挑战:追踪数据流 + +动手示例专注于代码质量审查和输入验证。现在在不同任务上练习相同的上下文技能——追踪数据如何在应用中流动: + +1. 启动交互式会话:`copilot` +2. 同时引用 `books.py` 和 `book_app.py`: + `@samples/book-app-project/books.py @samples/book-app-project/book_app.py Trace how a book goes from user input to being saved in data.json. What functions are involved at each step?` +3. 引入数据文件作为额外上下文: + `@samples/book-app-project/data.json What happens if this JSON file is missing or corrupted? Which functions would fail?` +4. 请求跨文件改进: + `@samples/book-app-project/books.py @samples/book-app-project/utils.py Suggest a consistent error-handling strategy that works across both files.` +5. 重命名会话:`/rename data-flow-analysis` +6. 用 `/exit` 退出,然后用 `copilot --continue` 恢复,并就数据流提出后续问题 + +**成功标准**:你能跨多个文件追踪数据,恢复命名的会话,并获得跨文件建议。 + +
+💡 提示(点击展开) + +**入门:** +```bash +cd /path/to/copilot-cli-for-beginners +copilot +> @samples/book-app-project/books.py @samples/book-app-project/book_app.py Trace how a book goes from user input to being saved in data.json. +> @samples/book-app-project/data.json What happens if this file is missing or corrupted? +> /rename data-flow-analysis +> /exit +``` + +然后用 `copilot --continue` 恢复 + +**有用的命令:** +- `@file.py` - 引用单个文件 +- `@folder/` - 引用文件夹中的所有文件(注意末尾的 `/`) +- `/context` - 检查使用了多少上下文 +- `/rename <名称>` - 命名你的会话以便轻松恢复 + +
+ +### 附加挑战:上下文限制 + +1. 使用 `@samples/book-app-project/` 一次性引用所有书籍应用文件 +2. 就不同文件(`books.py`、`utils.py`、`book_app.py`、`data.json`)提出几个详细问题 +3. 运行 `/context` 查看使用情况。填满的速度有多快? +4. 练习使用 `/compact` 回收空间,然后继续对话 +5. 尝试更具体的文件引用(例如 `@samples/book-app-project/books.py` 而不是整个文件夹),观察它如何影响上下文使用 + +--- + +
+🔧 常见错误与故障排除(点击展开) + +### 常见错误 + +| 错误 | 发生了什么 | 解决方法 | +|------|-----------|---------| +| 文件名前忘记 `@` | Copilot CLI 将"books.py"视为纯文本 | 使用 `@samples/book-app-project/books.py` 引用文件 | +| 期望会话自动持久 | 全新启动 `copilot` 会丢失所有之前的上下文 | 使用 `--continue`(最近的会话)或 `--resume`(选择会话)| +| 引用当前目录之外的文件 | "Permission denied"或"File not found"错误 | 使用 `/add-dir /path/to/directory` 授予访问权限 | +| 切换话题时不使用 `/clear` | 旧上下文干扰新话题的响应 | 在开始不同任务前运行 `/clear` | + +### 故障排除 + +**"File not found"错误** — 确保你在正确的目录中: + +```bash +pwd # 检查当前目录 +ls # 列出文件 + +# 然后启动 copilot 并使用相对路径 +copilot + +> Review @samples/book-app-project/books.py +``` + +**"Permission denied"** — 将目录添加到允许列表: + +```bash +copilot --add-dir /path/to/directory + +# 或在会话中: +> /add-dir /path/to/directory +``` + +**上下文填满太快**: +- 更具体地指定文件引用 +- 在不同话题之间使用 `/clear` +- 将工作拆分到多个会话中 + +
+ +--- + +# 总结 + +## 🔑 关键要点 + +1. **`@` 语法**赋予 Copilot CLI 关于文件、目录和图片的上下文 +2. **多轮对话**随着上下文积累相互建立 +3. **会话自动保存**:使用 `--continue` 或 `--resume` 从上次停止的地方继续 +4. **上下文窗口**有限制:使用 `/context`、`/clear` 和 `/compact` 管理它们 +5. **权限标志**(`--add-dir`、`--allow-all`)控制多目录访问。明智使用! +6. **图片引用**(`@screenshot.png`)帮助直观调试 UI 问题 + +> 📚 **官方文档**:[使用 Copilot CLI](https://docs.github.com/copilot/how-tos/copilot-cli/use-copilot-cli) 获取上下文、会话和文件处理的完整参考。 + +> 📋 **快速参考**:查看 [GitHub Copilot CLI 命令参考](https://docs.github.com/en/copilot/reference/cli-command-reference) 获取完整的命令和快捷键列表。 + +--- + +## ➡️ 下一步 + +现在你能给 Copilot CLI 提供上下文了,让我们把它应用到真实的开发任务中。你刚刚学到的上下文技术(文件引用、跨文件分析和会话管理)是下一章强大工作流的基础。 + +在 **[第 03 章:开发工作流](../03-development-workflows/README.zh-CN.md)** 中,你将学习: + +- 代码审查工作流 +- 重构模式 +- 调试辅助 +- 测试生成 +- Git 集成 + +--- + +**[← 返回第 01 章](../01-setup-and-first-steps/README.zh-CN.md)** | **[继续第 03 章 →](../03-development-workflows/README.zh-CN.md)** diff --git a/03-development-workflows/README.zh-CN.md b/03-development-workflows/README.zh-CN.md new file mode 100644 index 0000000..8e07b41 --- /dev/null +++ b/03-development-workflows/README.zh-CN.md @@ -0,0 +1,896 @@ +![第 03 章:开发工作流](images/chapter-header.png) + +> **如果 AI 能发现你甚至不知道要问的 Bug 呢?** + +在本章中,GitHub Copilot CLI 将成为你的日常工具。你将在已经依赖的工作流中使用它:测试、重构、调试和 Git。 + +## 🎯 学习目标 + +完成本章后,你将能够: + +- 使用 Copilot CLI 进行全面的代码审查 +- 安全地重构遗留代码 +- 借助 AI 调试问题 +- 自动生成测试 +- 将 Copilot CLI 集成到 Git 工作流中 + +> ⏱️ **预计用时**:约 60 分钟(阅读 15 分钟 + 动手 45 分钟) + +--- + +## 🧩 现实类比:木匠的工作流 + +木匠不只是知道如何使用工具,他们针对不同工作有*工作流*: + +工匠工坊,展示三种工作流:制作家具(测量、切割、组装、精加工)、修复损坏(评估、移除、修复、匹配)和质量检查(检查、测试接头、检查对齐) + +类似地,开发者针对不同任务有工作流。GitHub Copilot CLI 增强了这些工作流,让你在日常编码任务中更高效、更有效。 + +--- + +# 五大工作流 + +五个发光的霓虹图标,代表代码审查、测试、调试、重构和 Git 集成工作流 + +以下每个工作流都是独立的。选择与你当前需求匹配的工作流,或全部学习。 + +--- + +## 自主选择 + +本章涵盖开发者通常使用的五种工作流。**但是,你不需要一次全部阅读!** 每个工作流都自包含在下方可折叠的部分中。选择与你现在需要的内容最匹配的工作流,以及最适合你当前项目的工作流。你随时可以回来探索其他工作流。 + +五种开发工作流:代码审查、重构、调试、测试生成和 Git 集成,以水平泳道展示 + +| 我想... | 跳转到 | +|--------|--------| +| 合并前审查代码 | [工作流 1:代码审查](#workflow-1-code-review) | +| 清理混乱或遗留代码 | [工作流 2:重构](#workflow-2-refactoring) | +| 追踪并修复 Bug | [工作流 3:调试](#workflow-3-debugging) | +| 为代码生成测试 | [工作流 4:测试生成](#workflow-4-test-generation) | +| 写出更好的提交和 PR | [工作流 5:Git 集成](#workflow-5-git-integration) | +| 编码前先调研 | [快速技巧:编码前先调研](#quick-tip-research-before-you-plan-or-code) | +| 看完整的 Bug 修复工作流 | [综合运用](#putting-it-all-together-bug-fix-workflow) | + +**点击下方展开某个工作流**,了解 GitHub Copilot CLI 如何增强该领域的开发流程。 + +--- + + +
+工作流 1:代码审查——审查文件、使用 /review 智能体、创建严重性检查清单 + +代码审查工作流:审查、识别问题、优先级排序、生成检查清单。 + +### 基础审查 + +此示例使用 `@` 符号引用文件,让 Copilot CLI 直接访问其内容进行审查。 + +```bash +copilot + +> Review @samples/book-app-project/book_app.py for code quality +``` + +--- + +
+🎬 看实际演示! + +![Code Review Demo](images/code-review-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +### 输入验证审查 + +通过在提示词中列出你关心的类别,让 Copilot CLI 专注于特定关注点(此处为输入验证)。 + +```text +copilot + +> Review @samples/book-app-project/utils.py for input validation issues. Check for: missing validation, error handling gaps, and edge cases +``` + + +### 跨文件项目审查 + +使用 `@` 引用整个目录,让 Copilot CLI 一次扫描项目中的每个文件。 + +```bash +copilot + +> @samples/book-app-project/ Review this entire project. Create a markdown checklist of issues found, categorized by severity +``` + +### 交互式代码审查 + +使用多轮对话深入挖掘。从宏观审查开始,然后提出后续问题,无需重新启动。 + +```bash +copilot + +> @samples/book-app-project/book_app.py Review this file for: +> - Input validation +> - Error handling +> - Code style and best practices + +# Copilot CLI 提供详细审查 + +> The user input handling - are there any edge cases I'm missing? + +# Copilot CLI 显示空字符串、特殊字符的潜在问题 + +> Create a checklist of all issues found, prioritized by severity + +# Copilot CLI 生成按优先级排序的行动项 +``` + +### 审查检查清单模板 + +让 Copilot CLI 以特定格式(此处为按严重性分类的 Markdown 检查清单,可粘贴到 issue 中)构建输出。 + +```bash +copilot + +> Review @samples/book-app-project/ and create a markdown checklist of issues found, categorized by: +> - Critical (data loss risks, crashes) +> - High (bugs, incorrect behavior) +> - Medium (performance, maintainability) +> - Low (style, minor improvements) +``` + +### 了解 Git 更改(使用 /review 前必读) + +使用 `/review` 命令之前,需要了解 Git 中两种类型的更改: + +| 更改类型 | 含义 | 如何查看 | +|---------|------|---------| +| **已暂存的更改** | 用 `git add` 标记为下次提交的文件 | `git diff --staged` | +| **未暂存的更改** | 已修改但尚未添加的文件 | `git diff` | + +```bash +# 快速参考 +git status # 显示已暂存和未暂存的内容 +git add file.py # 将文件暂存以便提交 +git diff # 显示未暂存的更改 +git diff --staged # 显示已暂存的更改 +``` + +### 使用 /review 命令 + +`/review` 命令调用内置的**代码审查智能体**,它针对分析已暂存和未暂存的更改进行了优化,输出高质量、低噪音的反馈。使用斜杠命令触发专门的内置智能体,而不是编写自由形式的提示词。 + +```bash +copilot + +> /review +# 对已暂存/未暂存的更改调用代码审查智能体 +# 提供聚焦、可操作的反馈 + +> /review Check for security issues in authentication +# 以特定关注点运行审查 +``` + +> 💡 **提示**:代码审查智能体在有待处理更改时效果最佳。使用 `git add` 暂存文件以获得更聚焦的审查。 + +
+ +--- + + +
+工作流 2:重构——重组代码、分离关注点、改进错误处理 + +重构工作流:评估代码、规划更改、实施、验证行为。 + +### 简单重构 + +> **先试试这个:** `@samples/book-app-project/book_app.py The command handling uses if/elif chains. Refactor it to use a dictionary dispatch pattern.` + +从简单的改进开始。在书籍应用上尝试这些。每个提示词都将 `@` 文件引用与具体的重构指令配对,让 Copilot CLI 知道确切要更改什么。 + +```bash +copilot + +> @samples/book-app-project/book_app.py The command handling uses if/elif chains. Refactor it to use a dictionary dispatch pattern. + +> @samples/book-app-project/utils.py Add type hints to all functions + +> @samples/book-app-project/book_app.py Extract the book display logic into utils.py for better separation of concerns +``` + +> 💡 **重构新手?** 在尝试复杂的转换之前,先从添加类型注解或改进变量名等简单请求开始。 + +--- + +
+🎬 看实际演示! + +![Refactor Demo](images/refactor-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +### 分离关注点 + +在单个提示词中使用 `@` 引用多个文件,让 Copilot CLI 可以在重构中在文件间移动代码。 + +```bash +copilot + +> @samples/book-app-project/utils.py @samples/book-app-project/book_app.py +> The utils.py file has print statements mixed with logic. Refactor to separate display functions from data processing. +``` + +### 改进错误处理 + +提供两个相关文件并描述横切关注点,让 Copilot CLI 可以建议跨两个文件一致的修复。 + +```bash +copilot + +> @samples/book-app-project/utils.py @samples/book-app-project/books.py +> These files have inconsistent error handling. Suggest a unified approach using custom exceptions. +``` + +### 添加文档 + +使用详细的项目符号列表精确指定每个 docstring 应包含的内容。 + +```bash +copilot + +> @samples/book-app-project/books.py Add comprehensive docstrings to all methods: +> - Include parameter types and descriptions +> - Document return values +> - Note any exceptions raised +> - Add usage examples +``` + +### 安全重构(先生成测试) + +在多轮对话中链接两个相关请求。先生成测试,然后以这些测试作为安全网进行重构。 + +```bash +copilot + +> @samples/book-app-project/books.py Before refactoring, generate tests for current behavior + +# 先获取测试 + +> Now refactor the BookCollection class to use a context manager for file operations + +# 有了测试保障,重构更有把握——测试验证行为未被破坏 +``` + +
+ +--- + + +
+工作流 3:调试——追踪 Bug、安全审计、跨文件追踪问题 + +调试工作流:理解错误、定位根因、修复、测试。 + +### 简单调试 + +> **先试试这个:** `@samples/book-app-buggy/books_buggy.py Users report that searching for "The Hobbit" returns no results even though it's in the data. Debug why.` + +先描述出了什么问题。这里是可以在有 Bug 的书籍应用上尝试的常见调试模式。每个提示词将 `@` 文件引用与清晰的症状描述配对,让 Copilot CLI 能够定位并诊断 Bug。 + +```bash +copilot + +# 模式:"期望 X 但得到了 Y" +> @samples/book-app-buggy/books_buggy.py Users report that searching for "The Hobbit" returns no results even though it's in the data. Debug why. + +# 模式:"意外行为" +> @samples/book-app-buggy/book_app_buggy.py When I remove a book that doesn't exist, the app says it was removed. Help me find why. + +# 模式:"错误结果" +> @samples/book-app-buggy/books_buggy.py When I mark one book as read, ALL books get marked. What's the bug? +``` + +> 💡 **调试技巧**:描述*症状*(你看到的)和*期望*(应该发生的)。Copilot CLI 会找出其余的。 + +--- + +
+🎬 看实际演示! + +![Fix Bug Demo](images/fix-bug-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +### "Bug 侦探"——AI 发现相关 Bug + +这就是上下文感知调试闪光的地方。在有 Bug 的书籍应用上尝试这个场景。通过 `@` 提供整个文件,只描述用户报告的症状。Copilot CLI 将追踪根因,可能还会发现附近的其他 Bug。 + +```bash +copilot + +> @samples/book-app-buggy/books_buggy.py +> +> Users report: "Finding books by author name doesn't work for partial names" +> Debug why this happens +``` + +**Copilot CLI 的操作**: +``` +Root Cause: Line 80 uses exact match (==) instead of partial match (in). + +Line 80: return [b for b in self.books if b.author == author] + +The find_by_author function requires an exact match. Searching for "Tolkien" +won't find books by "J.R.R. Tolkien". + +Fix: Change to case-insensitive partial match: +return [b for b in self.books if author.lower() in b.author.lower()] +``` + +**为什么这很重要**:Copilot CLI 读取整个文件,理解你 Bug 报告的上下文,并给你具有清晰说明的具体修复。 + +> 💡 **彩蛋**:因为 Copilot CLI 分析整个文件,它通常会发现你没有询问的*其他*问题。例如,在修复作者搜索时,Copilot CLI 可能还会注意到 `find_book_by_title` 中的大小写敏感 Bug! + +### 现实安全侧注 + +在调试自己的代码时,理解生产应用中的安全漏洞同样关键。试试这个示例:将 Copilot CLI 指向一个陌生的文件,让它进行安全审计。 + +```bash +copilot + +> @samples/buggy-code/python/user_service.py Find all security vulnerabilities in this Python user service +``` + +这个文件展示了你在生产应用中会遇到的真实世界安全模式。 + +> 💡 **你会遇到的常见安全术语:** +> - **SQL 注入**:当用户输入直接放入数据库查询时,允许攻击者运行恶意命令 +> - **参数化查询**:安全的替代方案——占位符(`?`)将用户数据与 SQL 命令分开 +> - **竞争条件**:当两个操作同时发生并相互干扰时 +> - **XSS(跨站脚本)**:当攻击者将恶意脚本注入网页时 + +--- + +### 理解错误 + +将堆栈跟踪与 `@` 文件引用一起粘贴到提示词中,让 Copilot CLI 可以将错误映射到源代码。 + +```bash +copilot + +> I'm getting this error: +> AttributeError: 'NoneType' object has no attribute 'title' +> at show_books (book_app.py:19) +> +> @samples/book-app-project/book_app.py Explain why and how to fix it +``` + +### 用测试用例调试 + +描述确切的输入和观察到的输出,给 Copilot CLI 一个具体的、可重现的测试用例来推理。 + +```bash +copilot + +> @samples/book-app-buggy/books_buggy.py The remove_book function has a bug. When I try to remove "Dune", +> it also removes "Dune Messiah". Debug this: explain the root cause and provide a fix. +``` + +### 跨代码追踪问题 + +引用多个文件,让 Copilot CLI 追踪数据流,定位问题的源头。 + +```bash +copilot + +> Users report that the book list numbering starts at 0 instead of 1. +> @samples/book-app-buggy/book_app_buggy.py @samples/book-app-buggy/books_buggy.py +> Trace through the list display flow and identify where the issue occurs +``` + +### 了解数据问题 + +在代码旁边包含读取它的数据文件,让 Copilot CLI 在建议错误处理改进时了解完整情况。 + +```bash +copilot + +> @samples/book-app-project/data.json @samples/book-app-project/books.py +> Sometimes the JSON file gets corrupted and the app crashes. How should we handle this gracefully? +``` + +
+ +--- + + +
+工作流 4:测试生成——自动生成全面测试和边缘用例 + +测试生成工作流:分析函数、生成测试、包含边缘用例、运行。 + +> **先试试这个:** `@samples/book-app-project/books.py Generate pytest tests for all functions including edge cases` + +### "测试爆炸"——2 个测试 vs 15+ 个测试 + +手动编写测试时,开发者通常只创建 2-3 个基础测试: +- 测试有效输入 +- 测试无效输入 +- 测试边缘用例 + +看看当你让 Copilot CLI 生成全面测试时会发生什么!这个提示词使用带有 `@` 文件引用的结构化项目列表,引导 Copilot CLI 进行全面的测试覆盖: + +```bash +copilot + +> @samples/book-app-project/books.py Generate comprehensive pytest tests. Include tests for: +> - Adding books +> - Removing books +> - Finding by title +> - Finding by author +> - Marking as read +> - Edge cases with empty data +``` + +--- + +
+🎬 看实际演示! + +![Test Generation Demo](images/test-gen-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +**你得到的**:15+ 个全面测试,包括: + +```python +class TestBookCollection: + # 正常路径 + def test_add_book_creates_new_book(self): + ... + def test_list_books_returns_all_books(self): + ... + + # 查找操作 + def test_find_book_by_title_case_insensitive(self): + ... + def test_find_book_by_title_returns_none_when_not_found(self): + ... + def test_find_by_author_partial_match(self): + ... + def test_find_by_author_case_insensitive(self): + ... + + # 边缘用例 + def test_add_book_with_empty_title(self): + ... + def test_remove_nonexistent_book(self): + ... + def test_mark_as_read_nonexistent_book(self): + ... + + # 数据持久性 + def test_save_books_persists_to_json(self): + ... + def test_load_books_handles_missing_file(self): + ... + def test_load_books_handles_corrupted_json(self): + ... + + # 特殊字符 + def test_add_book_with_unicode_characters(self): + ... + def test_find_by_author_with_special_characters(self): + ... +``` + +**结果**:30 秒内,你得到了手动思考和编写需要一小时的边缘用例测试。 + +--- + +### 单元测试 + +针对单个函数,列举你想要测试的输入类别,让 Copilot CLI 生成聚焦、全面的单元测试。 + +```bash +copilot + +> @samples/book-app-project/utils.py Generate comprehensive pytest tests for get_book_details covering: +> - Valid input +> - Empty strings +> - Invalid year formats +> - Very long titles +> - Special characters in author names +``` + +### 运行测试 + +用自然语言向 Copilot CLI 提问关于你工具链的问题。它可以为你生成正确的 Shell 命令。 + +```bash +copilot + +> How do I run the tests? Show me the pytest command. + +# Copilot CLI 响应: +# cd samples/book-app-project && python -m pytest tests/ +# 或详细输出:python -m pytest tests/ -v +# 查看 print 语句:python -m pytest tests/ -s +``` + +### 针对特定场景测试 + +列出你想覆盖的高级或棘手场景,让 Copilot CLI 超越正常路径。 + +```bash +copilot + +> @samples/book-app-project/books.py Generate tests for these scenarios: +> - Adding duplicate books (same title and author) +> - Removing a book by partial title match +> - Finding books when collection is empty +> - File permission errors during save +> - Concurrent access to the book collection +``` + +### 向现有文件添加测试 + +为单个函数请求*额外*的测试,让 Copilot CLI 生成补充你现有测试的新用例。 + +```bash +copilot + +> @samples/book-app-project/books.py +> Generate additional tests for the find_by_author function with edge cases: +> - Author name with hyphens (e.g., "Jean-Paul Sartre") +> - Author with multiple first names +> - Empty string as author +> - Author name with accented characters +``` + +
+ +--- + + +
+工作流 5:Git 集成——提交消息、PR 描述、/delegate 和 /diff + +Git 集成工作流:暂存更改、生成消息、提交、创建 PR。 + +> 💡 **此工作流假设你具备基本的 Git 知识**(暂存、提交、分支)。如果 Git 对你来说是新的,先尝试其他四个工作流。 + +### 生成提交消息 + +> **先试试这个:** `copilot -p "Generate a conventional commit message for: $(git diff --staged)"` — 暂存一些更改,然后运行这个命令,让 Copilot CLI 为你写提交消息。 + +此示例使用 `-p` 内联提示词标志与 Shell 命令替换,将 `git diff` 输出直接传给 Copilot CLI 进行一次性提交消息生成。`$(...)` 语法运行括号内的命令并将其输出插入到外部命令中。 + +```bash + +# 查看更改了什么 +git diff --staged + +# 使用[约定式提交](../GLOSSARY.md#conventional-commit)格式生成提交消息 +# (如"feat(books): add search"或"fix(data): handle empty input"的结构化消息) +copilot -p "Generate a conventional commit message for: $(git diff --staged)" + +# 输出:"feat(books): add partial author name search +# +# - Update find_by_author to support partial matches +# - Add case-insensitive comparison +# - Improve user experience when searching authors" +``` + +--- + +
+🎬 看实际演示! + +![Git Integration Demo](images/git-integration-demo.gif) + +*演示输出仅供参考。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +### 解释更改 + +将 `git show` 的输出通过管道传给 `-p` 提示词,获取最近一次提交的简洁英文摘要。 + +```bash +# 这次提交更改了什么? +copilot -p "Explain what this commit does: $(git show HEAD --stat)" +``` + +### PR 描述 + +将 `git log` 输出与结构化提示词模板结合,自动生成完整的 Pull Request 描述。 + +```bash +# 从分支更改生成 PR 描述 +copilot -p "Generate a pull request description for these changes: +$(git log main..HEAD --oneline) + +Include: +- Summary of changes +- Why these changes were made +- Testing done +- Breaking changes? (yes/no)" +``` + +### 推送前审查 + +在 `-p` 提示词中使用 `git diff main..HEAD` 对所有分支更改进行快速的推送前健全性检查。 + +```bash +# 推送前的最后检查 +copilot -p "Review these changes for issues before I push: +$(git diff main..HEAD)" +``` + +### 使用 /delegate 处理后台任务 + +`/delegate` 命令将工作移交给 GitHub 上的 Copilot 编码智能体。使用 `/delegate` 斜杠命令(或 `&` 快捷方式)将定义明确的任务下放给后台智能体。 + +```bash +copilot + +> /delegate Add input validation to the login form + +# 或使用 & 前缀快捷方式: +> & Fix the typo in the README header + +# Copilot CLI: +# 1. 将你的更改提交到新分支 +# 2. 创建草稿 PR +# 3. 在 GitHub 后台工作 +# 4. 完成后请求你的审查 +``` + +这对于你想在专注于其他工作时完成的定义明确的任务非常有用。 + +### 使用 /diff 审查会话更改 + +`/diff` 命令显示你当前会话中所做的所有更改。在提交之前使用这个斜杠命令查看 Copilot CLI 修改的所有内容的可视化差异。 + +```bash +copilot + +# 做了一些更改之后... +> /diff + +# 显示本次会话中修改的所有文件的可视化差异 +# 提交前审查的好工具 +``` + +
+ +--- + + +## 快速技巧:编码前先调研 + +当你需要调查某个库、了解最佳实践或探索不熟悉的主题时,在编写任何代码之前使用 `/research` 进行深度调研: + +```bash +copilot + +> /research What are the best Python libraries for validating user input in CLI apps? +``` + +Copilot 搜索 GitHub 仓库和网络资源,然后返回带有参考资料的摘要。当你即将开始新功能并想做出明智决策时,这非常有用。你可以使用 `/share` 分享结果。 + +--- + + +## ▶️ 自己试试 + +完成演示后,尝试这些变体: + +1. **Bug 侦探挑战**:让 Copilot CLI 调试 `samples/book-app-buggy/books_buggy.py` 中的 `mark_as_read` 函数。它是否解释了为什么该函数将所有书籍都标记为已读,而不仅仅是一本? + +2. **测试挑战**:为书籍应用中的 `add_book` 函数生成测试。数一数 Copilot CLI 包含了多少你不会想到的边缘用例。 + +3. **提交消息挑战**:对某个书籍应用文件进行任何小改动,暂存它(`git add .`),然后运行: + ```bash + copilot -p "Generate a conventional commit message for: $(git diff --staged)" + ``` + 这条消息比你快速写出的更好吗? + +**自我检验**:当你能解释为什么"调试这个 Bug"比"查找 Bug"更强大时(上下文很重要!),说明你理解了开发工作流。 + +--- + +## 📝 作业 + +### 主要挑战:重构、测试并交付 + +动手示例专注于 `find_book_by_title` 和代码审查。现在在 `book-app-project` 的不同函数上练习相同的工作流技能: + +1. **审查**:让 Copilot CLI 审查 `books.py` 中的 `remove_book()` 的边缘用例和潜在问题: + `@samples/book-app-project/books.py Review the remove_book() function. What happens if the title partially matches another book (e.g., "Dune" vs "Dune Messiah")? Are there any edge cases not handled?` +2. **重构**:让 Copilot CLI 改进 `remove_book()` 以处理大小写不敏感匹配等边缘用例,并在找不到书时返回有用的反馈 +3. **测试**:专门为改进后的 `remove_book()` 函数生成 pytest 测试,覆盖: + - 删除存在的书 + - 大小写不敏感的标题匹配 + - 找不到书时返回适当的反馈 + - 从空集合中删除 +4. **审查**:暂存你的更改并运行 `/review` 检查剩余问题 +5. **提交**:生成约定式提交消息: + `copilot -p "Generate a conventional commit message for: $(git diff --staged)"` + +
+💡 提示(点击展开) + +**每步的示例提示词:** + +```bash +copilot + +# 步骤 1:审查 +> @samples/book-app-project/books.py Review the remove_book() function. What edge cases are not handled? + +# 步骤 2:重构 +> Improve remove_book() to use case-insensitive matching and return a clear message when the book isn't found. Show me the before and after code. + +# 步骤 3:测试 +> Generate pytest tests for the improved remove_book() function, including: +> - Removing a book that exists +> - Case-insensitive matching ("dune" should remove "Dune") +> - Book not found returns appropriate response +> - Removing from an empty collection + +# 步骤 4:审查 +> /review + +# 步骤 5:提交 +> Generate a conventional commit message for this refactor +``` + +**提示:** 改进 `remove_book()` 后,尝试让 Copilot CLI:"Are there any other functions in this file that could benefit from the same improvements?",它可能会建议对 `find_book_by_title()` 或 `find_by_author()` 进行类似的改进。 + +
+ +### 附加挑战:用 Copilot CLI 创建应用 + +> 💡 **注意**:这个 GitHub Skills 练习使用 **Node.js** 而不是 Python。你将练习的 GitHub Copilot CLI 技术——创建 issue、生成代码和从终端协作——适用于任何语言。 + +这个练习向开发者展示如何使用 GitHub Copilot CLI 创建 issue、生成代码,并在构建 Node.js 计算器应用的过程中从终端进行协作。 + +##### [开始"使用 Copilot CLI 创建应用"技能练习](https://github.com/skills/create-applications-with-the-copilot-cli) + +--- + +
+🔧 常见错误与故障排除(点击展开) + +### 常见错误 + +| 错误 | 发生了什么 | 解决方法 | +|------|-----------|---------| +| 使用模糊的提示词如"审查这段代码" | 遗漏特定问题的通用反馈 | 具体说明:"Review for SQL injection, XSS, and auth issues" | +| 不使用 `/review` 进行代码审查 | 错过优化的代码审查智能体 | 使用 `/review`,它针对高质量输出进行了调整 | +| 在没有上下文的情况下要求"查找 Bug" | Copilot CLI 不知道你遇到的是什么 Bug | 描述症状:"Users report X happens when Y" | +| 生成测试时不指定框架 | 测试可能使用错误的语法或断言库 | 指定:"Generate tests using Jest"或"using pytest" | + +### 故障排除 + +**审查似乎不完整** — 更具体地说明要查找什么: + +```bash +copilot + +# 替代: +> Review @samples/book-app-project/book_app.py + +# 尝试: +> Review @samples/book-app-project/book_app.py for input validation, error handling, and edge cases +``` + +**测试与我的框架不匹配** — 指定框架: + +```bash +copilot + +> @samples/book-app-project/books.py Generate tests using pytest (not unittest) +``` + +**重构改变了行为** — 让 Copilot CLI 保持行为不变: + +```bash +copilot + +> @samples/book-app-project/book_app.py Refactor command handling to use dictionary dispatch. IMPORTANT: Maintain identical external behavior - no breaking changes +``` + +
+ +--- + +# 总结 + +## 🔑 关键要点 + +每种任务的专门工作流:代码审查、重构、调试、测试和 Git 集成 + +1. **代码审查**通过具体的提示词变得全面 +2. **重构**在先生成测试时更安全 +3. **调试**通过同时向 Copilot CLI 展示错误**和**代码而受益 +4. **测试生成**应包含边缘用例和错误场景 +5. **Git 集成**自动化提交消息和 PR 描述 + +> 📋 **快速参考**:查看 [GitHub Copilot CLI 命令参考](https://docs.github.com/en/copilot/reference/cli-command-reference) 获取完整的命令和快捷键列表。 + +--- + +## ✅ 检查点:你已掌握基础知识 + +**恭喜!** 你现在具备了使用 GitHub Copilot CLI 的所有核心技能: + +| 技能 | 章节 | 你现在能... | +|------|------|------------| +| 基本命令 | 第 01 章 | 使用交互式模式、计划模式、编程模式(-p)和斜杠命令 | +| 上下文 | 第 02 章 | 用 `@` 引用文件、管理会话、理解上下文窗口 | +| 工作流 | 第 03 章 | 审查代码、重构、调试、生成测试、与 Git 集成 | + +第 04-06 章涵盖了更多功能,值得学习。 + +--- + +## 🛠️ 构建你的个人工作流 + +使用 GitHub Copilot CLI 没有唯一"正确"的方式。以下是你发展自己模式时的一些技巧: + +> 📚 **官方文档**:[Copilot CLI 最佳实践](https://docs.github.com/copilot/how-tos/copilot-cli/cli-best-practices) 获取 GitHub 推荐的工作流和技巧。 + +- **对任何非简单的任务都先用 `/plan`**。在执行前完善计划——好计划带来更好的结果。 +- **保存运作良好的提示词。** 当 Copilot CLI 出错时,记下出了什么问题。随着时间推移,这将成为你的个人操作手册。 +- **自由实验。** 有些开发者喜欢长而详细的提示词。其他人喜欢短提示词加后续问题。尝试不同的方式,注意什么感觉自然。 + +> 💡 **即将到来**:在第 04 章和第 05 章中,你将学习如何将你的最佳实践编码到 Copilot CLI 自动加载的自定义指令和技能中。 + +--- + +## ➡️ 接下来 + +剩余章节涵盖扩展 Copilot CLI 功能的额外特性: + +| 章节 | 内容 | 你什么时候会需要它 | +|------|------|-----------------| +| 第 04 章:智能体 | 创建专门的 AI 角色 | 当你需要领域专家时(前端、安全)| +| 第 05 章:技能 | 自动加载任务指令 | 当你经常重复相同的提示词时 | +| 第 06 章:MCP | 连接外部服务 | 当你需要来自 GitHub、数据库的实时数据时 | + +**建议**:使用核心工作流一周,然后在有具体需求时再回来学习第 04-06 章。 + +--- + +在 **[第 04 章:智能体与自定义指令](../04-agents-custom-instructions/README.zh-CN.md)** 中,你将学习: + +- 使用内置智能体(`/plan`、`/review`) +- 用 `.agent.md` 文件创建专门的智能体(前端专家、安全审计员) +- 多智能体协作模式 +- 项目标准的自定义指令文件 + +--- + +**[← 返回第 02 章](../02-context-conversations/README.zh-CN.md)** | **[继续第 04 章 →](../04-agents-custom-instructions/README.zh-CN.md)** diff --git a/04-agents-custom-instructions/README.zh-CN.md b/04-agents-custom-instructions/README.zh-CN.md new file mode 100644 index 0000000..c4f81a2 --- /dev/null +++ b/04-agents-custom-instructions/README.zh-CN.md @@ -0,0 +1,768 @@ +![第 04 章:智能体与自定义指令](images/chapter-header.png) + +> **如果你能同时雇佣一个 Python 代码审查员、测试专家和安全审查员……全都在一个工具里呢?** + +在第 03 章中,你掌握了基本工作流:代码审查、重构、调试、测试生成和 Git 集成。这些工作流让你使用 GitHub Copilot CLI 高效工作。现在,让我们更进一步。 + +到目前为止,你一直将 Copilot CLI 用作通用助手。智能体让你为它赋予特定角色,附带内置标准——比如一个强制执行类型注解和 PEP 8 的代码审查员,或是一个编写 pytest 用例的测试助手。你会看到相同的提示词在由具有针对性指令的智能体处理时,能得到明显更好的结果。 + +## 🎯 学习目标 + +完成本章后,你将能够: + +- 使用内置智能体:Plan(`/plan`)、Code-review(`/review`),并了解自动智能体(Explore、Task) +- 使用智能体文件(`.agent.md`)创建专门的智能体 +- 将智能体用于特定领域的任务 +- 使用 `/agent` 和 `--agent` 切换智能体 +- 为项目特定标准编写自定义指令文件 + +> ⏱️ **预计用时**:约 55 分钟(阅读 20 分钟 + 动手 35 分钟) + +--- + +## 🧩 现实类比:雇佣专家 + +当你需要房屋帮助时,你不会打电话给一个"通用帮手",而是打给专家: + +| 问题 | 专家 | 原因 | +|------|------|------| +| 水管漏水 | 水管工 | 了解管道规范,有专业工具 | +| 电路重新布线 | 电工 | 了解安全要求,符合规范 | +| 新屋顶 | 屋顶工 | 了解材料、当地天气因素 | + +智能体的工作方式相同。与其使用通用 AI,不如使用专注于特定任务并知道正确流程的智能体。一次设置好指令,每当你需要该专业时就可以复用:代码审查、测试、安全、文档。 + +雇佣专家类比——就像你为房屋修缮呼叫专业工匠一样,AI 智能体专门用于代码审查、测试、安全和文档等特定任务 + +--- + +# 使用智能体 + +立即开始使用内置和自定义智能体。 + +--- + +## *智能体新手?* 从这里开始! +从未使用或制作过智能体?以下是本课程入门所需了解的一切。 + +1. **立即试用*内置*智能体:** + ```bash + copilot + > /plan Add input validation for book year in the book app + ``` + 这会调用 Plan 智能体创建一个逐步实现计划。 + +2. **查看我们的自定义智能体示例:** 定义智能体的指令很简单,查看我们提供的 [python-reviewer.agent.md](../.github/agents/python-reviewer.agent.md) 文件了解模式。 + +3. **理解核心概念:** 智能体就像咨询专家而不是综合医生。一个"前端智能体"会自动关注无障碍性和组件模式,你不需要每次提醒它,因为这已经在智能体的指令中指定了。 + + +## 内置智能体 + +**你在第 03 章开发工作流中已经用过一些内置智能体了!** +`/plan` 和 `/review` 实际上就是内置智能体。现在你知道背后发生了什么。以下是完整列表: + +| 智能体 | 调用方式 | 功能 | +|--------|---------|------| +| **Plan** | `/plan` 或 `Shift+Tab`(循环切换模式)| 在编码前创建逐步实现计划 | +| **Code-review** | `/review` | 对已暂存/未暂存的更改进行审查,提供聚焦、可操作的反馈 | +| **Init** | `/init` | 生成项目配置文件(指令、智能体)| +| **Explore** | *自动* | 当你让 Copilot 探索或分析代码库时内部使用 | +| **Task** | *自动* | 执行测试、构建、代码检查和依赖安装等命令 | + +
+ +**内置智能体实际演示** - 调用 Plan、Code-review、Explore 和 Task 的示例 + +```bash +copilot + +# 调用 Plan 智能体创建实现计划 +> /plan Add input validation for book year in the book app + +# 对你的更改调用 Code-review 智能体 +> /review + +# Explore 和 Task 智能体在相关时自动调用: +> Run the test suite # 使用 Task 智能体 + +> Explore how book data is loaded # 使用 Explore 智能体 +``` + +Task 智能体是如何工作的?它在后台管理和追踪进程,并以清晰整洁的格式汇报: + +| 结果 | 你看到的 | +|------|---------| +| ✅ **成功** | 简短摘要(如"All 247 tests passed"、"Build succeeded")| +| ❌ **失败** | 完整输出,包含堆栈跟踪、编译器错误和详细日志 | + + +> 📚 **官方文档**:[GitHub Copilot CLI 智能体](https://docs.github.com/copilot/how-tos/use-copilot-agents/use-copilot-cli#use-custom-agents) + +--- + +# 向 Copilot CLI 添加智能体 + +你可以直接定义自己的智能体,使其成为工作流的一部分!定义一次,随时调用! + +四个彩色 AI 机器人站在一起,每个都带有代表专门智能体能力的不同工具 + + +## 🗂️ 添加你的智能体 + +智能体文件是带有 `.agent.md` 扩展名的 Markdown 文件。它们有两个部分:YAML frontmatter(元数据)和 Markdown 指令。 + +> 💡 **不熟悉 YAML frontmatter?** 它是文件顶部的一小块设置,由 `---` 标记包围。YAML 就是 `key: value` 对。文件的其余部分是普通 Markdown。 + +这是一个最简单的智能体: + +```markdown +--- +name: my-reviewer +description: Code reviewer focused on bugs and security issues +--- + +# Code Reviewer + +You are a code reviewer focused on finding bugs and security issues. + +When reviewing code, always check for: +- SQL injection vulnerabilities +- Missing error handling +- Hardcoded secrets +``` + +> 💡 **必填 vs 可选**:`description` 字段是必填的。`name`、`tools` 和 `model` 等其他字段是可选的。 + + +## 智能体文件放在哪里 + +| 位置 | 范围 | 最适合 | +|------|------|--------| +| `.github/agents/` | 项目特定 | 具有项目约定的团队共享智能体 | +| `~/.copilot/agents/` | 全局(所有项目)| 你在任何地方使用的个人智能体 | + +**本项目在 [.github/agents/](../.github/agents/) 文件夹中包含示例智能体文件**。你可以编写自己的,或自定义已提供的文件。 + +
+📂 查看本课程中的示例智能体 + +| 文件 | 描述 | +|------|------| +| `hello-world.agent.md` | 最简单的示例——从这里开始 | +| `python-reviewer.agent.md` | Python 代码质量审查员 | +| `pytest-helper.agent.md` | Pytest 测试专家 | + +```bash +# 或复制一个到你的个人智能体文件夹(在每个项目中可用) +cp .github/agents/python-reviewer.agent.md ~/.copilot/agents/ +``` + +更多社区智能体,请参见 [github/awesome-copilot](https://github.com/github/awesome-copilot) + +
+ + +## 🚀 使用自定义智能体的两种方式 + +### 交互模式 +在交互模式中,使用 `/agent` 列出智能体,并选择一个智能体开始工作。 +选择一个智能体以继续你的对话。 + +```bash +copilot +> /agent +``` + +要切换到另一个智能体,或返回默认模式,再次使用 `/agent` 命令。 + +### 编程模式 + +直接使用智能体启动新会话。 + +```bash +copilot --agent python-reviewer +> Review @samples/book-app-project/books.py +``` + +> 💡 **切换智能体**:你随时可以使用 `/agent` 或 `--agent` 切换到不同的智能体。要返回标准 Copilot CLI 体验,使用 `/agent` 并选择**无智能体**。 + +--- + +# 深入了解智能体 + +机器人在工作台上被组装,周围是零件和工具,代表自定义智能体创建 + +> 💡 **本节是可选的。** 内置智能体(`/plan`、`/review`)对大多数工作流来说已经足够强大。当你需要在整个工作中一致应用的专业知识时,才需要创建自定义智能体。 + +以下每个主题都是独立的。**选择你感兴趣的——你不需要一次全部阅读。** + +| 我想... | 跳转到 | +|--------|--------| +| 了解为何智能体比通用提示词更好 | [专家 vs 通用](#specialist-vs-generic-see-the-difference) | +| 在一个功能上组合智能体 | [使用多个智能体](#working-with-multiple-agents) | +| 组织、命名和分享智能体 | [组织与分享智能体](#organizing--sharing-agents) | +| 设置始终在线的项目上下文 | [为 Copilot 配置项目](#configuring-your-project-for-copilot) | +| 查找 YAML 属性和工具 | [智能体文件参考](#agent-file-reference) | + +点击下方场景展开它。 + +--- + + +
+专家 vs 通用:看看区别——为何智能体比通用提示词产生更好的输出 + +## 专家 vs 通用:看看区别 + +这里是智能体证明其价值的地方。观察区别: + +### 不使用智能体(通用 Copilot) + +```bash +copilot + +> Add a function to search books by year range in the book app +``` + +**通用输出**: +```python +def search_by_year_range(books, start_year, end_year): + results = [] + for book in books: + if book['year'] >= start_year and book['year'] <= end_year: + results.append(book) + return results +``` + +基础。能用。但缺少很多。 + +--- + +### 使用 Python 审查员智能体 + +```bash +copilot + +> /agent +# 选择"python-reviewer" + +> Add a function to search books by year range in the book app +``` + +**专家输出**: +```python +from typing import List, Dict, Any + +def search_by_year_range( + books: List[Dict[str, Any]], + start_year: int, + end_year: int +) -> List[Dict[str, Any]]: + """ + Search for books within a specified year range. + + Args: + books: List of book dictionaries + start_year: Starting year (inclusive) + end_year: Ending year (inclusive) + + Returns: + List of books published within the year range + + Raises: + ValueError: If start_year is greater than end_year + TypeError: If year values are not integers + """ + if not isinstance(start_year, int) or not isinstance(end_year, int): + raise TypeError("Year values must be integers") + + if start_year > end_year: + raise ValueError(f"Start year ({start_year}) cannot be greater than end year ({end_year})") + + return [ + book for book in books + if isinstance(book.get('year'), int) + and start_year <= book['year'] <= end_year + ] +``` + +**python-reviewer 智能体自动包含了什么**: +- ✅ 所有参数和返回值的类型注解 +- ✅ 包含 Args/Returns/Raises 的全面 docstring +- ✅ 带有正确错误处理的输入验证 +- ✅ 更好性能的列表推导式 +- ✅ 边缘用例处理(缺失/无效的年份值) +- ✅ 符合 PEP 8 的格式 +- ✅ 防御式编程实践 + +**区别**:相同的提示词,产生了明显更好的输出。智能体带来了你会忘记要求的专业知识。 + +
+ +--- + + +
+使用多个智能体——组合专家、会话中途切换、智能体即工具 + +## 使用多个智能体 + +真正的力量在于专家在一个功能上协作。 + +### 示例:构建简单功能 + +```bash +copilot + +> I want to add a "search by year range" feature to the book app + +# 使用 python-reviewer 进行设计 +> /agent +# 选择"python-reviewer" + +> @samples/book-app-project/books.py Design a find_by_year_range method. What's the best approach? + +# 切换到 pytest-helper 进行测试设计 +> /agent +# 选择"pytest-helper" + +> @samples/book-app-project/tests/test_books.py Design test cases for a find_by_year_range method. +> What edge cases should we cover? + +# 综合两种设计 +> Create an implementation plan that includes the method implementation and comprehensive tests. +``` + +**核心洞察**:你是指挥专家的架构师。他们处理细节,你处理愿景。 + +
+🎬 看实际演示! + +![Python Reviewer Demo](images/python-reviewer-demo.gif) + +*演示输出仅供参考——你的模型、工具和响应将与此处显示的不同。* + +
+ +### 智能体即工具 + +当智能体被配置后,Copilot 也可以在复杂任务中将其作为工具调用。如果你要求一个全栈功能,Copilot 可能会自动将部分工作委派给适当的专家智能体。 + +
+ +--- + + +
+组织与分享智能体——命名、文件放置、指令文件和团队分享 + +## 组织与分享智能体 + +### 命名你的智能体 + +创建智能体文件时,名称很重要。这是你在 `/agent` 或 `--agent` 后输入的内容,也是你的团队成员在智能体列表中看到的内容。 + +| ✅ 好名称 | ❌ 避免使用 | +|---------|-----------| +| `frontend` | `my-agent` | +| `backend-api` | `agent1` | +| `security-reviewer` | `helper` | +| `react-specialist` | `code` | +| `python-backend` | `assistant` | + +**命名规范:** +- 使用小写加连字符:`my-agent-name.agent.md` +- 包含领域:`frontend`、`backend`、`devops`、`security` +- 需要时具体说明:`react-typescript` vs 简单的 `frontend` + +--- + +### 与团队分享 + +将智能体文件放在 `.github/agents/` 中,它们就会被版本控制。推送到仓库,每个团队成员都会自动获得它们。但智能体只是 Copilot 从项目读取的一种文件类型。它还支持**指令文件**,无需任何人运行 `/agent` 就会自动应用于每个会话。 + +这样理解:智能体是你召唤的专家,指令文件是始终有效的团队规则。 + +### 文件放在哪里 + +你已经知道两个主要位置(见上方[智能体文件放在哪里](#where-to-put-agent-files))。使用这个决策树来选择: + +智能体文件放置决策树:实验中 → 当前文件夹,团队使用 → .github/agents/,随处使用 → ~/.copilot/agents/ + +**从简单开始:** 在项目文件夹中创建一个 `*.agent.md` 文件。满意后再将其移到永久位置。 + +除了智能体文件,Copilot 还会自动读取**项目级指令文件**,无需 `/agent`。有关 `AGENTS.md`、`.instructions.md` 和 `/init` 的详情,请参阅下方的[为 Copilot 配置项目](#configuring-your-project-for-copilot)。 + +
+ +--- + + +
+为 Copilot 配置项目——AGENTS.md、指令文件和 /init 设置 + +## 为 Copilot 配置项目 + +智能体是你按需调用的专家。**项目配置文件**不同:Copilot 在每个会话中自动读取它们,以了解项目的约定、技术栈和规则。无需任何人运行 `/agent`;上下文始终对在仓库中工作的每个人有效。 + +### 使用 /init 快速设置 + +最快的开始方式是让 Copilot 为你生成配置文件: + +```bash +copilot +> /init +``` + +Copilot 会扫描你的项目并创建定制的指令文件。你可以之后编辑它们。 + +### 指令文件格式 + +| 文件 | 范围 | 说明 | +|------|------|------| +| `AGENTS.md` | 项目根目录或嵌套位置 | **跨平台标准**——与 Copilot 和其他 AI 助手兼容 | +| `.github/copilot-instructions.md` | 项目 | GitHub Copilot 特定 | +| `.github/instructions/*.instructions.md` | 项目 | 细粒度、特定主题的指令 | +| `CLAUDE.md`、`GEMINI.md` | 项目根目录 | 为兼容性而支持 | + +> 🎯 **刚刚开始?** 使用 `AGENTS.md` 作为项目指令。你可以根据需要之后探索其他格式。 + +### AGENTS.md + +`AGENTS.md` 是推荐格式。它是一个[开放标准](https://agents.md/),跨 Copilot 和其他 AI 编码工具兼容。将其放在仓库根目录,Copilot 会自动读取。本项目自己的 [AGENTS.md](../AGENTS.md) 是一个实际示例。 + +典型的 `AGENTS.md` 描述你的项目上下文、代码风格、安全要求和测试标准。使用 `/init` 生成一个,或按照我们示例文件中的模式自己编写。 + +### 自定义指令文件(.instructions.md) + +对于需要更细粒度控制的团队,将指令拆分为特定主题的文件。每个文件涵盖一个关注点并自动应用: + +``` +.github/ +└── instructions/ + ├── python-standards.instructions.md + ├── security-checklist.instructions.md + └── api-design.instructions.md +``` + +> 💡 **注意**:指令文件适用于任何语言。这个示例使用 Python 以匹配我们的课程项目,但你可以为 TypeScript、Go、Rust 或你团队使用的任何技术创建类似文件。 + +**查找社区指令文件**:浏览 [github/awesome-copilot](https://github.com/github/awesome-copilot) 获取涵盖 .NET、Angular、Azure、Python、Docker 等众多技术的预制指令文件。 + +### 禁用自定义指令 + +如果你需要 Copilot 忽略所有项目特定配置(用于调试或比较行为): + +```bash +copilot --no-custom-instructions +``` + +
+ +--- + + +
+智能体文件参考——YAML 属性、工具别名和完整示例 + +## 智能体文件参考 + +### 更完整的示例 + +你已经在上方看到了[最简智能体格式](#-add-your-agents)。这是一个使用 `tools` 属性的更全面的智能体。创建 `~/.copilot/agents/python-reviewer.agent.md`: + +```markdown +--- +name: python-reviewer +description: Python code quality specialist for reviewing Python projects +tools: ["read", "edit", "search", "execute"] +--- + +# Python Code Reviewer + +You are a Python specialist focused on code quality and best practices. + +**Your focus areas:** +- Code quality (PEP 8, type hints, docstrings) +- Performance optimization (list comprehensions, generators) +- Error handling (proper exception handling) +- Maintainability (DRY principles, clear naming) + +**Code style requirements:** +- Use Python 3.10+ features (dataclasses, type hints, pattern matching) +- Follow PEP 8 naming conventions +- Use context managers for file I/O +- All functions must have type hints and docstrings + +**When reviewing code, always check:** +- Missing type hints on function signatures +- Mutable default arguments +- Proper error handling (no bare except) +- Input validation completeness +``` + +### YAML 属性 + +| 属性 | 必填 | 描述 | +|------|------|------| +| `name` | 否 | 显示名称(默认为文件名)| +| `description` | **是** | 智能体的功能——帮助 Copilot 理解何时建议它 | +| `tools` | 否 | 允许的工具列表(省略 = 所有工具可用)。见下方工具别名。| +| `target` | 否 | 限制为仅 `vscode` 或 `github-copilot` | + +### 工具别名 + +在 `tools` 列表中使用以下名称: +- `read` - 读取文件内容 +- `edit` - 编辑文件 +- `search` - 搜索文件(grep/glob) +- `execute` - 运行 Shell 命令(也可用:`shell`、`Bash`) +- `agent` - 调用其他自定义智能体 + +> 📖 **官方文档**:[自定义智能体配置](https://docs.github.com/copilot/reference/custom-agents-configuration) +> +> ⚠️ **仅限 VS Code**:`model` 属性(用于选择 AI 模型)在 VS Code 中有效,但 GitHub Copilot CLI 不支持。你可以安全地将其包含在跨平台智能体文件中,GitHub Copilot CLI 会忽略它。 + +### 更多智能体模板 + +> 💡 **初学者注意**:以下示例是模板。**将具体技术替换为你项目中使用的技术。** 重要的是智能体的*结构*,而不是提到的具体技术。 + +本项目在 [.github/agents/](../.github/agents/) 文件夹中包含实际示例: +- [hello-world.agent.md](../.github/agents/hello-world.agent.md) - 最简示例,从这里开始 +- [python-reviewer.agent.md](../.github/agents/python-reviewer.agent.md) - Python 代码质量审查员 +- [pytest-helper.agent.md](../.github/agents/pytest-helper.agent.md) - Pytest 测试专家 + +社区智能体请参见 [github/awesome-copilot](https://github.com/github/awesome-copilot)。 + +
+ +--- + +# 动手练习 + +温馨的桌面环境,显示器显示代码,台灯、咖啡杯和耳机,准备好动手实践 + +创建你自己的智能体并看它们在实际中运行。 + +--- + +## ▶️ 自己试试 + +```bash + +# 创建智能体目录(如果不存在) +mkdir -p .github/agents + +# 创建代码审查员智能体 +cat > .github/agents/reviewer.agent.md << 'EOF' +--- +name: reviewer +description: Senior code reviewer focused on security and best practices +--- + +# Code Reviewer Agent + +You are a senior code reviewer focused on code quality. + +**Review priorities:** +1. Security vulnerabilities +2. Performance issues +3. Maintainability concerns +4. Best practice violations + +**Output format:** +Provide issues as a numbered list with severity tags: +[CRITICAL], [HIGH], [MEDIUM], [LOW] +EOF + +# 创建文档智能体 +cat > .github/agents/documentor.agent.md << 'EOF' +--- +name: documentor +description: Technical writer for clear and complete documentation +--- + +# Documentation Agent + +You are a technical writer who creates clear documentation. + +**Documentation standards:** +- Start with a one-sentence summary +- Include usage examples +- Document parameters and return values +- Note any gotchas or limitations +EOF + +# 现在使用它们 +copilot --agent reviewer +> Review @samples/book-app-project/books.py + +# 或切换智能体 +copilot +> /agent +# 选择"documentor" +> Document @samples/book-app-project/books.py +``` + +--- + +## 📝 作业 + +### 主要挑战:构建专门智能体团队 + +动手示例创建了 `reviewer` 和 `documentor` 智能体。现在为不同任务练习创建和使用智能体——改进书籍应用中的数据验证: + +1. 创建 3 个智能体文件(`.agent.md`),每个智能体一个,放在 `.github/agents/` 中 +2. 你的智能体: + - **data-validator**:检查 `data.json` 中缺失或格式错误的数据(空作者、year=0、缺失字段) + - **error-handler**:审查 Python 代码中不一致的错误处理,并建议统一的方法 + - **doc-writer**:生成或更新 docstring 和 README 内容 +3. 在书籍应用上使用每个智能体: + - `data-validator` → 审计 `@samples/book-app-project/data.json` + - `error-handler` → 审查 `@samples/book-app-project/books.py` 和 `@samples/book-app-project/utils.py` + - `doc-writer` → 为 `@samples/book-app-project/books.py` 添加 docstring +4. 协作:使用 `error-handler` 识别错误处理差距,然后用 `doc-writer` 记录改进的方法 + +**成功标准**:你有 3 个能产生一致、高质量输出的可用智能体,并且可以用 `/agent` 在它们之间切换。 + +
+💡 提示(点击展开) + +**起始模板**:在 `.github/agents/` 中为每个智能体创建一个文件: + +`data-validator.agent.md`: +```markdown +--- +description: Analyzes JSON data files for missing or malformed entries +--- + +You analyze JSON data files for missing or malformed entries. + +**Focus areas:** +- Empty or missing author fields +- Invalid years (year=0, future years, negative years) +- Missing required fields (title, author, year, read) +- Duplicate entries +``` + +`error-handler.agent.md`: +```markdown +--- +description: Reviews Python code for error handling consistency +--- + +You review Python code for error handling consistency. + +**Standards:** +- No bare except clauses +- Use custom exceptions where appropriate +- All file operations use context managers +- Consistent return types for success/failure +``` + +`doc-writer.agent.md`: +```markdown +--- +description: Technical writer for clear Python documentation +--- + +You are a technical writer who creates clear Python documentation. + +**Standards:** +- Google-style docstrings +- Include parameter types and return values +- Add usage examples for public methods +- Note any exceptions raised +``` + +**测试你的智能体:** + +> 💡 **注意:** 你的本地副本应该已经有 `samples/book-app-project/data.json`。如果缺失,从源仓库下载原始版本: +> [data.json](https://github.com/github/copilot-cli-for-beginners/blob/main/samples/book-app-project/data.json) + +```bash +copilot +> /agent +# 从列表中选择"data-validator" +> @samples/book-app-project/data.json Check for books with empty author fields or invalid years +``` + +**提示:** YAML frontmatter 中的 `description` 字段是智能体能够工作所必需的。 + +
+ +### 附加挑战:指令库 + +你已经构建了按需调用的智能体。现在尝试另一面:**指令文件**,Copilot 在每个会话中自动读取,无需 `/agent`。 + +创建一个 `.github/instructions/` 文件夹,至少包含 3 个指令文件: +- `python-style.instructions.md`:强制执行 PEP 8 和类型注解约定 +- `test-standards.instructions.md`:在测试文件中强制执行 pytest 约定 +- `data-quality.instructions.md`:验证 JSON 数据条目 + +在书籍应用代码上测试每个指令文件。 + +--- + +
+🔧 常见错误与故障排除(点击展开) + +### 常见错误 + +| 错误 | 发生了什么 | 解决方法 | +|------|-----------|---------| +| 智能体 frontmatter 中缺少 `description` | 智能体不会加载或无法被发现 | 始终在 YAML frontmatter 中包含 `description:` | +| 智能体文件位置错误 | 尝试使用时找不到智能体 | 放在 `~/.copilot/agents/`(个人)或 `.github/agents/`(项目)| +| 使用 `.md` 而不是 `.agent.md` | 文件可能无法被识别为智能体 | 将文件命名为 `python-reviewer.agent.md` 这样的形式 | +| 智能体提示词过长 | 可能达到 30,000 字符限制 | 保持智能体定义聚焦;对于详细指令使用技能 | + +### 故障排除 + +**找不到智能体** — 确认智能体文件存在于以下位置之一: +- `~/.copilot/agents/` +- `.github/agents/` + +列出可用智能体: + +```bash +copilot +> /agent +# 显示所有可用智能体 +``` + +**智能体不遵循指令** — 在提示词中明确说明,并在智能体定义中添加更多细节: +- 带版本号的具体框架/库 +- 团队约定 +- 示例代码模式 + +**自定义指令未加载** — 在项目中运行 `/init` 设置项目特定指令: + +```bash +copilot +> /init +``` + +或检查它们是否被禁用: +```bash +# 如果你想加载它们,不要使用 --no-custom-instructions +copilot # 这会默认加载自定义指令 +``` + +
+ +--- + +## 🔑 关键要点 + +1. **内置智能体**(`/plan`、`/review`)对大多数工作流来说已经足够强大 +2. **自定义智能体**(`.agent.md` 文件)让你为特定工作流创建专家 +3. **指令文件**(`AGENTS.md`、`.instructions.md`)自动为每个会话应用上下文 +4. **专家胜通用**:相同提示词,通过智能体处理能得到更好的结果 +5. **使用 `/agent` 切换**:可以在一个会话中组合多个专家 + +> 📋 **快速参考**:查看 [GitHub Copilot CLI 命令参考](https://docs.github.com/en/copilot/reference/cli-command-reference) 获取完整的命令和快捷键列表。 + +--- + +**[← 返回第 03 章](../03-development-workflows/README.zh-CN.md)** | **[继续第 05 章 →](../05-skills/README.zh-CN.md)** diff --git a/05-skills/README.zh-CN.md b/05-skills/README.zh-CN.md new file mode 100644 index 0000000..61c7a42 --- /dev/null +++ b/05-skills/README.zh-CN.md @@ -0,0 +1,864 @@ +![第 05 章:技能系统](images/chapter-header.png) + +> **如果 Copilot 能自动应用团队的最佳实践,而不用你每次都重新解释一遍,会怎样?** + +在本章中,你将学习 Agent Skills:它们是一组按文件夹组织的指令,Copilot 会在与你的任务相关时自动加载。智能体改变的是 Copilot *如何*思考,而技能教会 Copilot *如何按特定方式完成任务*。你将创建一个安全审计技能,让 Copilot 在你询问安全问题时自动应用;你还会构建团队统一的审查标准,以确保代码质量保持一致,并了解技能如何在 Copilot CLI、VS Code 和 Copilot 编码智能体之间协同工作。 + + +## 🎯 学习目标 + +完成本章后,你将能够: + +- 理解智能体技能的工作原理及使用时机 +- 使用 SKILL.md 文件创建自定义技能 +- 使用来自共享仓库的社区技能 +- 知道何时使用技能 vs 智能体 vs MCP + +> ⏱️ **预计用时**:约 55 分钟(阅读 20 分钟 + 动手 35 分钟) + +--- + +## 🧩 现实类比:动力工具 + +通用电钻很有用,但专用配件才是它的威力所在。 +动力工具——技能扩展 Copilot 的能力 + + +技能的工作方式相同。就像为不同工作换钻头一样,你可以为不同任务向 Copilot 添加技能: + +| 技能配件 | 用途 | +|---------|------| +| `commit` | 生成一致的提交信息 | +| `security-audit` | 检查 OWASP 漏洞 | +| `generate-tests` | 创建全面的 pytest 测试 | +| `code-checklist` | 应用团队代码质量标准 | + + + +*技能是扩展 Copilot 能力的专用配件* + +--- + +# 技能的工作原理 + +发光的 RPG 风格技能图标通过光迹连接在星空背景上,代表 Copilot 技能 + +了解技能是什么,为何重要,以及它们与智能体和 MCP 的区别。 + +--- + +## *技能新手?* 从这里开始! + +1. **查看哪些技能已经可用:** + ```bash + copilot + > /skills list + ``` + 这会显示 Copilot 在项目和个人文件夹中找到的所有技能。 + +2. **查看真实的技能文件:** 查看我们提供的 [code-checklist SKILL.md](../.github/skills/code-checklist/SKILL.md) 以了解模式。它只是 YAML frontmatter 加上 Markdown 指令。 + +3. **理解核心概念:** 技能是特定任务的指令,当你的提示词与技能描述匹配时,Copilot *自动*加载它们。你不需要激活它们,只需自然地提问即可。 + + +## 理解技能 + +智能体技能是包含指令、脚本和资源的文件夹,Copilot **在与任务相关时自动加载**。Copilot 读取你的提示词,检查是否有技能匹配,并自动应用相关指令。 + +```bash +copilot + +> Check books.py against our quality checklist +# Copilot 检测到这与你的"code-checklist"技能匹配 +# 并自动应用其 Python 质量清单 + +> Generate tests for the BookCollection class +# Copilot 加载你的"pytest-gen"技能 +# 并应用你首选的测试结构 + +> What are the code quality issues in this file? +# Copilot 加载你的"code-checklist"技能 +# 并根据团队标准进行检查 +``` + +> 💡 **关键洞察**:技能根据你的提示词与技能描述的匹配**自动触发**。自然地提问,Copilot 在后台自动应用相关技能。当然,你也可以直接调用技能,稍后会介绍。 + +> 🧰 **即用模板**:查看 [.github/skills](../.github/skills/) 文件夹获取可直接复制使用的技能。 + +### 直接斜杠命令调用 + +虽然自动触发是技能工作的主要方式,你也可以使用技能名称作为斜杠命令**直接调用技能**: + +```bash +> /generate-tests Create tests for the user authentication module + +> /code-checklist Check books.py for code quality issues + +> /security-audit Check the API endpoints for vulnerabilities +``` + +这让你在想要确保使用特定技能时拥有明确的控制权。 + +> 📝 **技能 vs 智能体的调用方式**:不要混淆技能调用与智能体调用: +> - **技能**:`/技能名称 <提示词>`,如 `/code-checklist Check this file` +> - **智能体**:`/agent`(从列表中选择)或 `copilot --agent <名称>`(命令行) +> +> 如果你同时有一个叫"code-reviewer"的技能和智能体,输入 `/code-reviewer` 会调用**技能**,而不是智能体。 + +### 如何知道技能被使用了? + +你可以直接问 Copilot: + +```bash +> What skills did you use for that response? + +> What skills do you have available for security reviews? +``` + +### 技能 vs 智能体 vs MCP + +技能只是 GitHub Copilot 可扩展性模型的一部分。以下是它们与智能体和 MCP 服务器的比较。 + +> *先别担心 MCP,我们将在[第 06 章](../06-mcp-servers/README.zh-CN.md)中介绍。这里包含它只是为了让你了解技能在整体图景中的位置。* + +比较图,显示智能体、技能和 MCP 服务器之间的差异以及它们如何组合到工作流中 + +| 功能 | 作用 | 使用时机 | +|------|------|---------| +| **智能体** | 改变 AI 的思考方式 | 跨多个任务需要专业知识 | +| **技能** | 提供特定任务的指令 | 有详细步骤的特定、可重复任务 | +| **MCP** | 连接外部服务 | 需要来自 API 的实时数据 | + +将智能体用于广泛的专业知识,将技能用于特定任务的指令,将 MCP 用于外部数据。智能体可以在对话中使用一个或多个技能。例如,当你让智能体检查代码时,它可能会自动应用 `security-audit` 技能和 `code-checklist` 技能。 + +> 📚 **了解更多**:查看官方[关于智能体技能](https://docs.github.com/copilot/concepts/agents/about-agent-skills)文档,获取技能格式和最佳实践的完整参考。 + +--- + +## 从手动提示词到自动专业知识 + +在深入了解如何创建技能之前,先看看*为什么*值得学习它们。一旦你看到一致性的提升,"如何"就会更有意义。 + +### 没有技能:不一致的审查 + +每次代码审查,你可能都会遗漏一些东西: + +```bash +copilot + +> Review this code for issues +# 通用审查——可能遗漏团队的具体关注点 +``` + +或者每次都要写一个很长的提示词: + +```bash +> Review this code checking for bare except clauses, missing type hints, +> mutable default arguments, missing context managers for file I/O, +> functions over 50 lines, print statements in production code... +``` + +耗时:**超过 30 秒**来输入。一致性:**因记忆力而异**。 + +### 有了技能:自动最佳实践 + +安装了 `code-checklist` 技能后,只需自然提问: + +```bash +copilot + +> Check the book collection code for quality issues +``` + +**后台发生了什么**: +1. Copilot 在提示词中看到"code quality"和"issues" +2. 检查技能描述,发现你的 `code-checklist` 技能匹配 +3. 自动加载团队质量清单 +4. 应用所有检查,无需你列出它们 + +技能自动触发原理——4 步流程,展示 Copilot 如何自动将提示词与正确技能匹配 + +*自然地提问,Copilot 将提示词与正确技能匹配并自动应用。* + +**输出**: +``` +## Code Checklist: books.py + +### Code Quality +- [PASS] All functions have type hints +- [PASS] No bare except clauses +- [PASS] No mutable default arguments +- [PASS] Context managers used for file I/O +- [PASS] Functions are under 50 lines +- [PASS] Variable and function names follow PEP 8 + +### Input Validation +- [FAIL] User input is not validated - add_book() accepts any year value +- [FAIL] Edge cases not fully handled - empty strings accepted for title/author +- [PASS] Error messages are clear and helpful + +### Testing +- [FAIL] No corresponding pytest tests found + +### Summary +3 items need attention before merge +``` + +**区别**:你的团队标准每次都被自动应用,无需把它们都输出来。 + +--- + +
+🎬 看实际演示! + +![技能触发演示](images/skill-trigger-demo.gif) + +*演示输出因情况而异。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +## 规模化一致性:团队 PR 审查技能 + +想象你的团队有一个 10 点的 PR 清单。没有技能,每个开发者都必须记住所有 10 个点,而且总有人会忘记其中某一点。有了 `pr-review` 技能,整个团队都能获得一致的审查: + +```bash +copilot + +> Can you review this PR? +``` + +Copilot 自动加载团队的 `pr-review` 技能并检查所有 10 个点: + +``` +PR Review: feature/user-auth + +## Security ✅ +- No hardcoded secrets +- Input validation present +- No bare except clauses + +## Code Quality ⚠️ +- [WARN] print statement on line 45 - remove before merge +- [WARN] TODO on line 78 missing issue reference +- [WARN] Missing type hints on public functions + +## Testing ✅ +- New tests added +- Edge cases covered + +## Documentation ❌ +- [FAIL] Breaking change not documented in CHANGELOG +- [FAIL] API changes need OpenAPI spec update +``` + +**技能的力量**:每个团队成员都自动应用相同的标准。新员工不需要记住清单,因为技能会处理这一切。 + +--- + +# 创建自定义技能 + +人手和机械手共同搭建发光积木墙,代表技能的创建和管理 + +从 SKILL.md 文件构建你自己的技能。 + +--- + +## 技能存放位置 + +技能存储在 `.github/skills/`(项目特定)或 `~/.copilot/skills/`(用户级别)中。 + +### Copilot 如何找到技能 + +Copilot 会自动扫描以下位置寻找技能: + +| 位置 | 范围 | +|------|------| +| `.github/skills/` | 项目特定(通过 git 与团队共享)| +| `~/.copilot/skills/` | 用户特定(你的个人技能)| + +### 技能结构 + +每个技能都存在于自己的文件夹中,包含一个 `SKILL.md` 文件。你也可以选择性地包含脚本、示例或其他资源: + +``` +.github/skills/ +└── my-skill/ + ├── SKILL.md # 必填:技能定义和指令 + ├── examples/ # 可选:Copilot 可以参考的示例文件 + │ └── sample.py + └── scripts/ # 可选:技能可以使用的脚本 + └── validate.sh +``` + +> 💡 **提示**:目录名称应与 SKILL.md frontmatter 中的 `name` 匹配(小写加连字符)。 + +### SKILL.md 格式 + +技能使用带有 YAML frontmatter 的简单 Markdown 格式: + +```markdown +--- +name: code-checklist +description: Comprehensive code quality checklist with security, performance, and maintainability checks +license: MIT +--- + +# Code Checklist + +When checking code, look for: + +## Security +- SQL injection vulnerabilities +- XSS vulnerabilities +- Authentication/authorization issues +- Sensitive data exposure + +## Performance +- N+1 query problems (running one query per item instead of one query for all items) +- Unnecessary loops or computations +- Memory leaks +- Blocking operations + +## Maintainability +- Function length (flag functions > 50 lines) +- Code duplication +- Missing error handling +- Unclear naming + +## Output Format +Provide issues as a numbered list with severity: +- [CRITICAL] - Must fix before merge +- [HIGH] - Should fix before merge +- [MEDIUM] - Should address soon +- [LOW] - Nice to have +``` + +**YAML 属性:** + +| 属性 | 必填 | 描述 | +|------|------|------| +| `name` | **是** | 唯一标识符(小写,空格用连字符替代)| +| `description` | **是** | 技能的作用以及 Copilot 何时应使用它 | +| `license` | 否 | 适用于此技能的许可证 | + +> 📖 **官方文档**:[关于智能体技能](https://docs.github.com/copilot/concepts/agents/about-agent-skills) + +### 创建你的第一个技能 + +让我们构建一个检查 OWASP Top 10 漏洞的安全审计技能: + +```bash +# 创建技能目录 +mkdir -p .github/skills/security-audit + +# 创建 SKILL.md 文件 +cat > .github/skills/security-audit/SKILL.md << 'EOF' +--- +name: security-audit +description: Security-focused code review checking OWASP (Open Web Application Security Project) Top 10 vulnerabilities +--- + +# Security Audit + +Perform a security audit checking for: + +## Injection Vulnerabilities +- SQL injection (string concatenation in queries) +- Command injection (unsanitized shell commands) +- LDAP injection +- XPath injection + +## Authentication Issues +- Hardcoded credentials +- Weak password requirements +- Missing rate limiting +- Session management flaws + +## Sensitive Data +- Plaintext passwords +- API keys in code +- Logging sensitive information +- Missing encryption + +## Access Control +- Missing authorization checks +- Insecure direct object references +- Path traversal vulnerabilities + +## Output +For each issue found, provide: +1. File and line number +2. Vulnerability type +3. Severity (CRITICAL/HIGH/MEDIUM/LOW) +4. Recommended fix +EOF + +# 测试你的技能(技能根据提示词自动加载) +copilot + +> @samples/book-app-project/ Check this code for security vulnerabilities +# Copilot 检测到"security vulnerabilities"与你的技能匹配 +# 并自动应用其 OWASP 清单 +``` + +**预期输出**(你的结果会有所不同): + +``` +Security Audit: book-app-project + +[HIGH] Hardcoded file path (book_app.py, line 12) + File path is hardcoded rather than configurable + Fix: Use environment variable or config file + +[MEDIUM] No input validation (book_app.py, line 34) + User input passed directly to function without sanitization + Fix: Add input validation before processing + +✅ No SQL injection found +✅ No hardcoded credentials found +``` + +--- + +## 编写好的技能描述 + +SKILL.md 中的 `description` 字段至关重要!这是 Copilot 决定是否加载你的技能的依据: + +```markdown +--- +name: security-audit +description: Use for security reviews, vulnerability scanning, + checking for SQL injection, XSS, authentication issues, + OWASP Top 10 vulnerabilities, and security best practices +--- +``` + +> 💡 **提示**:包含与你自然提问方式匹配的关键词。如果你说"security review",就在描述中包含"security review"。 + +### 将技能与智能体结合 + +技能和智能体可以协同工作。智能体提供专业知识,技能提供具体指令: + +```bash +# 使用 code-reviewer 智能体开始 +copilot --agent code-reviewer + +> Check the book app for quality issues +# code-reviewer 智能体的专业知识与 +# 你的 code-checklist 技能的清单相结合 +``` + +--- + +# 管理与分享技能 + +发现已安装的技能,寻找社区技能,并分享你自己的技能。 + +管理与分享技能——展示 CLI 技能的发现、使用、创建和分享循环 + +--- + +## 使用 `/skills` 命令管理技能 + +使用 `/skills` 命令管理你安装的技能: + +| 命令 | 作用 | +|------|------| +| `/skills list` | 显示所有已安装的技能 | +| `/skills info <名称>` | 获取特定技能的详细信息 | +| `/skills add <名称>` | 启用一个技能(来自仓库或市场)| +| `/skills remove <名称>` | 禁用或卸载一个技能 | +| `/skills reload` | 编辑 SKILL.md 文件后重新加载技能 | + +> 💡 **记住**:你不需要为每个提示词"激活"技能。一旦安装,当提示词与描述匹配时技能会**自动触发**。这些命令是用来管理哪些技能可用,而不是用来使用它们的。 + +### 示例:查看你的技能 + +```bash +copilot + +> /skills list + +Available skills: +- security-audit: Security-focused code review checking OWASP Top 10 +- generate-tests: Generate comprehensive unit tests with edge cases +- code-checklist: Team code quality checklist +... + +> /skills info security-audit + +Skill: security-audit +Source: Project +Location: .github/skills/security-audit/SKILL.md +Description: Security-focused code review checking OWASP Top 10 vulnerabilities +``` + +--- + +
+看实际演示! + +![列出技能演示](images/list-skills-demo.gif) + +*演示输出因情况而异。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +### 何时使用 `/skills reload` + +创建或编辑技能的 SKILL.md 文件后,运行 `/skills reload` 无需重启 Copilot 即可获取更改: + +```bash +# 编辑你的技能文件 +# 然后在 Copilot 中: +> /skills reload +Skills reloaded successfully. +``` + +> 💡 **值得了解**:即使使用 `/compact` 压缩对话历史后,技能仍然有效。无需在压缩后重新加载。 + +--- + +## 查找和使用社区技能 + +### 使用插件安装技能 + +> 💡 **什么是插件?** 插件是可安装的包,可以将技能、智能体和 MCP 服务器配置捆绑在一起。把它们看作 Copilot CLI 的"应用商店"扩展。 + +`/plugin` 命令允许你浏览和安装这些包: + +```bash +copilot + +> /plugin list +# 显示已安装的插件 + +> /plugin marketplace +# 浏览可用插件 + +> /plugin install <插件名称> +# 从市场安装插件 +``` + +插件可以将多个功能捆绑在一起——一个插件可能包含协同工作的相关技能、智能体和 MCP 服务器配置。 + +### 社区技能仓库 + +预制技能也可从社区仓库获取: + +- **[Awesome Copilot](https://github.com/github/awesome-copilot)** - 官方 GitHub Copilot 资源,包括技能文档和示例 + +### 手动安装社区技能 + +如果你在 GitHub 仓库中找到了技能,将其文件夹复制到你的技能目录: + +```bash +# 克隆 awesome-copilot 仓库 +git clone https://github.com/github/awesome-copilot.git /tmp/awesome-copilot + +# 将特定技能复制到你的项目 +cp -r /tmp/awesome-copilot/skills/code-checklist .github/skills/ + +# 或用于个人跨项目使用 +cp -r /tmp/awesome-copilot/skills/code-checklist ~/.copilot/skills/ +``` + +> ⚠️ **安装前先审查**:在将技能的 `SKILL.md` 复制到项目之前,始终仔细阅读它。技能控制 Copilot 的行为,恶意技能可能指示它运行有害命令或以意外方式修改代码。 + +--- + +# 动手练习 + +温馨的桌面环境,显示器显示代码,台灯、咖啡杯和耳机,准备好动手实践 + +通过构建和测试你自己的技能来应用所学知识。 + +--- + +## ▶️ 自己试试 + +### 构建更多技能 + +以下是两个展示不同模式的技能。按照上方"创建你的第一个技能"中的相同 `mkdir` + `cat` 工作流操作,或将技能粘贴到正确位置。更多示例在 [.github/skills](../.github/skills) 中。 + +### pytest 测试生成技能 + +确保代码库中一致的 pytest 结构的技能: + +```bash +mkdir -p .github/skills/pytest-gen + +cat > .github/skills/pytest-gen/SKILL.md << 'EOF' +--- +name: pytest-gen +description: Generate comprehensive pytest tests with fixtures and edge cases +--- + +# pytest Test Generation + +Generate pytest tests that include: + +## Test Structure +- Use pytest conventions (test_ prefix) +- One assertion per test when possible +- Clear test names describing expected behavior +- Use fixtures for setup/teardown + +## Coverage +- Happy path scenarios +- Edge cases: None, empty strings, empty lists +- Boundary values +- Error scenarios with pytest.raises() + +## Fixtures +- Use @pytest.fixture for reusable test data +- Use tmpdir/tmp_path for file operations +- Mock external dependencies with pytest-mock + +## Output +Provide complete, runnable test file with proper imports. +EOF +``` + +### 团队 PR 审查技能 + +在团队中强制执行一致 PR 审查标准的技能: + +```bash +mkdir -p .github/skills/pr-review + +cat > .github/skills/pr-review/SKILL.md << 'EOF' +--- +name: pr-review +description: Team-standard PR review checklist +--- + +# PR Review + +Review code changes against team standards: + +## Security Checklist +- [ ] No hardcoded secrets or API keys +- [ ] Input validation on all user data +- [ ] No bare except clauses +- [ ] No sensitive data in logs + +## Code Quality +- [ ] Functions under 50 lines +- [ ] No print statements in production code +- [ ] Type hints on public functions +- [ ] Context managers for file I/O +- [ ] No TODOs without issue references + +## Testing +- [ ] New code has tests +- [ ] Edge cases covered +- [ ] No skipped tests without explanation + +## Documentation +- [ ] API changes documented +- [ ] Breaking changes noted +- [ ] README updated if needed + +## Output Format +Provide results as: +- ✅ PASS: Items that look good +- ⚠️ WARN: Items that could be improved +- ❌ FAIL: Items that must be fixed before merge +EOF +``` + +### 进一步探索 + +1. **技能创建挑战**:创建一个 `quick-review` 技能,执行 3 点清单: + - Bare except 子句 + - 缺失的类型注解 + - 不清晰的变量名 + + 通过提问来测试:「Do a quick review of books.py」 + +2. **技能对比**:计时手动编写详细安全审查提示词需要多长时间。然后只需提问「Check for security issues in this file」,让你的 security-audit 技能自动加载。技能帮你节省了多少时间? + +3. **团队技能挑战**:思考团队的代码审查清单。能将它编码为技能吗?写下技能应该始终检查的 3 件事。 + +**自我检验**:当你能解释 `description` 字段为何重要(这是 Copilot 决定是否加载你的技能的方式)时,你就理解了技能。 + +--- + +## 📝 作业 + +### 主要挑战:构建书籍摘要技能 + +上面的示例创建了 `pytest-gen` 和 `pr-review` 技能。现在练习创建一种完全不同类型的技能:用于从数据生成格式化输出的技能。 + +1. 列出当前技能:运行 Copilot 并传入 `/skills list`。你也可以使用 `ls .github/skills/` 查看项目技能,或 `ls ~/.copilot/skills/` 查看个人技能。 +2. 在 `.github/skills/book-summary/SKILL.md` 创建一个 `book-summary` 技能,生成书籍集合的格式化 Markdown 摘要 +3. 你的技能应该有: + - 清晰的名称和描述(描述对匹配至关重要!) + - 具体的格式规则(例如,带有标题、作者、年份、阅读状态的 Markdown 表格) + - 输出约定(例如,已读状态使用 ✅/❌,按年份排序) +4. 测试技能:`@samples/book-app-project/data.json Summarize the books in this collection` +5. 通过检查 `/skills list` 验证技能自动触发 +6. 尝试直接调用:`/book-summary Summarize the books in this collection` + +**成功标准**:你有一个可用的 `book-summary` 技能,Copilot 在你询问书籍集合时会自动应用。 + +
+💡 提示(点击展开) + +**起始模板**:创建 `.github/skills/book-summary/SKILL.md`: + +```markdown +--- +name: book-summary +description: Generate a formatted markdown summary of a book collection +--- + +# Book Summary Generator + +Generate a summary of the book collection following these rules: + +1. Output a markdown table with columns: Title, Author, Year, Status +2. Use ✅ for read books and ❌ for unread books +3. Sort by year (oldest first) +4. Include a total count at the bottom +5. Flag any data issues (missing authors, invalid years) + +Example: +| Title | Author | Year | Status | +|-------|--------|------|--------| +| 1984 | George Orwell | 1949 | ✅ | +| Dune | Frank Herbert | 1965 | ❌ | + +**Total: 2 books (1 read, 1 unread)** +``` + +**测试:** +```bash +copilot +> @samples/book-app-project/data.json Summarize the books in this collection +# 技能应基于描述匹配自动触发 +``` + +**如果未触发:** 尝试 `/skills reload` 然后再次提问。 + +
+ +### 附加挑战:提交信息技能 + +1. 创建一个 `commit-message` 技能,生成格式一致的约定式提交信息 +2. 通过暂存一个更改并提问来测试:「Generate a commit message for my staged changes」 +3. 记录你的技能并在 GitHub 上以 `copilot-skill` 主题分享 + +--- + +
+🔧 常见错误与故障排除(点击展开) + +### 常见错误 + +| 错误 | 发生了什么 | 解决方法 | +|------|-----------|---------| +| 文件名不是 `SKILL.md` | 技能不会被识别 | 文件必须完全命名为 `SKILL.md` | +| `description` 字段模糊 | 技能从不自动加载 | 描述是*主要*发现机制,使用具体的触发词 | +| frontmatter 中缺少 `name` 或 `description` | 技能加载失败 | 在 YAML frontmatter 中添加这两个字段 | +| 文件夹位置错误 | 找不到技能 | 使用 `.github/skills/技能名称/`(项目)或 `~/.copilot/skills/技能名称/`(个人)| + +### 故障排除 + +**技能未被使用** - 如果 Copilot 在预期情况下未使用你的技能: + +1. **检查描述**:它是否与你的提问方式匹配? + ```markdown + # 坏:太模糊 + description: Reviews code + + # 好:包含触发词 + description: Use for code reviews, checking code quality, + finding bugs, security issues, and best practice violations + ``` + +2. **验证文件位置**: + ```bash + # 项目技能 + ls .github/skills/ + + # 用户技能 + ls ~/.copilot/skills/ + ``` + +3. **检查 SKILL.md 格式**:frontmatter 是必需的: + ```markdown + --- + name: skill-name + description: What the skill does and when to use it + --- + + # Instructions here + ``` + +**技能未出现** - 验证文件夹结构: +``` +.github/skills/ +└── my-skill/ # 文件夹名称 + └── SKILL.md # 必须完全是 SKILL.md(区分大小写) +``` + +创建或编辑技能后运行 `/skills reload` 确保获取更改。 + +**测试技能是否加载** - 直接问 Copilot: +```bash +> What skills do you have available for checking code quality? +# Copilot 将描述它发现的相关技能 +``` + +**如何知道技能是否真正在工作?** + +1. **检查输出格式**:如果技能指定了输出格式(如 `[CRITICAL]` 标签),在响应中查找它 +2. **直接询问**:获得响应后,问「Did you use any skills for that?」 +3. **对比有无技能**:用 `--no-custom-instructions` 尝试相同提示词以查看区别: + ```bash + # 使用技能 + copilot --allow-all -p "Review @file.py for security issues" + + # 不使用技能(基线对比) + copilot --allow-all -p "Review @file.py for security issues" --no-custom-instructions + ``` +4. **检查特定检查**:如果技能包含特定检查(如「functions over 50 lines」),看看这些是否出现在输出中 + +
+ +--- + +# 总结 + +## 🔑 关键要点 + +1. **技能是自动的**:当提示词与技能描述匹配时,Copilot 会加载它们 +2. **直接调用**:你也可以使用 `/技能名称` 作为斜杠命令直接调用技能 +3. **SKILL.md 格式**:YAML frontmatter(name、description、可选的 license)加上 Markdown 指令 +4. **位置很重要**:`.github/skills/` 用于项目/团队共享,`~/.copilot/skills/` 用于个人使用 +5. **描述是关键**:编写与你自然提问方式匹配的描述 + +> 📋 **快速参考**:查看 [GitHub Copilot CLI 命令参考](https://docs.github.com/en/copilot/reference/cli-command-reference) 获取完整的命令和快捷键列表。 + +--- + +## ➡️ 下一步 + +技能通过自动加载指令扩展 Copilot 的能力。但如果需要连接到外部服务呢?这就是 MCP 的用武之地。 + +在**[第 06 章:MCP 服务器](../06-mcp-servers/README.zh-CN.md)**中,你将学习: + +- 什么是 MCP(模型上下文协议) +- 连接到 GitHub、文件系统和文档服务 +- 配置 MCP 服务器 +- 多服务器工作流 + +--- + +**[← 返回第 04 章](../04-agents-custom-instructions/README.zh-CN.md)** | **[继续第 06 章 →](../06-mcp-servers/README.zh-CN.md)** diff --git a/06-mcp-servers/README.zh-CN.md b/06-mcp-servers/README.zh-CN.md new file mode 100644 index 0000000..db15126 --- /dev/null +++ b/06-mcp-servers/README.zh-CN.md @@ -0,0 +1,937 @@ +![第 06 章:MCP 服务器](images/chapter-header.png) + +> **如果 Copilot 能直接从终端读取 GitHub Issues、检查数据库,还能创建 PR……那会怎样?** + +到目前为止,Copilot 只能使用你直接提供的内容:用 `@` 引用的文件、对话历史以及它自身的训练数据。但如果它能主动检查你的 GitHub 仓库、浏览项目文件,或查找某个库的最新文档呢? + +这正是 MCP(模型上下文协议)的作用。它将 Copilot 与外部服务连接起来,让它能访问实时的真实世界数据。Copilot 连接的每个服务都称为一个"MCP 服务器"。在本章中,你将设置几个这样的连接,并了解它们如何让 Copilot 变得更加强大。 + +> 💡 **已经熟悉 MCP 了?** [直接跳到快速入门](#-use-the-built-in-github-mcp)确认它正常工作,然后开始配置服务器。 + +## 🎯 学习目标 + +完成本章后,你将能够: + +- 理解 MCP 是什么以及为何重要 +- 使用 `/mcp` 命令管理 MCP 服务器 +- 配置 GitHub、文件系统和文档的 MCP 服务器 +- 通过书籍应用项目使用 MCP 驱动的工作流 +- 了解何时以及如何构建自定义 MCP 服务器(可选) + +> ⏱️ **预计用时**:约 50 分钟(阅读 15 分钟 + 动手 35 分钟) + +--- + +## 🧩 现实类比:浏览器扩展 + +MCP 服务器就像浏览器扩展 + +把 MCP 服务器想象成浏览器扩展。你的浏览器本身可以显示网页,但扩展将它连接到额外的服务: + +| 浏览器扩展 | 连接到 | MCP 等价物 | +|-----------|--------|-----------| +| 密码管理器 | 你的密码库 | **GitHub MCP** → 你的仓库、Issues、PRs | +| Grammarly | 写作分析服务 | **Context7 MCP** → 库文档 | +| 文件管理器 | 云存储 | **Filesystem MCP** → 本地项目文件 | + +没有扩展,你的浏览器仍然有用,但有了扩展,它就变成了一个强力工具。MCP 服务器对 Copilot 的作用是一样的。它们将 Copilot 连接到真实的实时数据源,让它能读取你的 GitHub Issues、浏览文件系统、获取最新文档等等。 + +***MCP 服务器将 Copilot 与外部世界连接:GitHub、仓库、文档等等*** + +> 💡 **关键洞察**:没有 MCP,Copilot 只能看到你通过 `@` 显式分享的文件。有了 MCP,它可以主动探索你的项目、检查 GitHub 仓库并查找文档,一切自动完成。 + +--- + +电源线连接时产生明亮电火花,周围漂浮着代表 MCP 服务器连接的科技图标 + +# 快速入门:30 秒体验 MCP + + + +## 使用内置 GitHub MCP 服务器 +在配置任何东西之前,先立即体验 MCP。 +GitHub MCP 服务器默认包含在内。试试这个: + +```bash +copilot +> List the recent commits in this repository +``` + +如果 Copilot 返回了真实的提交数据,你刚刚就已经看到了 MCP 的实际效果。这是 GitHub MCP 服务器代表你向 GitHub 发出请求的结果。但 GitHub 只是*一个*服务器。本章将向你展示如何添加更多服务器(文件系统访问、最新文档等),让 Copilot 能做更多事情。 + +--- + +## `/mcp show` 命令 + +使用 `/mcp show` 查看哪些 MCP 服务器已配置以及是否已启用: + +```bash +copilot + +> /mcp show + +MCP Servers: +✓ github (enabled) - GitHub integration +✓ filesystem (enabled) - File system access +``` + +> 💡 **只看到 GitHub 服务器?** 这是正常的!如果你还没有添加任何其他 MCP 服务器,GitHub 是唯一列出的服务器。你将在下一节中添加更多。 + +> 📚 **想查看所有 `/mcp` 命令?** 还有其他用于添加、编辑、启用和删除服务器的命令。请参阅本章末尾的[完整命令参考](#-additional-mcp-commands)。 + +
+🎬 看实际演示! + +![MCP 状态演示](images/mcp-status-demo.gif) + +*演示输出因情况而异。你的模型、工具和响应将与此处显示的不同。* + +
+ +--- + +## MCP 带来了什么变化? + +以下是 MCP 在实际中的区别: + +**没有 MCP:** +```bash +> What's in GitHub issue #42? + +"I don't have access to GitHub. You'll need to copy and paste the issue content." +``` + +**有了 MCP:** +```bash +> What's in GitHub issue #42 of this repository? + +Issue #42: Login fails with special characters +Status: Open +Labels: bug, priority-high +Description: Users report that passwords containing... +``` + +MCP 让 Copilot 了解你真实的开发环境。 + +> 📚 **官方文档**:[关于 MCP](https://docs.github.com/copilot/concepts/context/mcp) 深入了解 MCP 如何与 GitHub Copilot 配合工作。 + +--- + +# 配置 MCP 服务器 + +双手调节专业音频混音台上的旋钮和滑块,代表 MCP 服务器配置 + +现在你已经看到了 MCP 的实际效果,让我们设置更多服务器。本节介绍配置文件格式以及如何添加新服务器。 + +--- + +## MCP 配置文件 + +MCP 服务器在 `~/.copilot/mcp-config.json`(用户级别,适用于所有项目)或 `.vscode/mcp.json`(项目级别,仅适用于当前工作区)中配置。 + +```json +{ + "mcpServers": { + "server-name": { + "type": "local", + "command": "npx", + "args": ["@package/server-name"], + "tools": ["*"] + } + } +} +``` + +*大多数 MCP 服务器以 npm 包的形式发布,通过 `npx` 命令运行。* + +
+💡 不熟悉 JSON? 点击这里了解每个字段的含义 + +| 字段 | 含义 | +|------|------| +| `"mcpServers"` | 所有 MCP 服务器配置的容器 | +| `"server-name"` | 你选择的名称(如"github"、"filesystem")| +| `"type": "local"` | 服务器在你的机器上运行 | +| `"command": "npx"` | 要运行的程序(npx 运行 npm 包)| +| `"args": [...]` | 传递给命令的参数 | +| `"tools": ["*"]` | 允许此服务器的所有工具 | + +**重要的 JSON 规则:** +- 字符串使用双引号 `"`(不是单引号) +- 最后一项后面没有尾随逗号 +- 文件必须是有效的 JSON(如不确定,使用 [JSON 验证器](https://jsonlint.com/)) + +
+ +--- + +## 添加 MCP 服务器 + +GitHub MCP 服务器是内置的,无需任何设置。以下是你可以添加的其他服务器。**选择你感兴趣的,或按顺序操作。** + +| 我想... | 跳转到 | +|--------|--------| +| 让 Copilot 浏览我的项目文件 | [文件系统服务器](#filesystem-server) | +| 获取最新的库文档 | [Context7 服务器](#context7-server-documentation) | +| 探索可选功能(自定义服务器、web_fetch)| [进阶](#beyond-the-basics) | + +
+文件系统服务器——让 Copilot 浏览你的项目文件 + + +### 文件系统服务器 + +```json +{ + "mcpServers": { + "filesystem": { + "type": "local", + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], + "tools": ["*"] + } + } +} +``` + +> 💡 **`.` 路径**:`.` 意思是"当前目录"。Copilot 可以访问你启动它的相对位置的文件。在 Codespace 中,这是工作区根目录。你也可以使用绝对路径,如 `/workspaces/copilot-cli-for-beginners`。 + +将此内容添加到 `~/.copilot/mcp-config.json` 并重启 Copilot。 + +
+ +
+Context7 服务器——获取最新的库文档 + + +### Context7 服务器(文档) + +Context7 让 Copilot 能访问流行框架和库的最新文档。Copilot 不再依赖可能过时的训练数据,而是获取真正的当前文档。 + +```json +{ + "mcpServers": { + "context7": { + "type": "local", + "command": "npx", + "args": ["-y", "@upstash/context7-mcp"], + "tools": ["*"] + } + } +} +``` + +- ✅ **无需 API 密钥** +- ✅ **无需账户** +- ✅ **你的代码留在本地** + +将此内容添加到 `~/.copilot/mcp-config.json` 并重启 Copilot。 + +
+ +
+进阶——自定义服务器和网络访问(可选) + + +这些是当你对上面的核心服务器感到熟悉后的可选功能。 + + + +### Microsoft Learn MCP 服务器 + +到目前为止你看到的所有 MCP 服务器(文件系统、Context7)都在你的机器上本地运行。但 MCP 服务器也可以远程运行,这意味着你只需将 Copilot CLI 指向一个 URL,它会处理其余的事情。无需 `npx` 或 `python`,无需本地进程,无需安装依赖。 + +[Microsoft Learn MCP 服务器](https://github.com/microsoftdocs/mcp) 就是一个很好的例子。它让 Copilot CLI 直接访问官方 Microsoft 文档(Azure、Microsoft Foundry 和其他 AI 主题、.NET、Microsoft 365 等),所以它可以搜索文档、获取完整页面,并找到官方代码示例,而不是依赖模型的训练数据。 + +- ✅ **无需 API 密钥** +- ✅ **无需账户** +- ✅ **无需本地安装** + +**使用 `/plugin install` 快速安装:** + +无需手动编辑 JSON 配置文件,你可以用一条命令安装它: + +```bash +copilot + +> /plugin install microsoftdocs/mcp +``` + +这会自动添加服务器及其关联的智能体技能。安装的技能包括: + +- **microsoft-docs**:概念、教程和事实查询 +- **microsoft-code-reference**:API 查询、代码示例和故障排除 +- **microsoft-skill-creator**:用于生成 Microsoft 技术相关自定义技能的元技能 + +**使用方式:** +```bash +copilot + +> What's the recommended way to deploy a Python app to Azure App Service? Search Microsoft Learn. +``` + +📚 了解更多:[Microsoft Learn MCP 服务器概述](https://learn.microsoft.com/training/support/mcp-get-started) + +### 使用 `web_fetch` 进行网络访问 + +Copilot CLI 包含一个内置的 `web_fetch` 工具,可以从任何 URL 获取内容。这对于在不离开终端的情况下拉取 README、API 文档或发布说明非常有用。无需 MCP 服务器。 + +你可以通过 `~/.copilot/config.json`(通用 Copilot 设置)控制哪些 URL 可以访问,这与 `~/.copilot/mcp-config.json`(MCP 服务器定义)是分开的。 + +```json +{ + "permissions": { + "allowedUrls": [ + "https://api.github.com/**", + "https://docs.github.com/**", + "https://*.npmjs.org/**" + ], + "blockedUrls": [ + "http://**" + ] + } +} +``` + +**使用方式:** +```bash +copilot + +> Fetch and summarize the README from https://github.com/facebook/react +``` + +### 构建自定义 MCP 服务器 + +想将 Copilot 连接到你自己的 API、数据库或内部工具?你可以用 Python 构建一个自定义 MCP 服务器。这是完全可选的,因为预构建的服务器(GitHub、文件系统、Context7)已经覆盖了大多数用例。 + +📖 请参阅[自定义 MCP 服务器指南](mcp-custom-server.zh-CN.md),以书籍应用为例进行完整演示。 + +📚 了解更多背景,请参阅 [MCP 初学者课程](https://github.com/microsoft/mcp-for-beginners)。 + +
+ + + +### 完整配置文件 + +以下是包含文件系统和 Context7 服务器的完整 `mcp-config.json`: + +> 💡 **注意:** GitHub MCP 是内置的,你不需要将它添加到配置文件中。 + +```json +{ + "mcpServers": { + "filesystem": { + "type": "local", + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], + "tools": ["*"] + }, + "context7": { + "type": "local", + "command": "npx", + "args": ["-y", "@upstash/context7-mcp"], + "tools": ["*"] + } + } +} +``` + +将这个内容保存为 `~/.copilot/mcp-config.json` 用于全局访问,或 `.vscode/mcp.json` 用于项目特定配置。 + +--- + +# 使用 MCP 服务器 + +现在你已经配置了 MCP 服务器,让我们看看它们能做什么。 + +使用 MCP 服务器——轮辐图显示开发者 CLI 连接到 GitHub、Filesystem、Context7 和自定义/Web Fetch 服务器 + +--- + +## 服务器使用示例 + +**选择一个服务器来探索,或按顺序操作。** + +| 我想尝试... | 跳转到 | +|------------|--------| +| GitHub 仓库、Issues 和 PRs | [GitHub 服务器](#github-server-built-in) | +| 浏览项目文件 | [文件系统服务器使用](#filesystem-server-usage) | +| 查找库文档 | [Context7 服务器使用](#context7-server-usage) | +| 自定义服务器、Microsoft Learn MCP 和 web_fetch 使用 | [进阶使用](#beyond-the-basics-usage) | + +
+GitHub 服务器(内置)——访问仓库、Issues、PRs 等 + + +### GitHub 服务器(内置) + +GitHub MCP 服务器是**内置的**。如果你已经登录 Copilot(你在初始设置时就已经登录了),它已经可以工作了。无需配置! + +> 💡 **没有工作?** 运行 `/login` 重新通过 GitHub 身份验证。 + +
+开发容器中的身份验证 + +- **GitHub Codespaces**(推荐):身份验证是自动的。`gh` CLI 继承了你的 Codespace 令牌。无需任何操作。 +- **本地开发容器(Docker)**:容器启动后运行 `gh auth login`,然后重启 Copilot。 + +**身份验证故障排除:** +```bash +# Check if you're authenticated +gh auth status + +# If not, log in +gh auth login + +# Verify GitHub MCP is connected +copilot +> /mcp show +``` + +
+ +| 功能 | 示例 | +|------|------| +| **仓库信息** | 查看提交、分支、贡献者 | +| **Issues** | 列出、创建、搜索和评论 Issues | +| **拉取请求** | 查看 PR、差异、创建 PR、检查状态 | +| **代码搜索** | 跨仓库搜索代码 | +| **Actions** | 查询工作流运行和状态 | + +```bash +copilot + +# See recent activity in this repo +> List the last 5 commits in this repository + +Recent commits: +1. abc1234 - Update chapter 05 skills examples (2 days ago) +2. def5678 - Add book app test fixtures (3 days ago) +3. ghi9012 - Fix typo in chapter 03 README (4 days ago) +... + +# Explore the repo structure +> What branches exist in this repository? + +Branches: +- main (default) +- chapter6 (current) + +# Search for code patterns across the repo +> Search this repository for files that import pytest + +Found 1 file: +- samples/book-app-project/tests/test_books.py +``` + +> 💡 **在你自己的 fork 上工作?** 如果你 fork 了这个课程仓库,你还可以尝试写操作,如创建 Issues 和拉取请求。我们将在下面的练习中实践这些。 + +> ⚠️ **没有看到结果?** GitHub MCP 操作的是仓库的远程(在 github.com 上),而不仅仅是本地文件。确保你的仓库有远程:运行 `git remote -v` 检查。 + +
+ +
+文件系统服务器——浏览和分析项目文件 + + +### 文件系统服务器 + +配置后,文件系统 MCP 提供 Copilot 可以自动使用的工具: + +```bash +copilot + +> How many Python files are in the book-app-project directory? + +Found 3 Python files in samples/book-app-project/: +- book_app.py +- books.py +- utils.py + +> What's the total size of the data.json file? + +samples/book-app-project/data.json: 2.4 KB + +> Find all functions that don't have type hints in the book app + +Found 2 functions without type hints: +- samples/book-app-project/utils.py:10 - get_user_choice() +- samples/book-app-project/utils.py:14 - get_book_details() +``` + +
+ +
+Context7 服务器——查找库文档 + + +### Context7 服务器 + +```bash +copilot + +> What are the best practices for using pytest fixtures? + +From pytest Documentation: + +Fixtures - Use fixtures to provide a fixed baseline for tests: + + import pytest + + @pytest.fixture + def sample_books(): + return [ + {"title": "1984", "author": "George Orwell", "year": 1949}, + {"title": "Dune", "author": "Frank Herbert", "year": 1965}, + ] + + def test_find_by_author(sample_books): + # fixture is automatically passed as argument + results = [b for b in sample_books if "Orwell" in b["author"]] + assert len(results) == 1 + +Best practices: +- Use fixtures instead of setup/teardown methods +- Use tmp_path fixture for temporary files +- Use monkeypatch for modifying environment +- Scope fixtures appropriately (function, class, module, session) + +> How can I apply this to the book app's test file? + +# Copilot now knows the official pytest patterns +# and can apply them to samples/book-app-project/tests/test_books.py +``` + +
+ +
+进阶——自定义服务器和 web_fetch 使用 + + +### 进阶 + +**自定义 MCP 服务器**:如果你从[自定义 MCP 服务器指南](mcp-custom-server.zh-CN.md)构建了书籍查找服务器,你可以直接查询你的书籍集合: + +```bash +copilot + +> Look up information about "1984" using the book lookup server. Search for books by George Orwell +``` + +**Microsoft Learn MCP**:如果你安装了 [Microsoft Learn MCP 服务器](#microsoft-learn-mcp-server),你可以直接查找官方 Microsoft 文档: + +```bash +copilot + +> How do I configure managed identity for an Azure Function? Search Microsoft Learn. +``` + +**网络获取**:使用内置的 `web_fetch` 工具从任何 URL 拉取内容: + +```bash +copilot + +> Fetch and summarize the README from https://github.com/facebook/react +``` + +
+ +--- + +## 多服务器工作流 + +这些工作流展示了为什么开发者会说"我再也不想在没有这个的情况下工作了"。每个示例都在一个会话中将多个 MCP 服务器组合在一起。 + +使用 MCP 的 Issue 到 PR 工作流——显示从获取 GitHub Issue 到创建拉取请求的完整流程 + +*完整的 MCP 工作流:GitHub MCP 检索仓库数据,Filesystem MCP 查找代码,Context7 MCP 提供最佳实践,Copilot 负责分析* + +下面的每个示例都是独立的。**选择一个你感兴趣的,或全部阅读。** + +| 我想看... | 跳转到 | +|----------|--------| +| 多个服务器协同工作 | [多服务器探索](#multi-server-exploration) | +| 在一个会话中从 Issue 到 PR | [Issue 到 PR 工作流](#issue-to-pr-workflow) | +| 快速的项目健康检查 | [健康仪表板](#health-dashboard) | + +
+多服务器探索——在一个会话中结合文件系统、GitHub 和 Context7 + + +#### 使用多个 MCP 服务器探索书籍应用 + +```bash +copilot + +# Step 1: Use filesystem MCP to explore the book app +> List all Python files in samples/book-app-project/ and summarize +> what each file does + +Found 3 Python files: +- book_app.py: CLI entry point with command routing (list, add, remove, find) +- books.py: BookCollection class with data persistence via JSON +- utils.py: Helper functions for user input and display + +# Step 2: Use GitHub MCP to check recent changes +> What were the last 3 commits that touched files in samples/book-app-project/? + +Recent commits affecting book app: +1. abc1234 - Add test fixtures for BookCollection (2 days ago) +2. def5678 - Add find_by_author method (5 days ago) +3. ghi9012 - Initial book app setup (1 week ago) + +# Step 3: Use Context7 MCP for best practices +> What are Python best practices for JSON data persistence? + +From Python Documentation: +- Use context managers (with statements) for file I/O +- Handle JSONDecodeError for corrupted files +- Use dataclasses for structured data +- Consider atomic writes to prevent data corruption + +# Step 4: Synthesize a recommendation +> Based on the book app code and these best practices, +> what improvements would you suggest? + +Suggestions: +1. Add input validation in add_book() for empty strings and invalid years +2. Consider atomic writes in save_books() to prevent data corruption +3. Add type hints to utils.py functions (get_user_choice, get_book_details) +``` + +
+🎬 看 MCP 工作流实际演示! + +![MCP 工作流演示](images/mcp-workflow-demo.gif) + +*演示输出因情况而异。你的模型、工具和响应将与此处显示的不同。* + +
+ +**结果**:代码探索 → 历史审查 → 最佳实践查询 → 改进计划。**全部在一个终端会话中,使用三个 MCP 服务器协同完成。** + +
+ +
+Issue 到 PR 工作流——不离开终端,从 GitHub Issue 一路到拉取请求 + + +#### Issue 到 PR 工作流(在你自己的仓库上) + +在你有写权限的 fork 或仓库上效果最佳: + +> 💡 **如果现在无法尝试也不用担心。** 如果你在只读克隆上,你将在作业中练习这个。现在只需阅读以理解流程即可。 + +```bash +copilot + +> Get the details of GitHub issue #1 + +Issue #1: Add input validation for book year +Status: Open +Description: The add_book function accepts any year value... + +> @samples/book-app-project/books.py Fix the issue described in issue #1 + +[Copilot 在 add_book() 中实现年份验证] + +> Run the tests to make sure the fix works + +All 8 tests passed ✓ + +> Create a pull request titled "Add year validation to book app" + +✓ Created PR #2: Add year validation to book app +``` + +**零复制粘贴。零上下文切换。一个终端会话。** + +
+ +
+健康仪表板——使用多个服务器快速获取项目健康检查 + + +#### 书籍应用健康仪表板 + +```bash +copilot + +> Give me a health report for the book app project: +> 1. List all functions across the Python files in samples/book-app-project/ +> 2. Check which functions have type hints and which don't +> 3. Show what tests exist in samples/book-app-project/tests/ +> 4. Check the recent commit history for this directory + +Book App Health Report +====================== + +📊 Functions Found: +- books.py: 8 methods in BookCollection (all have type hints ✓) +- book_app.py: 6 functions (4 have type hints, 2 missing) +- utils.py: 3 functions (1 has type hints, 2 missing) + +🧪 Test Coverage: +- test_books.py: 8 test functions covering BookCollection +- Missing: no tests for book_app.py CLI functions +- Missing: no tests for utils.py helper functions + +📝 Recent Activity: +- 3 commits in the last week +- Most recent: added test fixtures + +Recommendations: +- Add type hints to utils.py functions +- Add tests for book_app.py CLI handlers +- All files well-sized (<100 lines) - good structure! +``` + +**结果**:多个数据源在几秒钟内聚合完毕。手动完成这些工作需要运行 grep、计算行数、检查 git log 并浏览测试文件。轻松需要 15 分钟以上。 + +
+ +--- + +# 动手练习 + +温馨的桌面环境,显示器显示代码,台灯、咖啡杯和耳机,准备好动手实践 + +**🎉 你现在已经掌握了要点!** 你理解了 MCP,了解了如何配置服务器,并看到了真实的工作流。现在是时候亲自尝试了。 + +--- + +## ▶️ 自己试试 + +现在轮到你了!完成这些练习,用 MCP 服务器实践书籍应用项目。 + +### 练习 1:检查你的 MCP 状态 + +首先查看哪些 MCP 服务器可用: + +```bash +copilot + +> /mcp show +``` + +你应该会看到 GitHub 服务器被列为已启用。如果没有,运行 `/login` 进行身份验证。 + +--- + +### 练习 2:使用文件系统 MCP 探索书籍应用 + +如果你配置了文件系统服务器,用它来探索书籍应用: + +```bash +copilot + +> How many Python files are in samples/book-app-project/? +> What functions are defined in each file? +``` + +**预期结果**:Copilot 列出 `book_app.py`、`books.py` 和 `utils.py` 及其函数。 + +> 💡 **还没有配置文件系统 MCP?** 使用上方[完整配置](#complete-configuration-file)部分的 JSON 创建配置文件,然后重启 Copilot。 + +--- + +### 练习 3:使用 GitHub MCP 查询仓库历史 + +使用内置的 GitHub MCP 探索这个课程仓库: + +```bash +copilot + +> List the last 5 commits in this repository + +> What branches exist in this repository? +``` + +**预期结果**:Copilot 显示来自 GitHub 远程的最近提交信息和分支名称。 + +> ⚠️ **在 Codespace 中?** 这会自动工作,身份验证已继承。如果你在本地克隆上,确保 `gh auth status` 显示你已登录。 + +--- + +### 练习 4:组合多个 MCP 服务器 + +现在在单个会话中组合文件系统和 GitHub MCP: + +```bash +copilot + +> Read samples/book-app-project/data.json and tell me what books are +> in the collection. Then check the recent commits to see when this +> file was last modified. +``` + +**预期结果**:Copilot 读取 JSON 文件(文件系统 MCP),列出包括「The Hobbit」、「1984」、「Dune」、「To Kill a Mockingbird」和「Mysterious Book」在内的 5 本书,然后通过 GitHub 查询提交历史。 + +**自我检验**:当你能解释为什么「Check my repo's commit history」比手动运行 `git log` 并将输出粘贴到提示词中更好时,你就理解了 MCP。 + +--- + +## 📝 作业 + +### 主要挑战:书籍应用 MCP 探索 + +练习在书籍应用项目上一起使用 MCP 服务器。在单个 Copilot 会话中完成以下步骤: + +1. **验证 MCP 正常工作**:运行 `/mcp show` 确认至少 GitHub 服务器已启用 +2. **设置文件系统 MCP**(如果还没有):创建 `~/.copilot/mcp-config.json` 并填入文件系统服务器配置 +3. **探索代码**:让 Copilot 使用文件系统服务器: + - 列出 `samples/book-app-project/books.py` 中的所有函数 + - 检查 `samples/book-app-project/utils.py` 中哪些函数缺少类型注解 + - 读取 `samples/book-app-project/data.json` 并识别任何数据质量问题(提示:查看最后一条) +4. **检查仓库活动**:让 Copilot 使用 GitHub MCP: + - 列出影响 `samples/book-app-project/` 文件的最近提交 + - 检查是否有任何开放的 Issues 或拉取请求 +5. **组合服务器**:在单个提示词中,让 Copilot: + - 读取 `samples/book-app-project/tests/test_books.py` 中的测试文件 + - 将测试的函数与 `books.py` 中的所有函数进行比较 + - 总结缺少哪些测试覆盖 + +**成功标准**:你能在单个 Copilot 会话中无缝组合文件系统和 GitHub MCP 数据,并能解释每个 MCP 服务器对响应的贡献。 + +
+💡 提示(点击展开) + +**步骤 1:验证 MCP** +```bash +copilot +> /mcp show +# Should show "github" as enabled +# If not, run: /login +``` + +**步骤 2:创建配置文件** + +使用上方[完整配置](#complete-configuration-file)部分的 JSON,将其保存为 `~/.copilot/mcp-config.json`。 + +**步骤 3:要寻找的数据质量问题** + +`data.json` 中的最后一本书是: +```json +{ + "title": "Mysterious Book", + "author": "", + "year": 0, + "read": false +} +``` +空的 author 字段和 year 为 0 就是数据质量问题! + +**步骤 5:测试覆盖率比较** + +`test_books.py` 中的测试涵盖:`add_book`、`mark_as_read`、`remove_book`、`get_unread_books` 和 `find_book_by_title`。`load_books`、`save_books` 和 `list_books` 等函数没有直接测试。`book_app.py` 中的 CLI 函数和 `utils.py` 中的辅助函数完全没有测试。 + +**如果 MCP 不工作:** 编辑配置文件后重启 Copilot。 + +
+ +### 附加挑战:构建自定义 MCP 服务器 + +准备好深入探索了?按照[自定义 MCP 服务器指南](mcp-custom-server.zh-CN.md)用 Python 构建你自己的 MCP 服务器,连接到任何 API。 + +--- + +
+🔧 常见错误与故障排除(点击展开) + +### 常见错误 + +| 错误 | 发生了什么 | 解决方法 | +|------|-----------|---------| +| 不知道 GitHub MCP 是内置的 | 尝试手动安装/配置它 | GitHub MCP 默认包含在内,直接试试:「List the recent commits in this repo」| +| 在错误位置查找配置 | 找不到或无法编辑 MCP 设置 | 用户级配置在 `~/.copilot/mcp-config.json`,项目级在 `.vscode/mcp.json` | +| 配置文件中 JSON 无效 | MCP 服务器无法加载 | 使用 `/mcp show` 检查配置;验证 JSON 语法 | +| 忘记验证 MCP 服务器 | 出现「Authentication failed」错误 | 某些 MCP 需要单独的身份验证,检查每个服务器的要求 | + +### 故障排除 + +**"MCP server not found"** - 检查: +1. npm 包存在:`npm view @modelcontextprotocol/server-github` +2. 你的配置是有效的 JSON +3. 服务器名称与你的配置匹配 + +使用 `/mcp show` 查看当前配置。 + +**"GitHub authentication failed"** - 内置 GitHub MCP 使用你的 `/login` 凭据。尝试: + +```bash +copilot +> /login +``` + +这会重新通过 GitHub 验证你的身份。如果问题持续,检查你的 GitHub 账户是否拥有访问该仓库所需的权限。 + +**"MCP server failed to start"** - 手动运行服务器命令查看错误: +```bash +npx -y @modelcontextprotocol/server-github +``` + +**MCP 工具不可用** - 确保服务器已启用: +```bash +copilot + +> /mcp show +# Check if server is listed and enabled +``` + +如果服务器被禁用,请参阅下方的[附加 `/mcp` 命令](#-additional-mcp-commands)了解如何重新启用它。 + +
+ +--- + +
+📚 附加 /mcp 命令(点击展开) + + +除了 `/mcp show`,还有其他几个管理 MCP 服务器的命令: + +| 命令 | 作用 | +|------|------| +| `/mcp show` | 显示所有已配置的 MCP 服务器及其状态 | +| `/mcp add` | 交互式添加新服务器 | +| `/mcp edit <服务器名称>` | 编辑现有服务器配置 | +| `/mcp enable <服务器名称>` | 启用已禁用的服务器 | +| `/mcp disable <服务器名称>` | 临时禁用服务器 | +| `/mcp delete <服务器名称>` | 永久删除服务器 | + +在本课程的大多数情况下,`/mcp show` 是你所需要的全部。其他命令在你随时间管理更多服务器时会变得有用。 + +
+ +--- + +# 总结 + +## 🔑 关键要点 + +1. **MCP** 将 Copilot 连接到外部服务(GitHub、文件系统、文档) +2. **GitHub MCP 是内置的**——无需配置,只需 `/login` +3. **文件系统和 Context7** 通过 `~/.copilot/mcp-config.json` 配置 +4. **多服务器工作流**在单个会话中组合来自多个数据源的数据 +5. **使用 `/mcp show` 检查服务器状态**(还有其他管理服务器的命令) +6. **自定义服务器**允许你连接任何 API(可选,在附录指南中介绍) + +> 📋 **快速参考**:查看 [GitHub Copilot CLI 命令参考](https://docs.github.com/en/copilot/reference/cli-command-reference) 获取完整的命令和快捷键列表。 + +--- + +## ➡️ 下一步 + +你现在拥有了所有构建块:模式、上下文、工作流、智能体、技能和 MCP。是时候将它们整合在一起了。 + +在**[第 07 章:整合所有内容](../07-putting-it-together/README.zh-CN.md)**中,你将学习: + +- 在统一工作流中组合智能体、技能和 MCP +- 从想法到合并 PR 的完整功能开发 +- 使用 hooks 进行自动化 +- 团队环境的最佳实践 + +--- + +**[← 返回第 05 章](../05-skills/README.zh-CN.md)** | **[继续第 07 章 →](../07-putting-it-together/README.zh-CN.md)** diff --git a/06-mcp-servers/mcp-custom-server.zh-CN.md b/06-mcp-servers/mcp-custom-server.zh-CN.md new file mode 100644 index 0000000..64ea11f --- /dev/null +++ b/06-mcp-servers/mcp-custom-server.zh-CN.md @@ -0,0 +1,176 @@ +# 构建自定义 MCP 服务器 + +> ⚠️ **本内容完全可选。** 仅使用预构建的 MCP 服务器(GitHub、文件系统、Context7),你已经可以高效地使用 Copilot CLI。本指南适用于希望将 Copilot 连接到自定义内部 API 的开发者。更多详情请参阅 [MCP 初学者课程](https://github.com/microsoft/mcp-for-beginners)。 +> +> **前置条件:** +> - 熟悉 Python +> - 理解 `async`/`await` 模式 +> - 系统上已安装 `pip`(包含在此开发容器中) +> +> **[← 返回第 06 章:MCP 服务器](README.zh-CN.md)** + +--- + +想将 Copilot 连接到你自己的 API?这里介绍如何用 Python 构建一个简单的 MCP 服务器,查找书籍信息——与你在本课程中一直使用的书籍应用项目相呼应。 + +## 项目设置 + +```bash +mkdir book-lookup-mcp-server +cd book-lookup-mcp-server +pip install mcp +``` + +> 💡 **什么是 `mcp` 包?** 这是用于构建 MCP 服务器的官方 Python SDK。它处理协议细节,让你专注于你的工具逻辑。 + +## 服务器实现 + +创建名为 `server.py` 的文件: + +```python +# server.py +import json +from mcp.server.fastmcp import FastMCP + +# Create the MCP server +mcp = FastMCP("book-lookup") + +# Sample book database (in a real server, this could query an API or database) +BOOKS_DB = { + "978-0-547-92822-7": { + "title": "The Hobbit", + "author": "J.R.R. Tolkien", + "year": 1937, + "genre": "Fantasy", + }, + "978-0-451-52493-5": { + "title": "1984", + "author": "George Orwell", + "year": 1949, + "genre": "Dystopian Fiction", + }, + "978-0-441-17271-9": { + "title": "Dune", + "author": "Frank Herbert", + "year": 1965, + "genre": "Science Fiction", + }, +} + + +@mcp.tool() +def lookup_book(isbn: str) -> str: + """Look up a book by its ISBN and return title, author, year, and genre.""" + book = BOOKS_DB.get(isbn) + if book: + return json.dumps(book, indent=2) + return f"No book found with ISBN: {isbn}" + + +@mcp.tool() +def search_books(query: str) -> str: + """Search for books by title or author. Returns all matching results.""" + query_lower = query.lower() + results = [ + {**book, "isbn": isbn} + for isbn, book in BOOKS_DB.items() + if query_lower in book["title"].lower() + or query_lower in book["author"].lower() + ] + if results: + return json.dumps(results, indent=2) + return f"No books found matching: {query}" + + +@mcp.tool() +def list_all_books() -> str: + """List all books in the database with their ISBNs.""" + books_list = [ + {"isbn": isbn, "title": book["title"], "author": book["author"]} + for isbn, book in BOOKS_DB.items() + ] + return json.dumps(books_list, indent=2) + + +if __name__ == "__main__": + mcp.run() +``` + +**代码说明:** + +| 部分 | 作用 | +|------|------| +| `FastMCP("book-lookup")` | 创建名为"book-lookup"的服务器 | +| `@mcp.tool()` | 将函数注册为 Copilot 可调用的工具 | +| 类型注解 + docstring | 告诉 Copilot 每个工具的功能和所需参数 | +| `mcp.run()` | 启动服务器并监听请求 | + +> 💡 **为何使用装饰器?** `@mcp.tool()` 装饰器就是你所需要的全部。MCP SDK 会自动读取函数的名称、类型注解和 docstring 来生成工具模式,无需手动编写 JSON Schema! + +## 配置 + +添加到你的 `~/.copilot/mcp-config.json`: + +```json +{ + "mcpServers": { + "book-lookup": { + "type": "local", + "command": "python3", + "args": ["./book-lookup-mcp-server/server.py"], + "tools": ["*"] + } + } +} +``` + +## 使用方式 + +```bash +copilot + +> Look up the book with ISBN 978-0-547-92822-7 + +{ + "title": "The Hobbit", + "author": "J.R.R. Tolkien", + "year": 1937, + "genre": "Fantasy" +} + +> Search for books by Orwell + +[ + { + "title": "1984", + "author": "George Orwell", + "year": 1949, + "genre": "Dystopian Fiction", + "isbn": "978-0-451-52493-5" + } +] + +> List all available books + +[Shows all books in the database with ISBNs] +``` + +## 下一步 + +构建基础服务器后,你可以: + +1. **添加更多工具**——每个 `@mcp.tool()` 函数都成为 Copilot 可调用的工具 +2. **连接真实 API**——将模拟的 `BOOKS_DB` 替换为实际的 API 调用或数据库查询 +3. **添加身份验证**——安全地处理 API 密钥和令牌 +4. **分享你的服务器**——发布到 PyPI,让其他人可以用 `pip` 安装 + +## 资源 + +- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) +- [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) +- [MCP 服务器示例](https://github.com/modelcontextprotocol/servers) +- [MCP 初学者课程](https://github.com/microsoft/mcp-for-beginners) + +--- + +**[← 返回第 06 章:MCP 服务器](README.zh-CN.md)** diff --git a/07-putting-it-together/README.zh-CN.md b/07-putting-it-together/README.zh-CN.md new file mode 100644 index 0000000..eca0cd2 --- /dev/null +++ b/07-putting-it-together/README.zh-CN.md @@ -0,0 +1,515 @@ +![第 07 章:整合所有内容](images/chapter-header.png) + +> **你学到的一切都会在这里汇合。只用一次会话,就能从想法走到合并 PR。** + +在本章中,你会把之前学到的内容整合成完整工作流。你将使用多智能体协作来构建功能,设置能在提交前拦截安全问题的 pre-commit hook,把 Copilot 集成进 CI/CD 流水线,并在一次终端会话中完成从功能想法到合并 PR 的全过程。GitHub Copilot CLI 会在这里真正成为你的效率放大器。 + +> 💡 **注意**:本章展示的是如何把你学到的一切组合起来。**即使没有智能体、技能或 MCP,你依然可以高效工作(虽然它们会非常有帮助)。** 核心工作流,也就是描述、规划、实现、测试、审查、交付,只靠第 00-03 章中的内置功能就能完成。 + +## 🎯 学习目标 + +完成本章后,你将能够: + +- 在统一工作流中组合智能体、技能和 MCP(模型上下文协议) +- 使用多工具方法构建完整功能 +- 通过 hook 设置基础自动化 +- 将专业开发的最佳实践应用到日常工作中 + +> ⏱️ **预计用时**:约 75 分钟(阅读 15 分钟 + 动手 60 分钟) + +--- + +## 🧩 现实类比:交响乐团 + +交响乐团类比:统一工作流 + +一支交响乐团由许多声部组成: +- **弦乐**提供基础,就像你的核心工作流 +- **铜管**增加力量,就像具备专门专长的智能体 +- **木管**增加色彩,就像扩展能力的技能 +- **打击乐**维持节奏,就像 MCP 连接外部系统 + +单独来看,每个声部的表现都有限。只有在良好指挥下协同演奏,它们才能创造出真正出色的成果。 + +**这正是本章要教你的内容!**
+*就像指挥家调度乐团一样,你将把智能体、技能和 MCP 编排成统一工作流* + +先从一个场景开始:在一次会话里修改代码、生成测试、完成审查并创建 PR。 + +--- + + + +## 一次会话从想法到合并 PR + +你不必在编辑器、终端、测试运行器和 GitHub UI 之间来回切换并不断丢失上下文,而是可以把所有工具集中到一个终端会话中完成。我们会在下方的[集成模式](#the-integration-pattern-for-power-users)部分拆解这种模式。 + +```bash +# Start Copilot in interactive mode +copilot + +> I need to add a "list unread" command to the book app that shows only +> books where read is False. What files need to change? + +# Copilot creates high-level plan... + +# SWITCH TO PYTHON-REVIEWER AGENT +> /agent +# Select "python-reviewer" + +> @samples/book-app-project/books.py Design a get_unread_books method. +> What is the best approach? + +# Python-reviewer agent produces: +# - Method signature and return type +# - Filter implementation using list comprehension +# - Edge case handling for empty collections + +# SWITCH TO PYTEST-HELPER AGENT +> /agent +# Select "pytest-helper" + +> @samples/book-app-project/tests/test_books.py Design test cases for +> filtering unread books. + +# Pytest-helper agent produces: +# - Test cases for empty collections +# - Test cases with mixed read/unread books +# - Test cases with all books read + +# IMPLEMENT +> Add a get_unread_books method to BookCollection in books.py +> Add a "list unread" command option in book_app.py +> Update the help text in the show_help function + +# TEST +> Generate comprehensive tests for the new feature + +# Multiple tests are generated similar to the following: +# - Happy path (3 tests) — filters correctly, excludes read, includes unread +# - Edge cases (4 tests) — empty collection, all read, none read, single book +# - Parametrized (5 cases) — varying read/unread ratios via @pytest.mark.parametrize +# - Integration (4 tests) — interplay with mark_as_read, remove_book, add_book, and data integrity + +# Review the changes +> /review + +# If review passes, generate a PR (uses GitHub MCP covered earlier in the course) +> Create a pull request titled "Feature: Add list unread books command" +``` + +**传统方式**:在编辑器、终端、测试运行器、文档和 GitHub UI 之间不断切换。每次切换都会带来上下文丢失和额外摩擦。 + +**关键洞察**:你像架构师一样调度这些专家。细节由他们处理,方向由你掌控。 + +> 💡 **继续深入**:对于这种大型多步骤计划,可以试试 `/fleet`,让 Copilot 并行运行相互独立的子任务。详情请参阅[官方文档](https://docs.github.com/copilot/concepts/agents/copilot-cli/fleet)。 + +--- + +# 更多工作流 + +人们正在拼装带齿轮的彩色巨型拼图,表示智能体、技能和 MCP 如何组合成统一工作流 + +对于完成了第 04-06 章的高级用户而言,下面这些工作流展示了智能体、技能和 MCP 如何成倍放大你的效率。 + + + +## 集成模式 + +这是将所有能力组合起来时的心智模型: + +集成模式:四阶段工作流,包括收集上下文(MCP)、分析与规划(智能体)、执行(技能 + 手动)、完成(MCP) + +--- + +## 工作流 1:排查并修复缺陷 + +这是一个集成全部工具的真实缺陷修复流程: + +```bash +copilot + +# PHASE 1: Understand the bug from GitHub (MCP provides this) +> Get the details of issue #1 + +# Learn: "find_by_author doesn't work with partial names" + +# PHASE 2: Research best practice (deep research with web + GitHub sources) +> /research Best practices for Python case-insensitive string matching + +# PHASE 3: Find related code +> @samples/book-app-project/books.py Show me the find_by_author method + +# PHASE 4: Get expert analysis +> /agent +# Select "python-reviewer" + +> Analyze this method for issues with partial name matching + +# Agent identifies: Method uses exact equality instead of substring matching + +# PHASE 5: Fix with agent guidance +> Implement the fix using lowercase comparison and 'in' operator + +# PHASE 6: Generate tests +> /agent +# Select "pytest-helper" + +> Generate pytest tests for find_by_author with partial matches +> Include test cases: partial name, case variations, no matches + +# PHASE 7: Commit and PR +> Generate a commit message for this fix + +> Create a pull request linking to issue #1 +``` + +--- + + + +## 工作流 2:代码审查自动化(可选) + +> 💡 **这一节是可选的。** pre-commit hook 对团队很有帮助,但并不是高效工作的前提。如果你刚开始使用,可以先跳过。 +> +> ⚠️ **性能说明**:这个 hook 会对每个已暂存文件调用一次 `copilot -p`,每个文件通常都需要几秒。对于较大的提交,建议只限制到关键文件,或者改为使用 `/review` 手动审查。 + +**git hook** 是 Git 在特定时机自动运行的脚本,例如在提交前。你可以利用它对代码执行自动检查。下面是如何在提交时运行自动化 Copilot 审查: + +```bash +# Create a pre-commit hook +cat > .git/hooks/pre-commit << 'EOF' +#!/bin/bash + +# Get staged files (Python files only) +STAGED=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.py$') + +if [ -n "$STAGED" ]; then + echo "Running Copilot review on staged files..." + + for file in $STAGED; do + echo "Reviewing $file..." + + # Use timeout to prevent hanging (60 seconds per file) + # --allow-all auto-approves file reads/writes so the hook can run unattended. + # Only use this in automated scripts. In interactive sessions, let Copilot ask for permission. + REVIEW=$(timeout 60 copilot --allow-all -p "Quick security review of @$file - critical issues only" 2>/dev/null) + + # Check if timeout occurred + if [ $? -eq 124 ]; then + echo "Warning: Review timed out for $file (skipping)" + continue + fi + + if echo "$REVIEW" | grep -qi "CRITICAL"; then + echo "Critical issues found in $file:" + echo "$REVIEW" + exit 1 + fi + done + + echo "Review passed" +fi +EOF + +chmod +x .git/hooks/pre-commit +``` + +> ⚠️ **macOS 用户**:macOS 默认不包含 `timeout` 命令。你可以用 `brew install coreutils` 安装,或者去掉超时保护,直接调用命令。 + +> 📚 **官方文档**:[Use hooks](https://docs.github.com/copilot/how-tos/copilot-cli/use-hooks) 和 [Hooks configuration reference](https://docs.github.com/copilot/reference/hooks-configuration) 提供了完整的 hooks API。 +> +> 💡 **内置替代方案**:Copilot CLI 也有内置 hooks 系统(`copilot hooks`),可以在 pre-commit 等事件上自动运行。上面的手工 git hook 能给你完全控制权,而内置系统配置起来更简单。你可以结合文档决定哪种方式更适合你的工作流。 + +现在,每次提交都会先经过一次快速安全审查: + +```bash +git add samples/book-app-project/books.py +git commit -m "Update book collection methods" + +# Output: +# Running Copilot review on staged files... +# Reviewing samples/book-app-project/books.py... +# Critical issues found in samples/book-app-project/books.py: +# - Line 15: File path injection vulnerability in load_from_file +# +# Fix the issue and try again. +``` + +--- + +## 工作流 3:加入新代码库时快速上手 + +当你加入一个新项目时,可以把上下文、智能体和 MCP 组合起来,快速完成熟悉过程: + +```bash +# Start Copilot in interactive mode +copilot + +# PHASE 1: Get the big picture with context +> @samples/book-app-project/ Explain the high-level architecture of this codebase + +# PHASE 2: Understand a specific flow +> @samples/book-app-project/book_app.py Walk me through what happens +> when a user runs "python book_app.py add" + +# PHASE 3: Get expert analysis with an agent +> /agent +# Select "python-reviewer" + +> @samples/book-app-project/books.py Are there any design issues, +> missing error handling, or improvements you would recommend? + +# PHASE 4: Find something to work on (MCP provides GitHub access) +> List open issues labeled "good first issue" + +# PHASE 5: Start contributing +> Pick the simplest open issue and outline a plan to fix it +``` + +这个工作流把 `@` 上下文、智能体和 MCP 合并到了同一个入门会话中,正对应本章前面介绍的集成模式。 + +--- + +# 最佳实践与自动化 + +这些模式和习惯能让你的工作流更高效。 + +--- + +## 最佳实践 + +### 1. 先建立上下文,再进行分析 + +提出分析请求之前,先把上下文收集完整: + +```bash +# Good +> Get the details of issue #42 +> /agent +# Select python-reviewer +> Analyze this issue + +# Less effective +> /agent +# Select python-reviewer +> Fix login bug +# Agent doesn't have issue context +``` + +### 2. 区分清楚:智能体、技能与自定义指令 + +每种工具都有最适合自己的位置: + +```bash +# Agents: Specialized personas you explicitly activate +> /agent +# Select python-reviewer +> Review this authentication code for security issues + +# Skills: Modular capabilities that auto-activate when your prompt +# matches the skill's description (you must create them first — see Ch 05) +> Generate comprehensive tests for this code +# If you have a testing skill configured, it activates automatically + +# Custom instructions (.github/copilot-instructions.md): Always-on +# guidance that applies to every session without switching or triggering +``` + +> 💡 **关键点**:智能体和技能都能做分析,也都能生成代码。真正的区别在于**它们如何被激活**:智能体是显式的(`/agent`),技能是自动的(根据提示匹配),自定义指令则是始终生效的。 + +### 3. 让每个会话聚焦单一目标 + +使用 `/rename` 为会话命名,便于在历史中查找;使用 `/exit` 干净地结束会话: + +```bash +# Good: One feature per session +> /rename list-unread-feature +# Work on list unread +> /exit + +copilot +> /rename export-csv-feature +# Work on CSV export +> /exit + +# Less effective: Everything in one long session +``` + +### 4. 把工作流沉淀为可复用的 Copilot 资产 + +不要只把流程写在 wiki 里,而要直接编码进仓库,让 Copilot 真正能用上: + +- **自定义指令**(`.github/copilot-instructions.md`):始终生效的指导,用于编码规范、架构约束,以及构建、测试、部署步骤。每次会话都会自动遵循。 +- **提示文件**(`.github/prompts/`):团队可共享的可复用参数化提示模板,例如代码审查、组件生成或 PR 描述模板。 +- **自定义智能体**(`.github/agents/`):把专门角色编码下来,例如安全审查员或文档写作者,团队成员都可以通过 `/agent` 激活。 +- **自定义技能**(`.github/skills/`):把分步骤工作流封装起来,在相关场景下自动触发。 + +> 💡 **回报**:新成员可以直接继承你的工作流,它们已经内建在仓库里,而不是只存在于某个人脑中。 + +--- + +## 加餐:生产环境模式 + +这些模式是可选的,但在专业环境里很有价值。 + +### PR 描述生成器 + +```bash +# Generate comprehensive PR descriptions +BRANCH=$(git branch --show-current) +COMMITS=$(git log main..$BRANCH --oneline) + +copilot -p "Generate a PR description for: +Branch: $BRANCH +Commits: +$COMMITS + +Include: Summary, Changes Made, Testing Done, Screenshots Needed" +``` + +### CI/CD 集成 + +对于已经使用 CI/CD 流水线的团队,你可以借助 GitHub Actions 在每个拉取请求上自动运行 Copilot 审查。这包括自动发布审查评论,以及按关键问题级别进行过滤。 + +> 📖 **了解更多**:请参阅 [CI/CD 集成](../appendices/ci-cd-integration.zh-CN.md),其中包含完整的 GitHub Actions 工作流、配置选项和故障排除说明。 + +--- + +# 练习 + +温馨的桌面环境,显示器展示代码,配有台灯、咖啡杯和耳机,适合动手练习 + +把完整工作流真正用起来。 + +--- + +## ▶️ 自己试试 + +完成演示后,试试这些变体: + +1. **端到端挑战**:选择一个小功能,例如 “list unread books” 或 “export to CSV”,然后走完整个流程: + - 使用 `/plan` 规划 + - 用智能体设计(python-reviewer、pytest-helper) + - 实现 + - 生成测试 + - 创建 PR + +2. **自动化挑战**:按照“代码审查自动化”工作流设置 pre-commit hook。然后故意提交一个带文件路径漏洞的改动,看看它是否会被拦截。 + +3. **你的生产工作流**:为自己经常做的一类任务设计一套工作流,把它写成检查清单。思考哪些部分可以用技能、智能体或 hook 自动化。 + +**自我检验**:当你能向同事解释智能体、技能和 MCP 如何协同工作,以及应该在什么场景下分别使用它们时,就说明你已经完成了本课程。 + +--- + +## 📝 作业 + +### 主要挑战:端到端功能开发 + +前面的实战示例演示了如何构建 “list unread books” 功能。现在请你用另一个功能来练习完整工作流:**按年份范围搜索书籍**。 + +1. 启动 Copilot 并收集上下文:`@samples/book-app-project/books.py` +2. 用 `/plan Add a "search by year" command that lets users find books published between two years` 进行规划 +3. 在 `BookCollection` 中实现 `find_by_year_range(start_year, end_year)` 方法 +4. 在 `book_app.py` 中添加 `handle_search_year()` 函数,用于提示用户输入起始和结束年份 +5. 生成测试:`@samples/book-app-project/books.py @samples/book-app-project/tests/test_books.py Generate tests for find_by_year_range() including edge cases like invalid years, reversed range, and no results.` +6. 使用 `/review` 审查 +7. 更新 README:`@samples/book-app-project/README.md Add documentation for the new "search by year" command.` +8. 生成提交信息 + +边做边记录你的工作流。 + +**成功标准**:你已经借助 Copilot CLI,从想法一路完成到提交,覆盖规划、实现、测试、文档和审查的完整流程。 + +> 💡 **加分项**:如果你已经按照第 04 章设置了智能体,可以尝试创建并使用自定义智能体。例如,用一个 error-handler 智能体做实现审查,用一个 doc-writer 智能体更新 README。 + +
+💡 提示(点击展开) + +**沿用本章开头[“一次会话从想法到合并 PR”](#idea-to-merged-pr-in-one-session)的模式。** 关键步骤如下: + +1. 用 `@samples/book-app-project/books.py` 收集上下文 +2. 用 `/plan Add a "search by year" command` 做规划 +3. 实现方法和命令处理函数 +4. 生成覆盖边界情况的测试(无效输入、空结果、范围反转) +5. 使用 `/review` 审查 +6. 用 `@samples/book-app-project/README.md` 更新 README +7. 使用 `-p` 生成提交信息 + +**需要考虑的边界情况:** +- 如果用户输入 “2000” 和 “1990” 这种反向范围怎么办? +- 如果没有任何书匹配该范围怎么办? +- 如果用户输入的是非数字怎么办? + +**重点在于练习完整流程**:从想法 → 上下文 → 规划 → 实现 → 测试 → 文档 → 提交。 + +
+ +--- + +
+🔧 常见错误(点击展开) + +| 错误 | 会发生什么 | 修复方式 | +|---------|--------------|-----| +| 直接跳到实现 | 会错过一些后续代价很高的设计问题 | 先用 `/plan` 想清楚方案 | +| 明明需要多个工具却只用一个 | 结果更慢,也不够全面 | 组合使用:智能体做分析 → 技能做执行 → MCP 做集成 | +| 提交前不做审查 | 安全问题或 bug 更容易漏进代码库 | 总是运行 `/review`,或者使用 [pre-commit hook](#workflow-2-code-review-automation-optional) | +| 忘记把工作流共享给团队 | 每个人都在重复造轮子 | 把模式沉淀到共享的智能体、技能和指令中 | + +
+ +--- + +# 总结 + +## 🔑 关键要点 + +1. **集成胜于孤立**:把工具组合起来,才能获得最大收益 +2. **上下文优先**:分析前先收集必要上下文 +3. **智能体负责分析,技能负责执行**:针对任务选对工具 +4. **自动化重复工作**:hooks 和脚本会成倍提高你的效率 +5. **把工作流文档化**:可共享的模式能让整个团队受益 + +> 📋 **快速参考**:请参阅 [GitHub Copilot CLI command reference](https://docs.github.com/en/copilot/reference/cli-command-reference) 获取完整命令和快捷键列表。 + +--- + +## 🎓 课程完成! + +恭喜,你已经学会了: + +| 章节 | 你学到的内容 | +|---------|-------------------| +| 00 | Copilot CLI 安装与快速开始 | +| 01 | 三种交互模式 | +| 02 | 使用 @ 语法管理上下文 | +| 03 | 开发工作流 | +| 04 | 专用智能体 | +| 05 | 可扩展技能 | +| 06 | 通过 MCP 建立外部连接 | +| 07 | 统一的生产级工作流 | + +现在,你已经具备把 GitHub Copilot CLI 当作真正效率放大器来使用的能力。 + +## ➡️ 接下来做什么 + +你的学习不会停在这里: + +1. **每天练习**:在真实工作中使用 Copilot CLI +2. **构建自定义工具**:为你的具体需求创建智能体和技能 +3. **分享知识**:帮助你的团队采用这些工作流 +4. **持续关注更新**:跟进 GitHub Copilot 的新功能 + +### 资源 + +- [GitHub Copilot CLI Documentation](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) +- [MCP Server Registry](https://github.com/modelcontextprotocol/servers) +- [Community Skills](https://github.com/topics/copilot-skill) + +--- + +**做得很好。现在去真正做点东西吧。** + +**[← 返回第 06 章](../06-mcp-servers/README.zh-CN.md)** | **[返回课程首页 →](../README.zh-CN.md)** \ No newline at end of file diff --git a/README.md b/README.md index 1d9ae0d..08dc403 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,8 @@ 🎯 [What You'll Learn](#what-youll-learn)   ✅ [Prerequisites](#prerequisites)   🤖 [Copilot Family](#understanding-the-github-copilot-family)   📚 [Course Structure](#course-structure)   📋 [Command Reference](#-github-copilot-cli-command-reference) +· English · [简体中文](./README.zh-CN.md) · + # GitHub Copilot CLI for Beginners > **✨ Learn to supercharge your development workflow with AI-powered command-line assistance.** diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..eb17930 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,110 @@ +![GitHub Copilot CLI 初学者教程](./images/copilot-banner.png) + +[![许可证: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](./LICENSE)  +[![在 GitHub Codespaces 中打开项目](https://img.shields.io/badge/Codespaces-Open-blue?style=flat-square&logo=github)](https://codespaces.new/github/copilot-cli-for-beginners?hide_repo_select=true&ref=main&quickstart=true)  +[![Copilot CLI 官方文档](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  +[![加入 AI Foundry Discord](https://img.shields.io/badge/Discord-AI_Community-blue?style=flat-square&logo=discord&color=5865f2&logoColor=fff)](https://aka.ms/foundry/discord) + +🎯 [你将学到什么](#what-youll-learn)   ✅ [先决条件](#prerequisites)   🤖 [Copilot 家族](#understanding-the-github-copilot-family)   📚 [课程结构](#course-structure)   📋 [命令参考](#github-copilot-cli-command-reference) + +· [English](./README.md) · [简体中文](./README.zh-CN.md) · + +# GitHub Copilot CLI 初学者教程 + +> **✨ 学习如何通过 AI 驱动的命令行助手,全面提升你的开发工作流。** + +GitHub Copilot CLI 将 AI 助手直接带到你的终端。你无需在浏览器或代码编辑器之间来回切换,就可以在命令行中提问、生成功能完整的应用、评审代码、生成测试并排查问题。 + +把它想象成一位 24/7 在线、经验丰富的同事: 能阅读你的代码,解释令人困惑的模式,并帮助你更高效地完成工作。 + +本课程适合以下人群: + +- 想在命令行中使用 AI 的**软件开发者** +- 偏好键盘驱动工作流、而不是 IDE 集成的**终端用户** +- 希望统一 AI 辅助代码评审和开发实践的**团队** + + + + GitHub Copilot Dev Days - 查找或举办活动 + + + + + +## 🎯 你将学到什么 + +这门实战课程会带你从零开始,快速上手 GitHub Copilot CLI 并实现高效产出。你将在所有章节中围绕同一个 Python 图书收藏应用持续实践,并通过 AI 辅助工作流逐步改进它。完成课程后,你将能够自信地在终端中使用 AI 进行代码评审、测试生成、问题调试与工作流自动化。 + +**无需 AI 经验。** 只要你会使用终端,就能学会本课程内容。 + +**非常适合:** 开发者、学生,以及任何有软件开发经验的人。 + + + +## ✅ 先决条件 + +开始前,请确保你具备: + +- **GitHub 账号**: [免费创建](https://github.com/signup)
+- **GitHub Copilot 权限**: [免费方案](https://github.com/features/copilot/plans)、[月度订阅](https://github.com/features/copilot/plans) 或 [面向学生/教师的免费权益](https://education.github.com/pack)
+- **终端基础**: 熟悉 `cd`、`ls` 等命令以及基础命令执行 + + + +## 🤖 了解 GitHub Copilot 家族 + +GitHub Copilot 已发展为一整套 AI 产品。下面是各产品的运行位置与定位: + +| 产品 | 运行位置 | 描述 | +|---------|---------------|----------| +| [**GitHub Copilot CLI**](https://docs.github.com/copilot/how-tos/copilot-cli/cli-getting-started)
(本课程) | 你的终端 | 原生命令行 AI 编程助手 | +| [**GitHub Copilot**](https://docs.github.com/copilot) | VS Code、Visual Studio、JetBrains 等 | Agent 模式、聊天、行内建议 | +| [**GitHub.com 上的 Copilot**](https://github.com/copilot) | GitHub | 沉浸式仓库对话、创建代理等功能 | +| [**GitHub Copilot 编码代理**](https://docs.github.com/copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks) | GitHub | 将 Issue 分配给代理并接收 PR | + +本课程聚焦 **GitHub Copilot CLI**,让 AI 能力直接进入你的终端工作流。 + + + +## 📚 课程结构 + +![GitHub Copilot CLI 学习路径](images/learning-path.png) + +| 章节 | 标题 | 你将构建的内容 | +|:-------:|-------|-------------------| +| 00 | 🚀 [快速开始](./00-quick-start/README.zh-CN.md) | 安装与验证 | +| 01 | 👋 [第一步](./01-setup-and-first-steps/README.zh-CN.md) | 现场演示 + 三种交互模式 | +| 02 | 🔍 [上下文与会话](./02-context-conversations/README.zh-CN.md) | 多文件项目分析 | +| 03 | ⚡ [开发工作流](./03-development-workflows/README.zh-CN.md) | 代码评审、调试、测试生成 | +| 04 | 🤖 [创建专用 AI 助手](./04-agents-custom-instructions/README.zh-CN.md) | 适配你工作流的自定义代理 | +| 05 | 🛠️ [自动化重复任务](./05-skills/README.zh-CN.md) | 自动加载的 Skills | +| 06 | 🔌 [连接 GitHub、数据库与 API](./06-mcp-servers/README.zh-CN.md) | MCP 服务器集成 | +| 07 | 🎯 [综合实战](./07-putting-it-together/README.zh-CN.md) | 完整功能工作流 | + +## 📖 课程如何进行 + +每章都遵循同一学习节奏: + +1. **真实世界类比**: 通过熟悉的比较理解概念 +2. **核心概念**: 掌握关键知识点 +3. **动手示例**: 运行真实命令并查看结果 +4. **练习任务**: 巩固你学到的内容 +5. **下一步**: 预览后续章节 + +**示例代码可直接运行。** 本课程中的每个 copilot 文本块都可以复制到终端中执行。 + + + +## 📋 GitHub Copilot CLI 命令参考 + +查阅 **[GitHub Copilot CLI 命令参考](https://docs.github.com/en/copilot/reference/cli-command-reference)**,可快速找到命令与快捷键,帮助你更高效地使用 Copilot CLI。 + +## 🙋 获取帮助 + +- 🐛 **发现 Bug?** [提交 Issue](https://github.com/github/copilot-cli-for-beginners/issues) +- 🤝 **想参与贡献?** 欢迎提交 PR! +- 📚 **官方文档:** [GitHub Copilot CLI Documentation](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) + +## 许可证 + +本项目基于 MIT 开源许可证发布。完整条款请参阅 [LICENSE](./LICENSE) 文件。 diff --git a/appendices/README.zh-CN.md b/appendices/README.zh-CN.md new file mode 100644 index 0000000..555297b --- /dev/null +++ b/appendices/README.zh-CN.md @@ -0,0 +1,12 @@ +# 附录 + +这些附录涵盖了对核心课程内容的补充主题。它们属于可选阅读,适用于你在需要特定能力时查阅。 + +| 附录 | 说明 | 前置章节 | +|----------|-------------|--------------| +| [附加上下文功能](additional-context.zh-CN.md) | 使用图片与多目录权限协作 | 第 02 章 | +| [CI/CD 集成](ci-cd-integration.zh-CN.md) | 用于自动化评审的 GitHub Actions 工作流 | 第 07 章 | + +--- + +**[← 返回课程首页](../README.zh-CN.md)** diff --git a/appendices/additional-context.zh-CN.md b/appendices/additional-context.zh-CN.md new file mode 100644 index 0000000..2897e35 --- /dev/null +++ b/appendices/additional-context.zh-CN.md @@ -0,0 +1,137 @@ +# 附加上下文功能 + +> 📖 **前置要求**: 阅读本附录前,请先完成 [第 02 章: 上下文与会话](../02-context-conversations/README.zh-CN.md)。 + +本附录介绍两个附加上下文能力: 使用图片,以及管理跨多个目录的权限。 + +--- + +## 使用图片 + +你可以通过 `@` 语法在会话中引入图片。Copilot 可以分析截图、设计稿、图表以及其他可视化内容。 + +### 基础图片引用 + +```bash +copilot + +> @screenshot.png 这个 UI 里发生了什么? + +# Copilot 会分析图片并回复 + +> @mockup.png @current-design.png 对比这两个设计 + +# 你也可以拖拽图片或从剪贴板粘贴 +``` + +### 支持的图片格式 + +| 格式 | 最适用场景 | +|--------|----------| +| PNG | 截图、UI 设计稿、示意图 | +| JPG/JPEG | 照片、复杂图像 | +| GIF | 简单图示(仅第一帧) | +| WebP | 网页截图 | + +### 图片实战场景 + +**1. UI 调试** +```bash +> @bug-screenshot.png 按钮没有正确对齐。可能是什么 CSS 导致的? +``` + +**2. 设计落地实现** +```bash +> @figma-export.png 按这个设计写出对应的 HTML 和 Tailwind CSS +``` + +**3. 报错分析** +```bash +> @error-screenshot.png 这个报错是什么意思?我该怎么修复? +``` + +**4. 架构评审** +```bash +> @whiteboard-diagram.png 把这个架构图转换成可放进文档的 Mermaid 图 +``` + +**5. 前后版本对比** +```bash +> @before.png @after.png 这两个 UI 版本之间有什么变化? +``` + +### 图片与代码结合 + +当图片与代码上下文一起使用时,效果会更强: + +```bash +copilot + +> @screenshot-of-bug.png @src/components/Header.jsx +> 截图里的 header 看起来不对。代码里是什么原因导致的? +``` + +### 图片使用建议 + +- **裁剪截图**: 仅保留相关区域(可节省上下文 token) +- **提高对比度**: 让你希望分析的 UI 元素更清晰 +- **必要时标注**: 上传前可圈出或高亮问题区域 +- **一图一概念**: 多图可用,但尽量保持聚焦 + +--- + +## 权限模式 + +默认情况下,Copilot 只能访问当前目录下的文件。若需访问其他位置的文件,你需要显式授权。 + +### 添加目录 + +```bash +# 将一个目录加入允许列表 +copilot --add-dir /path/to/other/project + +# 添加多个目录 +copilot --add-dir ~/workspace --add-dir /tmp +``` + +### 允许所有路径 + +```bash +# 完全关闭路径限制(谨慎使用) +copilot --allow-all-paths +``` + +### 在会话内授权 + +```bash +copilot + +> /add-dir /path/to/other/project +# 现在你可以引用该目录中的文件 + +> /list-dirs +# 查看所有已允许目录 +``` + +### 用于自动化 + +```bash +# 为非交互脚本启用全部权限 +copilot -p "Review @src/" --allow-all + +# 或者使用更易记的别名 +copilot -p "Review @src/" --yolo +``` + +### 何时需要多目录访问 + +以下是常见场景: + +1. **Monorepo 开发** - 跨 package 对比代码 +2. **跨项目重构** - 更新共享库 +3. **文档工程** - 引用多个代码库 +4. **迁移工作** - 对比旧实现与新实现 + +--- + +**[← 返回第 02 章](../02-context-conversations/README.zh-CN.md)** | **[返回附录](README.zh-CN.md)** diff --git a/appendices/ci-cd-integration.zh-CN.md b/appendices/ci-cd-integration.zh-CN.md new file mode 100644 index 0000000..9b0c42a --- /dev/null +++ b/appendices/ci-cd-integration.zh-CN.md @@ -0,0 +1,199 @@ +# CI/CD 集成 + +> 📖 **前置要求**: 阅读本附录前,请先完成 [第 07 章: 综合实战](../07-putting-it-together/README.zh-CN.md)。 +> +> ⚠️ **本附录适用于已有 CI/CD 流水线的团队。** 如果你刚接触 GitHub Actions 或 CI/CD 概念,请先从第 07 章 [代码评审自动化](../07-putting-it-together/README.zh-CN.md#workflow-2-code-review-automation-optional) 中更简单的 pre-commit hook 方案开始。 + +本附录展示如何将 GitHub Copilot CLI 集成到 CI/CD 流水线中,以便在 Pull Request 上自动执行代码评审。 + +--- + +## GitHub Actions 工作流 + +下面的工作流会在 Pull Request 创建或更新时,自动评审变更文件: + +```yaml +# .github/workflows/copilot-review.yml +name: Copilot Review + +on: + pull_request: + types: [opened, synchronize] + +jobs: + review: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # 用于与 main 分支进行比较 + + - name: Install Copilot CLI + run: npm install -g @github/copilot + + - name: Review Changed Files + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # 获取变更的 JS/TS 文件列表 + FILES=$(git diff --name-only origin/main...HEAD | grep -E '\.(js|ts|jsx|tsx)$' || true) + + if [ -z "$FILES" ]; then + echo "No JavaScript/TypeScript files changed" + exit 0 + fi + + echo "# Copilot Code Review" > review.md + echo "" >> review.md + + for file in $FILES; do + echo "Reviewing $file..." + echo "## $file" >> review.md + echo "" >> review.md + + # 使用 --silent 抑制进度输出 + copilot --allow-all -p "Quick security and quality review of @$file. List only critical issues." --silent >> review.md 2>/dev/null || echo "Review skipped" >> review.md + echo "" >> review.md + done + + - name: Post Review Comment + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + const review = fs.readFileSync('review.md', 'utf8'); + + // 仅在有有效内容时发布 + if (review.includes('CRITICAL') || review.includes('HIGH')) { + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: review + }); + } else { + console.log('No critical issues found, skipping comment'); + } +``` + +--- + +## 配置选项 + +### 限定评审范围 + +你可以将评审聚焦到某类问题: + +```yaml +# 仅安全评审 +copilot --allow-all -p "Security review of @$file. Check for: SQL injection, XSS, hardcoded secrets, authentication issues." --silent + +# 仅性能评审 +copilot --allow-all -p "Performance review of @$file. Check for: N+1 queries, memory leaks, blocking operations." --silent +``` + +### 处理大型 PR + +当 PR 文件较多时,建议分批或限制数量: + +```yaml +# 仅处理前 10 个文件 +FILES=$(git diff --name-only origin/main...HEAD | grep -E '\.(js|ts)$' | head -10) + +# 或者对每个文件设置超时 +timeout 60 copilot --allow-all -p "Review @$file" --silent || echo "Review timed out" +``` + +### 团队统一配置 + +为确保团队评审口径一致,可创建共享配置: + +```json +// .copilot/config.json (提交到仓库) +{ + "model": "claude-sonnet-4.5", + "permissions": { + "allowedPaths": ["src/**/*", "tests/**/*"], + "deniedPaths": [".env*", "secrets/**/*", "*.min.js"] + } +} +``` + +--- + +## 可选方案: PR 评审机器人 + +如果你需要更高级的评审工作流,可考虑使用 Copilot coding agent: + +```yaml +# .github/workflows/copilot-agent-review.yml +name: Request Copilot Review + +on: + pull_request: + types: [opened, ready_for_review] + +jobs: + request-review: + runs-on: ubuntu-latest + steps: + - name: Request Copilot Review + uses: actions/github-script@v7 + with: + script: | + await github.rest.pulls.requestReviewers({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: context.issue.number, + reviewers: ['copilot[bot]'] + }); +``` + +--- + +## CI/CD 集成最佳实践 + +1. **使用 `--silent` 参数** - 抑制进度输出,让日志更干净 +2. **设置超时** - 避免卡住的评审阻塞流水线 +3. **按文件类型过滤** - 仅评审相关文件(跳过生成代码、依赖等) +4. **关注速率限制** - 大型 PR 评审应适当分散调用 +5. **优雅失败** - 评审失败时记录并继续,不阻塞合并 + +--- + +## 故障排查 + +### CI 中出现 "Authentication failed" + +请确保工作流具备正确权限: + +```yaml +permissions: + contents: read + pull-requests: write + issues: write +``` + +### 评审超时 + +提高超时或缩小评审范围: + +```bash +timeout 120 copilot --allow-all -p "Quick review of @$file - critical issues only" --silent +``` + +### 大文件触发 token 限制 + +跳过超大文件: + +```bash +if [ $(wc -l < "$file") -lt 500 ]; then + copilot --allow-all -p "Review @$file" --silent +else + echo "Skipping $file (too large)" +fi +``` + +--- + +**[← 返回第 07 章](../07-putting-it-together/README.zh-CN.md)** | **[返回附录](README.zh-CN.md)**