From 7dbd501cd6a2c0b8d7a14a8cfcf13e21db471c1b Mon Sep 17 00:00:00 2001 From: Justin Yoo Date: Wed, 13 May 2026 17:06:07 +0900 Subject: [PATCH 1/8] feat(localization): add complete Japanese (ja-JP) translation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds full Japanese localization for the GitHub Copilot CLI for Beginners course under localization/ja-jp/. Files translated (13 total): - localization/ja-jp/README.md — course index - localization/ja-jp/00-quick-start/README.md - localization/ja-jp/01-setup-and-first-steps/README.md - localization/ja-jp/02-context-conversations/README.md - localization/ja-jp/03-development-workflows/README.md - localization/ja-jp/04-agents-custom-instructions/README.md - localization/ja-jp/05-skills/README.md - localization/ja-jp/06-mcp-servers/README.md - localization/ja-jp/06-mcp-servers/mcp-custom-server.md - localization/ja-jp/07-putting-it-together/README.md - localization/ja-jp/appendices/README.md - localization/ja-jp/appendices/additional-context.md - localization/ja-jp/appendices/ci-cd-integration.md Translation conventions: - Polite form (です・ます調) throughout - Brand names, code blocks, file paths, and identifiers preserved as-is - Relative paths adjusted for localization/ja-jp/ depth (../../.. prefix) - Sibling chapter links kept as localized references Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- localization/ja-jp/00-quick-start/README.md | 290 ++++++ .../ja-jp/01-setup-and-first-steps/README.md | 690 +++++++++++++ .../ja-jp/02-context-conversations/README.md | 908 ++++++++++++++++ .../ja-jp/03-development-workflows/README.md | 971 +++++++++++++++++ .../04-agents-custom-instructions/README.md | 783 ++++++++++++++ localization/ja-jp/05-skills/README.md | 886 ++++++++++++++++ localization/ja-jp/06-mcp-servers/README.md | 974 ++++++++++++++++++ .../ja-jp/06-mcp-servers/mcp-custom-server.md | 176 ++++ .../ja-jp/07-putting-it-together/README.md | 512 +++++++++ localization/ja-jp/README.md | 110 ++ localization/ja-jp/appendices/README.md | 12 + .../ja-jp/appendices/additional-context.md | 140 +++ .../ja-jp/appendices/ci-cd-integration.md | 199 ++++ 13 files changed, 6651 insertions(+) create mode 100644 localization/ja-jp/00-quick-start/README.md create mode 100644 localization/ja-jp/01-setup-and-first-steps/README.md create mode 100644 localization/ja-jp/02-context-conversations/README.md create mode 100644 localization/ja-jp/03-development-workflows/README.md create mode 100644 localization/ja-jp/04-agents-custom-instructions/README.md create mode 100644 localization/ja-jp/05-skills/README.md create mode 100644 localization/ja-jp/06-mcp-servers/README.md create mode 100644 localization/ja-jp/06-mcp-servers/mcp-custom-server.md create mode 100644 localization/ja-jp/07-putting-it-together/README.md create mode 100644 localization/ja-jp/README.md create mode 100644 localization/ja-jp/appendices/README.md create mode 100644 localization/ja-jp/appendices/additional-context.md create mode 100644 localization/ja-jp/appendices/ci-cd-integration.md diff --git a/localization/ja-jp/00-quick-start/README.md b/localization/ja-jp/00-quick-start/README.md new file mode 100644 index 00000000..237287b0 --- /dev/null +++ b/localization/ja-jp/00-quick-start/README.md @@ -0,0 +1,290 @@ +![第 00 章: クイックスタート](../../../00-quick-start/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」と表示される場合は、無料オプションを利用するか、プランに加入するか、アクセスを提供する組織に参加する必要があります。 + +--- + +## インストール + +> ⏱️ **所要時間の目安**: インストールに 2〜5 分、認証に さらに 1〜2 分かかります。 + +### GitHub Codespaces(セットアップ不要) + +前提条件のインストールを避けたい場合は、GitHub Codespaces を使用できます。Copilot CLI がすぐに使える状態で用意されており(サインインは必要)、Python と pytest も事前インストールされています。 + +1. [このリポジトリをフォーク](https://github.com/github/copilot-cli-for-beginners/fork)して自分の GitHub アカウントに追加する +2. **Code** > **Codespaces** > **Create codespace on main** を選択する +3. コンテナのビルドが完了するまで数分待つ +4. 準備完了!Codespace 環境でターミナルが自動的に開きます。 + +> 💡 **Codespace での確認**: `cd samples/book-app-project && python book_app.py help` を実行して、Python とサンプルアプリが動作していることを確認しましょう。 + +### ローカルインストール + +ローカルマシンでコースサンプルと一緒に Copilot CLI を動かしたい場合は、以下の手順に従ってください。 + +1. コースサンプルをマシンに取得するため、リポジトリをクローンします。 + + ```bash + git clone https://github.com/github/copilot-cli-for-beginners + cd copilot-cli-for-beginners + ``` + +2. 以下のいずれかの方法で Copilot CLI をインストールします。 + + > 💡 **どれを選べばよいか迷ったら?** Node.js がインストールされている場合は `npm` を使うのが手軽です。それ以外は自分のシステムに合った方法を選んでください。 + + ### すべてのプラットフォーム(npm) + + ```bash + # Node.js がインストールされていれば、これが最も手軽な方法です + npm install -g @github/copilot + ``` + + ### macOS/Linux(Homebrew) + + ```bash + brew install copilot-cli + ``` + + ### Windows(WinGet) + + ```bash + winget install GitHub.Copilot + ``` + + ### macOS/Linux(インストールスクリプト) + + ```bash + curl -fsSL https://gh.io/copilot-install | bash + ``` + +
+オプション: シェルのタブ補完を有効にする + +シェルのタブ補完を使うと、**Tab** キーを押して `copilot` のサブコマンド、コマンドオプション、一部のオプション値を補完できます。これはオプションですが、CLI に慣れてきたら便利です。 + +Copilot CLI は現在 Bash、Zsh、Fish の補完スクリプトをサポートしています。 + +```shell +# Bash、現在のセッションのみ +source <(copilot completion bash) + +# Bash、Linux で永続化 +copilot completion bash | sudo tee /etc/bash_completion.d/copilot + +# Zsh +copilot completion zsh > "${fpath[1]}/_copilot" + +# Fish +copilot completion fish > ~/.config/fish/completions/copilot.fish +``` + +永続的な補完を追加した後はシェルを再起動してください。Windows では PowerShell で Copilot CLI を実行できますが、`copilot completion` は現在 Bash、Zsh、Fish のみをサポートしています。 + +
+ +--- + +## 認証 + +`copilot-cli-for-beginners` リポジトリのルートでターミナルを開き、CLI を起動してフォルダへのアクセスを許可します。 + +```bash +copilot +``` + +リポジトリが含まれるフォルダを信頼するかどうか確認されます(まだ信頼していない場合)。1 回だけ信頼するか、今後のすべてのセッションで信頼するかを選べます。 + +Copilot CLI でフォルダ内のファイルを信頼する + +フォルダを信頼した後、GitHub アカウントでサインインできます。 + +``` +> /login +``` + +**次に何が起こるか:** + +1. Copilot CLI がワンタイムコード(例: `ABCD-1234`)を表示する +2. ブラウザが GitHub のデバイス認証ページを開く。まだ GitHub にサインインしていない場合はサインインする。 +3. プロンプトが表示されたらコードを入力する +4. 「Authorize」を選択して GitHub Copilot CLI のアクセスを許可する +5. ターミナルに戻ると、サインイン完了です! + +デバイス認証フロー - ターミナルのログインからサインイン確認までの 5 ステップ + +*デバイス認証フロー: ターミナルでコードを生成し、ブラウザで確認すると Copilot CLI が認証されます。* + +**ヒント**: サインインはセッションをまたいで持続します。トークンが期限切れになるか明示的にサインアウトするまで、1 回だけ行えば十分です。 + +--- + +## 動作確認 + +### ステップ 1: Copilot CLI をテストする + +サインインできたので、Copilot CLI が動作しているか確認しましょう。ターミナルでまだ CLI を起動していない場合は起動します。 + +```bash +> Say hello and tell me what you can help with +``` + +レスポンスを受け取ったら、CLI を終了できます。 + +```bash +> /exit +``` + +--- + +
+🎬 実際の動作を見てみましょう! + +![Hello Demo](../../../00-quick-start/images/hello-demo.gif) + +*デモの出力は異なる場合があります。モデル、ツール、レスポンスはここに表示されているものと異なります。* + +
+ +--- + +**期待される出力**: Copilot CLI の機能を説明する親しみやすいレスポンス。 + +### ステップ 2: サンプルブックアプリを実行する + +コースには、CLI を使って探索・改善していくサンプルアプリが提供されています。*(コードは /samples/book-app-project で確認できます)*。始める前に、*Python ブックコレクションターミナルアプリ*が動作することを確認してください。システムに応じて `python` または `python3` を実行します。 + +> **注意:** コース全体の主な例は Python(`samples/book-app-project`)を使用しているため、ローカルオプションを選んだ場合は [Python 3.10+](https://www.python.org/downloads/) が必要です(Codespace にはすでにインストールされています)。JavaScript(`samples/book-app-project-js`)および C#(`samples/book-app-project-cs`)バージョンも用意されています。各サンプルには、その言語でアプリを実行するための README が含まれています。 + +```bash +cd samples/book-app-project +python book_app.py list +``` + +**期待される出力**: 「The Hobbit」「1984」「Dune」などを含む 5 冊の本のリスト。 + +### ステップ 3: ブックアプリで Copilot CLI を試す + +(ステップ 2 を実行した場合は)まずリポジトリのルートに戻ります。 + +```bash +cd ../.. # 必要に応じてリポジトリのルートに戻る +copilot +> What does @samples/book-app-project/book_app.py do? +``` + +**期待される出力**: ブックアプリの主な関数とコマンドの概要。 + +エラーが表示された場合は、下記の[トラブルシューティング](#troubleshooting)セクションを確認してください。 + +完了したら Copilot CLI を終了できます。 + +```bash +> /exit +``` + +--- + +## ✅ 準備完了! + +インストールはこれで完了です。第 01 章から本当の楽しみが始まります。そこでは以下を行います。 + +- AI がブックアプリをレビューしてコード品質の問題を即座に見つける様子を見る +- Copilot CLI を使う 3 つの方法を学ぶ +- 平易な日本語からコードを生成する + +**[第 01 章: はじめの一歩に進む →](../01-setup-and-first-steps/README.md)** + +--- + +## トラブルシューティング {#troubleshooting} + +### 「copilot: command not found」 + +CLI がインストールされていません。別のインストール方法を試してください。 + +```bash +# brew が失敗した場合は npm を試す: +npm install -g @github/copilot + +# またはインストールスクリプト: +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) に手動でアクセスし、ターミナルに表示されたコードを入力してください。 + +### トークンの有効期限切れ + +`/login` を再度実行するだけです。 + +```bash +copilot +> /login +``` + +### まだ解決できない場合 + +- [GitHub Copilot CLI ドキュメント](https://docs.github.com/copilot/concepts/agents/about-copilot-cli)を確認する +- [GitHub Issues](https://github.com/github/copilot-cli/issues) を検索する + +--- + +## 🔑 重要なポイント + +1. **GitHub Codespace はすぐに始める最短の方法** - Python、pytest、GitHub Copilot CLI がすべてプリインストールされており、デモにすぐ飛び込めます +2. **複数のインストール方法** - システムに合ったものを選んでください(Homebrew、WinGet、npm、またはインストールスクリプト) +3. **1 回限りの認証** - ログインはトークンが期限切れになるまで持続します +4. **ブックアプリが動作する** - コース全体を通して `samples/book-app-project` を使用します + +> 📚 **公式ドキュメント**: インストールオプションと要件については [Copilot CLI のインストール](https://docs.github.com/copilot/how-tos/copilot-cli/cli-getting-started)を参照してください。 + +> 📋 **クイックリファレンス**: コマンドとキーボードショートカットの完全なリストは [GitHub Copilot CLI コマンドリファレンス](https://docs.github.com/en/copilot/reference/cli-command-reference)をご覧ください。 + +--- + +**[第 01 章: はじめの一歩に進む →](../01-setup-and-first-steps/README.md)** diff --git a/localization/ja-jp/01-setup-and-first-steps/README.md b/localization/ja-jp/01-setup-and-first-steps/README.md new file mode 100644 index 00000000..2819619b --- /dev/null +++ b/localization/ja-jp/01-setup-and-first-steps/README.md @@ -0,0 +1,690 @@ +![第 01 章: はじめの一歩](../../../01-setup-and-first-steps/images/chapter-header.png) + +> **AI がバグを即座に発見し、わかりにくいコードを説明し、動作するスクリプトを生成する様子をご覧ください。そして GitHub Copilot CLI の 3 つの使い方を学びましょう。** + +この章から本当の楽しさが始まります!GitHub Copilot CLI を「シニアエンジニアをスピードダイヤルに登録している」と表現する開発者の理由を、実際に体験していただきます。AI がセキュリティバグを数秒で見つけ、複雑なコードを平易な言葉で説明し、動作するスクリプトを即座に生成する様子を見た後、3 つのインタラクションモード(インタラクティブ、プラン、プログラマティック)をマスターして、どのタスクにどのモードを使えばよいか正確に理解しましょう。 + +> ⚠️ **前提条件**: 先に **[第 00 章: クイックスタート](../00-quick-start/README.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 セッション内で入力するプロンプトです。`>` プレフィックスのない行は、ターミナルで実行するシェルコマンドです。 + +> 💡 **出力例について**: このコース全体で示すサンプル出力はあくまで例示用です。Copilot CLI のレスポンスは毎回異なるため、文言、フォーマット、詳細度は異なります。正確なテキストではなく、返される*情報の種類*に注目してください。 + +### デモ 1: 数秒でコードレビュー + +コースには、意図的にコード品質の問題が含まれたサンプルファイルが含まれています。ローカルマシンで作業していてまだリポジトリをクローンしていない場合は、以下の `git clone` コマンドを実行し、`copilot-cli-for-beginners` フォルダに移動してから `copilot` コマンドを実行してください。 + +```bash +# ローカルで作業していてまだクローンしていない場合 +git clone https://github.com/github/copilot-cli-for-beginners +cd copilot-cli-for-beginners + +# Copilot を起動する +copilot +``` + +インタラクティブな Copilot CLI セッションに入ったら、以下を実行します。 + +``` +> Review @samples/book-app-project/book_app.py for code quality issues and suggest improvements +``` + +> 💡 **`@` 記号は何に使うのか?** `@` 記号は Copilot CLI にファイルを読むよう指示します。これについては第 02 章で詳しく学びます。今はコマンドをそのままコピーするだけで大丈夫です。 + +--- + +
+🎬 実際の動作を見てみましょう! + +![コードレビューデモ](../../../01-setup-and-first-steps/images/code-review-demo.gif) + +*デモの出力は異なる場合があります。モデル、ツール、レスポンスはここに表示されているものと異なります。* + +
+ +--- + +**ポイント**: 数秒でプロフェッショナルなコードレビューが完成。手動レビューではもっと時間がかかります! + +--- + +### デモ 2: わかりにくいコードを説明する + +コードを見てもよくわからないことがありますか?Copilot CLI セッションで試してみましょう。 + +``` +> Explain what @samples/book-app-project/books.py does in simple terms +``` + +--- + +
+🎬 実際の動作を見てみましょう! + +![コード説明デモ](../../../01-setup-and-first-steps/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 分かけて検索しなければならないような関数が必要ですか?セッションを続けて試してみましょう。 + +``` +> Write a Python function that takes a list of books and returns statistics: + total count, number read, number unread, oldest and newest book +``` + +--- + +
+🎬 実際の動作を見てみましょう! + +![コード生成デモ](../../../01-setup-and-first-steps/images/generate-code-demo.gif) + +*デモの出力は異なる場合があります。モデル、ツール、レスポンスはここに表示されているものと異なります。* + +
+ +--- + +**何が起こるか**: 数秒で完全な動作するコードが生成され、コピーして実行できます。 + +探索し終わったら、セッションを終了しましょう。 + +``` +> /exit +``` + +**ポイント**: 即座に結果が得られ、一つのセッションを通じて作業が完了しました。 + +--- + +# モードとコマンド + +Copilot CLI のモードとコマンドを表す光るスクリーン、ダイヤル、イコライザーを備えた未来的なコントロールパネル + +Copilot CLI でできることを体験しました。次は、これらの機能を効果的に使う*方法*を理解しましょう。重要なのは、状況に応じて 3 つのインタラクションモードのどれを使うかを知ることです。 + +> 💡 **注意**: Copilot CLI には、入力を待たずにタスクを進める**オートパイロット**モードもあります。強力ですが、フルアクセス権の付与が必要で、プレミアムリクエストを自律的に使用します。このコースでは下記の 3 つのモードに焦点を当てます。基本に慣れてからオートパイロットを紹介します。 + +--- + +## 🧩 現実世界のたとえ話: 外食する + +GitHub Copilot CLI の使い方を、外食に例えてみましょう。計画から注文まで、状況によって適したアプローチが異なります。 + +| モード | 外食のたとえ | 使う場面 | +|------|----------------|-------------| +| **プラン** | レストランへの GPS ルート | 複雑なタスク - ルートを確認し、経由地をチェックし、計画に合意してから出発 | +| **インタラクティブ** | ウェイターと話す | 探索と反復 - 質問し、カスタマイズし、リアルタイムフィードバックを得る | +| **プログラマティック** | ドライブスルーで注文 | 素早い特定タスク - 環境から離れずに素早く結果を得る | + +外食のように、どのアプローチが適切か自然にわかるようになります。 + +GitHub Copilot CLI の 3 つの使い方 - プランモード(GPS ルート)、インタラクティブモード(ウェイターと話す)、プログラマティックモード(ドライブスルー) + +*タスクに応じてモードを選択: まず計画するならプラン、対話型の共同作業ならインタラクティブ、素早い一発勝負ならプログラマティック* + +### どのモードから始めればよい? + +**インタラクティブモードから始めましょう。** +- 実験して追加質問ができます +- 会話を通じてコンテキストが自然に積み上がります +- ミスは `/clear` で簡単に修正できます + +慣れてきたら試してみましょう。 +- **プログラマティックモード** (`copilot -p "<プロンプト>"`) - 素早い一発の質問に +- **プランモード** (`/plan`) - コーディング前に詳細な計画が必要な場合に + +--- + +## 3 つのモード + +### モード 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** を押してプランモードに切り替えます。 + +```bash +copilot + +> /plan Add a "mark as read" command to the book app +``` + +> 💡 **ヒント**: **Shift+Tab** でモードが切り替わります: インタラクティブ → プラン → オートパイロット。インタラクティブセッション中にいつでも押してコマンドを入力せずにモードを切り替えられます。 + +`--plan` フラグを使って Copilot CLI をプランモードで直接起動することもできます。 + +```bash +copilot --plan +``` + +**プランモードの出力:**(実際の出力は異なる場合があります) + +``` +📋 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` を試してみましょう。プランモードは、シンプルな機能からフルアプリケーションまでスケールします。 + +> 📚 **オートパイロットモード**: Shift+Tab で **オートパイロット**という 3 番目のモードに切り替わることに気づいたかもしれません。オートパイロットモードでは、各ステップの後に入力を待たずに計画全体を実行します。これは「タスクをお願いして、終わったら教えて」と同僚に伝えるようなものです。典型的なワークフローは「計画 → 承認 → オートパイロット」で、まず計画を上手に書く必要があります。`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?" +``` + +**重要なポイント**: プログラマティックモードは素早く回答して終了します。会話なし、入力 → 出力のみです。 + +
+📚 さらに進む: スクリプトでのプログラマティックモードの使用(クリックして展開) + +慣れてきたら、シェルスクリプトで `-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` は自分で書いたプロンプトに対して、信頼できるディレクトリでのみ使用してください。信頼できない入力や機密性の高いディレクトリでは絶対に使用しないでください。 + +
+ +--- + +## 主要なスラッシュコマンド + +Copilot CLI を使い始める際にまず覚えておくべきコマンドです。 + +| コマンド | 機能 | 使う場面 | +|---------|--------------|-------------| +| `/ask` | 会話履歴に影響を与えずに素早く質問する | 現在のタスクを中断せずに素早く答えが欲しいとき | +| `/clear` | 会話をクリアして最初からやり直す | 話題を切り替えるとき | +| `/help` | 利用可能なコマンドをすべて表示する | コマンドを忘れたとき | +| `/model` | AI モデルを表示または切り替える | AI モデルを変更したいとき | +| `/plan` | コーディング前に作業を計画する | 複雑な機能の場合 | +| `/research` | GitHub とウェブソースを使って深い調査をする | コーディング前にトピックを調査する必要があるとき | +| `/exit` | セッションを終了する | 作業が終わったとき | + +> 💡 **`/ask` と通常のチャットの違い**: 通常、送るすべてのメッセージは継続的な会話の一部となり、将来のレスポンスに影響します。`/ask` は「オフレコード」のショートカットで、`/ask What does YAML mean?` のような一発の質問に最適です。セッションのコンテキストを汚染しません。 + +> 💡 **タブ補完**: スラッシュコマンドを入力するときに **Tab** を押すと、コマンド名の自動補完や利用可能なサブコマンドと引数のサイクルができます。コマンドの正確な名前を覚えていないときに特に便利です。 + +これで始め方はわかりました!慣れてきたら、追加のコマンドを探索してみましょう。 + +> 📚 **公式ドキュメント**: コマンドとフラグの完全なリストは [CLI コマンドリファレンス](https://docs.github.com/copilot/reference/cli-command-reference)をご覧ください。 + +
+📚 追加コマンド(クリックして展開) + +> 💡 上記の主要コマンドは日常的な使用の多くをカバーします。このリファレンスは、さらに探索したいときのためにあります。 + +### エージェント環境 + +| コマンド | 機能 | +|---------|--------------| +| `/agent` | 利用可能なエージェントを閲覧・選択する | +| `/env` | 読み込まれた環境の詳細を表示する(有効な指示、MCP サーバー、スキル、エージェント、プラグイン) | +| `/init` | リポジトリの Copilot 指示を初期化する | +| `/mcp` | MCP サーバーの設定を管理する | +| `/skills` | 機能強化のためのスキルを管理する | + +> 💡 エージェントは[第 04 章](../04-agents-custom-instructions/README.md)、スキルは[第 05 章](../05-skills/README.md)、MCP サーバーは[第 06 章](../06-mcp-servers/README.md)で説明します。 + +### モデルとサブエージェント + +| コマンド | 機能 | +|---------|--------------| +| `/delegate` | GitHub Copilot クラウドエージェントにタスクを委任する | +| `/fleet` | 複雑なタスクを並列サブタスクに分割して高速化する | +| `/model` | AI モデルを表示または切り替える | +| `/tasks` | バックグラウンドのサブエージェントとデタッチされたシェルセッションを表示する | + +### コード + +| コマンド | 機能 | +|---------|--------------| +| `/diff` | 現在のディレクトリで行われた変更をレビューする | +| `/pr` | 現在のブランチのプルリクエストを操作する | +| `/research` | GitHub とウェブソースを使って深い調査を実行する | +| `/review` | コードレビューエージェントを実行して変更を分析する | +| `/terminal-setup` | 複数行入力サポートを有効にする(shift+enter と ctrl+enter) | + +### アクセス許可 + +| コマンド | 機能 | +|---------|--------------| +| `/add-dir <ディレクトリ>` | 許可リストにディレクトリを追加する | +| `/allow-all [on\|off\|show]` | すべてのアクセス許可プロンプトを自動承認する。`on` で有効化、`off` で無効化、`show` で現在の状態を確認 | +| `/yolo` | `/allow-all on` のクイックエイリアス — すべてのアクセス許可プロンプトを自動承認する | +| `/cwd`、`/cd [ディレクトリ]` | 作業ディレクトリを表示または変更する | +| `/list-dirs` | すべての許可ディレクトリを表示する | + +> ⚠️ **注意して使う**: `/allow-all` と `/yolo` は確認プロンプトをスキップします。信頼できるプロジェクトには便利ですが、信頼できないコードには注意してください。 + +### セッション + +| コマンド | 機能 | +|---------|--------------| +| `/clear` | 現在のセッションを破棄(履歴は保存されない)して新しい会話を開始する | +| `/compact` | コンテキストの使用量を削減するために会話を要約する | +| `/context` | コンテキストウィンドウのトークン使用量と可視化を表示する | +| `/keep-alive` | Copilot CLI がアクティブな間はシステムのスリープを防ぐ — ノートパソコンでの長時間タスクに便利 | +| `/new` | 現在のセッションを終了(履歴に保存して検索・再開可能)して新しい会話を開始する | +| `/resume` | 別のセッションに切り替える(セッション ID または名前を指定可) | +| `/rename` | 現在のセッションの名前を変更する(名前を省略すると自動生成) | +| `/rewind` | タイムラインピッカーを開いて会話の以前の任意の時点にロールバックする | +| `/usage` | セッションの使用メトリクスと統計を表示する | +| `/session` | セッション情報とワークスペースの概要を表示する。`/session delete`、`/session delete `、または `/session delete-all` でセッションを削除 | +| `/share` | セッションを Markdown ファイル、GitHub Gist、またはスタンドアロン HTML ファイルとしてエクスポートする | + +### 表示 + +| コマンド | 機能 | +|---------|--------------| +| `/statusline`(または `/footer`) | セッション下部のステータスバーに表示する項目をカスタマイズする(ディレクトリ、ブランチ、労力、コンテキストウィンドウ、クォータ) | +| `/theme` | ターミナルテーマを表示または設定する | + +### ヘルプとフィードバック + +| コマンド | 機能 | +|---------|--------------| +| `/changelog` | CLI バージョンの変更ログを表示する | +| `/feedback` | GitHub にフィードバックを送信する | +| `/help` | 利用可能なコマンドをすべて表示する | + +### クイックシェルコマンド + +`!` をプレフィックスとして付けることで、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 など)は優れたデフォルトです。高性能で効率的です。高い倍率のモデルはプレミアムリクエストのクォータをより速く消費するので、本当に必要な場合のために取っておきましょう。 + +> 💡 **どのモデルを選べばいいかわからない場合?** モデルピッカーで **`Auto`** を選択すると、Copilot が各セッションに最適なモデルを自動的に選択します。始めたばかりでモデル選択について考えたくない場合に最適なデフォルトです。 + +
+ +--- + +# 練習 + +コードが表示されたモニター、ランプ、コーヒーカップ、ヘッドホンが置かれた居心地の良いデスク + +学んだことを実践する時間です。 + +--- + +## ▶️ 自分で試してみよう + +### インタラクティブな探索 + +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"` を実行する。最初の試みで動作したか確認する。 + +--- + +## 💡 ヒント: ウェブまたはモバイルから CLI セッションを制御する + +GitHub Copilot CLI は**リモートセッション**をサポートしており、ターミナルにいなくても Web ブラウザ(デスクトップまたはモバイル)や GitHub Mobile アプリから実行中の CLI セッションを監視・操作できます。 + +`--remote` フラグでリモートセッションを開始します。 + +```bash +copilot --remote +``` + +Copilot CLI がリンクを表示し、QR コードへのアクセスを提供します。スマートフォンまたはデスクトップのブラウザタブでリンクを開くと、セッションをリアルタイムで確認し、フォローアッププロンプトを送信し、計画を確認し、リモートでエージェントを操作できます。セッションはユーザー固有なので、自分の Copilot CLI セッションにのみアクセスできます。 + +アクティブなセッション内からいつでもリモートアクセスを有効にすることもできます。 + +``` +> /remote +``` + +リモートセッションの詳細は [Copilot CLI ドキュメント](https://docs.github.com/copilot/how-tos/copilot-cli/steer-remotely)をご覧ください。 + +--- + +## 📝 課題 + +### メインチャレンジ: ブックアプリのユーティリティを改善する + +ハンズオン例は `book_app.py` のレビューとリファクタリングに焦点を当てていました。今度は別のファイル `utils.py` で同じスキルを練習しましょう。 + +1. インタラクティブセッションを開始する: `copilot` +2. ファイルの概要を Copilot CLI に頼む: "Summarize @samples/book-app-project/utils.py and explain what each function in this file does" +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. ドキュメント文字列の追加を頼む: "Add a comprehensive docstring to `get_book_details()` with parameter descriptions and return values" +6. コンテキストがプロンプト間でどのように引き継がれるかを観察する。各改善は前のものを積み上げる +7. `/exit` で終了する + +**成功基準**: 入力バリデーション、エラーハンドリング、ドキュメント文字列が追加された改善された `utils.py` ができており、すべてが複数ターンの会話で構築されています。 + +
+💡 ヒント(クリックして展開) + +**試してみるサンプルプロンプト:** +```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()` メソッドを追加するという単一の新しいタスクで 3 つのモードすべてを試してみましょう。 + +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`)を使う | +| `$` や `!` を含むプロンプトを引用符なしで使う | Copilot CLI が見る前にシェルが特殊文字を解釈する | プロンプトを引用符で囲む: `copilot -p "What does $HOME mean?"` | +| 実行中のタスクをキャンセルするために Esc を 1 回押す | 単一の Esc は実行中の作業をキャンセルしなくなった(誤操作防止のため) | Copilot CLI が処理中にキャンセルするには **Esc を 2 回**押す | + +### トラブルシューティング + +**「Model not available」** - サブスクリプションにすべてのモデルが含まれていない場合があります。`/model` で利用可能なものを確認してください。 + +**「Context too long」** - 会話がコンテキストウィンドウをすべて使い切りました。`/clear` でリセットするか、新しいセッションを開始してください。 + +**「Rate limit exceeded」** - 数分待ってから再試行してください。バッチ操作には遅延を入れたプログラマティックモードの使用を検討してください。 + +
+ +--- + +# まとめ + +## 🔑 重要なポイント + +1. **インタラクティブモード**は探索と反復のためのものです - コンテキストは引き継がれます。これまで言ったことを覚えている相手と会話しているようなものです。 +2. **プランモード**は通常、より複雑なタスクのためのものです。実装前にレビューしましょう。 +3. **プログラマティックモード**は自動化のためのものです。インタラクションは不要です。 +4. **主要コマンド**(`/ask`、`/help`、`/clear`、`/plan`、`/research`、`/model`、`/exit`)は日常的な使用のほとんどをカバーします。 + +> 📋 **クイックリファレンス**: コマンドとキーボードショートカットの完全なリストは [GitHub Copilot CLI コマンドリファレンス](https://docs.github.com/en/copilot/reference/cli-command-reference)をご覧ください。 + +--- + +## ➡️ 次のステップ + +3 つのモードを理解したので、次はコードについて Copilot CLI にコンテキストを提供する方法を学びましょう。 + +**[第 02 章: コンテキストと会話](../02-context-conversations/README.md)**では以下を学びます。 + +- ファイルとディレクトリを参照するための `@` 構文 +- `--resume` と `--continue` を使ったセッション管理 +- コンテキスト管理が Copilot CLI を本当に強力にする仕組み + +--- + +**[← コースホームに戻る](../README.md)** | **[第 02 章に進む →](../02-context-conversations/README.md)** diff --git a/localization/ja-jp/02-context-conversations/README.md b/localization/ja-jp/02-context-conversations/README.md new file mode 100644 index 00000000..a7dbbc06 --- /dev/null +++ b/localization/ja-jp/02-context-conversations/README.md @@ -0,0 +1,908 @@ +![第 02 章: コンテキストと会話](../../../02-context-conversations/images/chapter-header.png) + +> **AI がファイルを 1 つずつではなく、コードベース全体を把握できたら?** + +この章では、GitHub Copilot CLI の真の力、「コンテキスト」を解き放ちます。`@` 構文を使ってファイルやディレクトリを参照し、Copilot CLI にコードベースの深い理解を与える方法を学びます。セッションをまたいで会話を維持する方法、数日後に正確に中断した場所から再開する方法、そして複数ファイルにわたる分析が単一ファイルのレビューでは見落とすバグをどのように発見するかを確認します。 + +## 🎯 学習目標 + +この章を終えると、以下ができるようになります。 + +- `@` 構文を使ってファイル、ディレクトリ、画像を参照する +- `--resume` と `--continue` で前のセッションを再開する +- [コンテキストウィンドウ](../../../GLOSSARY.md#context-window)の仕組みを理解する +- 効果的な複数ターンの会話を書く +- マルチプロジェクトワークフローのためのディレクトリアクセス許可を管理する + +> ⏱️ **目安時間**: 約 50 分(20 分読む + 30 分ハンズオン) + +--- + +## 🧩 現実世界のたとえ話: 同僚と働く + +コンテキストが違いをもたらす - コンテキストなしとコンテキストありの比較 + +*同僚と同様に、Copilot CLI は読心術師ではありません。より多くの情報を提供することで、人間も Copilot も的を絞ったサポートができます!* + +同僚にバグを説明する場面を想像してください。 + +> **コンテキストなし**: 「ブックアプリが動かない。」 + +> **コンテキストあり**: 「`books.py` の `find_book_by_title` 関数を見てみて。大文字小文字を区別しないマッチングをしていないんだ。」 + +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 +``` + +--- + +
+🎬 実際の動作を見てみましょう! + +![ファイルコンテキストデモ](../../../02-context-conversations/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 +``` + +--- + +## クロスファイルインテリジェンス + +ここでコンテキストがスーパーパワーになります。単一ファイルの分析は有用です。クロスファイルの分析は変革的です。 + +クロスファイルインテリジェンス - 単一ファイルとクロスファイル分析の比較、一緒に分析することで単独では見えないバグ、データフロー、パターンが明らかになる + +### デモ: 複数ファイルにまたがるバグを見つける + +```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 +> ``` + +--- + +
+🎬 実際の動作を見てみましょう! + +![マルチファイルデモ](../../../02-context-conversations/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. +``` + +**結果**: コードを読むのに 1 時間かかることが 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 はすでに見たコードをトレースできる +``` + +
+🎬 複数ターンの会話の実際の動作を見てみましょう! + +![複数ターンデモ](../../../02-context-conversations/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 + +# またはセッションに付けた名前で再開する +copilot --resume="my book app review" +``` + +> 💡 **セッション ID はどうやって確認するの?** 覚える必要はありません。ID なしで `copilot --resume` を実行すると、前のセッションの名前、ID、最後のアクティブ時間が一覧表示されます。好きなものを選ぶだけです。 +> +> **複数のターミナルがある場合は?** 各ターミナルウィンドウはそれぞれのコンテキストを持つ独立したセッションです。3 つのターミナルで Copilot CLI を開いていれば、それは 3 つの別々のセッションです。どのターミナルからも `--resume` を実行するとすべてを閲覧できます。`--continue` フラグは最初に現在の作業ディレクトリのセッションを取得し、なければ最近アクティブだったセッションを取得します。 +> +> **再起動せずにセッションを切り替えられる?** はい。アクティブなセッション内から `/resume` スラッシュコマンドを使います: +> ``` +> > /resume +> # 切り替えるセッションのリストを表示する +> ``` + +### セッションを整理する + +後で見つけやすいように、セッションに意味のある名前を付けましょう。セッションの開始時に名前を付けるか、セッション内でいつでも名前を変更できます。 + +```bash +# セッションを開始するときに名前を付ける +copilot --name book-app-review + +# またはセッション内から名前を変更する +copilot + +> /rename book-app-review +# セッションが名前付けられて見つけやすくなる +``` + +セッションに名前が付いたら、リストを参照せずに直接名前で再開できます。 + +```bash +copilot --resume=book-app-review +``` + +不要になったセッションを整理するには、セッション内から `/session delete` を使います。 + +```bash +copilot + +> /session delete # 現在のセッションを削除する +> /session delete abc123 # 特定のセッションを ID で削除する +> /session delete-all # すべてのセッションを削除する(注意して使う!) +``` + +### コンテキストの確認と管理 + +ファイルや会話を追加するにつれて、Copilot CLI の[コンテキストウィンドウ](../../../GLOSSARY.md#context-window)が埋まっていきます。コントロールを保つためのコマンドがいくつかあります。 + +```bash +copilot + +> /context +Context usage: 62k/200k tokens (31%) + +> /clear +# 現在のセッションを破棄(履歴は保存されない)して新しい会話を開始する + +> /new +# 現在のセッションを終了(履歴に保存して検索・再開可能)して新しい会話を開始する + +> /rewind +# タイムラインピッカーを開いて会話の以前の時点にロールバックできる +``` + +> 💡 **`/clear` または `/new` をいつ使うか**: `books.py` をレビューしていて `utils.py` の話に切り替えたい場合は、まず `/new` を実行してください(セッション履歴が不要なら `/clear`)。そうしないと古いトピックの古いコンテキストがレスポンスを混乱させることがあります。 + +> 💡 **間違えた、または別のアプローチを試したい?** `/rewind`(または Esc を 2 回押す)を使うと、最後のものだけでなく会話の任意の以前の時点にロールバックできる**タイムラインピッカー**が開きます。間違った方向に進んだが、完全にやり直すことなく引き返したいときに便利です。 + +--- + +### 中断した場所から再開する + +GitHub Copilot CLI のセッションが数日間どのように持続するかを示すタイムライン - 月曜日に開始し、水曜日に完全なコンテキストが復元された状態で再開 + +*セッションは終了時に自動保存されます。数日後にファイル、問題、進捗がすべて記憶された状態で再開できます。* + +複数日にわたるワークフローを想像してください。 + +```bash +# 月曜日: 最初から名前付きでブックアプリのレビューを開始する +copilot --name 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 --resume=book-app-review + +> 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 は以下を覚えています。 +- 作業していた正確なファイル +- 問題の番号付きリスト +- すでに対処したもの +- 会話のコンテキスト + +再説明不要。ファイルの再読み込み不要。ただ作業を続けるだけです。 + +--- + +**🎉 これで必須事項を理解しました!** `@` 構文、セッション管理(`--name`/`--continue`/`--resume`/`/rename`)、コンテキストコマンド(`/context`/`/clear`)で十分に生産的に働けます。以下はオプションです。準備ができたら戻ってきましょう。 + +--- + +# オプション: さらに深く学ぶ + +深いコンテキストの概念の探求を表す青と紫のトーンの抽象的な水晶洞窟 + +これらのトピックは上記の必須事項を基に構築されています。**興味のあるものを選んで、または[練習](#practice)に進んでください。** + +| 学びたいこと... | ジャンプ先 | +|---|---| +| ワイルドカードパターンと高度なセッションコマンド | [追加の @ パターンとセッションコマンド](#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 を作成する + +> /share html +# セッションをスタンドアロンのインタラクティブ HTML ファイルとしてエクスポートする +# チームメートと洗練されたセッションレポートを共有したり、参考用に保存したりするのに便利 +``` + +
+ +
+コンテキスト対応の会話 + + +### コンテキスト対応の会話 + +魔法は、互いに積み上がる複数ターンの会話をするときに起こります。 + +#### 例: 段階的な改善 + +```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` | 無関係なコンテキストを削除する | +| 間違った方向に進んだ | `/rewind` | 任意の以前の時点にロールバックする | +| 長い会話 | `/compact` | 履歴を要約してトークンを解放する | +| 特定のファイルが必要 | `@folder/` ではなく `@file.py` | 必要なものだけを読み込む | +| 制限に達する | `/new` または `/clear` | 新しいコンテキスト | +| 複数のトピック | トピックごとに `/rename` を使う | 適切なセッションに簡単に再開 | + +#### 大規模コードベースのベストプラクティス + +1. **具体的にする**: `@samples/book-app-project/` の代わりに `@samples/book-app-project/books.py` +2. **トピック間でコンテキストをクリアする**: フォーカスを切り替えるときは `/new` または `/clear` を使う +3. **`/compact` を使う**: 会話を要約してコンテキストを解放する +4. **複数のセッションを使う**: 機能やトピックごとに 1 つのセッション + +
+ +
+何を参照するかを選ぶ + + +### 何を参照するかを選ぶ + +コンテキストに関しては、すべてのファイルが同じではありません。賢い選択の方法です。 + +#### ファイルサイズの考慮事項 + +| ファイルサイズ | 概算[トークン](../../../GLOSSARY.md#token) | 戦略 | +|-----------|-------------------|----------| +| 小(100 行未満) | 約 500〜1,500 トークン | 自由に参照する | +| 中(100〜500 行) | 約 1,500〜7,500 トークン | 特定のファイルを参照する | +| 大(500 行以上) | 7,500 トークン以上 | 選択的に、特定のファイルを使う | +| 非常に大(1,000 行以上) | 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 またはベンダーディレクトリ +- 大規模なデータファイルまたはフィクスチャ +- 質問と無関係なファイル + +#### 特定性のスペクトラム + +``` +あまり具体的でない ────────────────────────► より具体的 +@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.md#working-with-images)を参照してください。 + +
+ +--- + +# 練習 {#practice} + +コードが表示されたモニター、ランプ、コーヒーカップ、ヘッドホンが置かれた居心地の良いデスク + +コンテキストとセッション管理のスキルを適用する時間です。 + +--- + +## ▶️ 自分で試してみよう + +### フルプロジェクトレビュー + +コースには直接レビューできるサンプルファイルが含まれています。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. **セッションの自動保存**: 起動時に `--name` で名前を付け、`--resume=<名前>` で名前で再開するか、`--continue` で最近のセッションを再開する +4. **コンテキストウィンドウ**には制限がある: `/clear`、`/compact`、`/context`、`/new`、`/rewind` で管理する +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.md)**では以下を学びます。 + +- コードレビューワークフロー +- リファクタリングパターン +- デバッグ支援 +- テスト生成 +- Git 統合 + +--- + +**[← 第 01 章に戻る](../01-setup-and-first-steps/README.md)** | **[第 03 章に進む →](../03-development-workflows/README.md)** diff --git a/localization/ja-jp/03-development-workflows/README.md b/localization/ja-jp/03-development-workflows/README.md new file mode 100644 index 00000000..b9ca4b89 --- /dev/null +++ b/localization/ja-jp/03-development-workflows/README.md @@ -0,0 +1,971 @@ +![第 03 章: 開発ワークフロー](../../../03-development-workflows/images/chapter-header.png) + +> **AI が質問されてもいないバグを見つけてくれたら?** + +この章では、GitHub Copilot CLI が日常的なドライバーになります。すでに毎日頼りにしているワークフロー、テスト、リファクタリング、デバッグ、Git の中で使いましょう。 + +## 🎯 学習目標 + +この章を終えると、以下ができるようになります。 + +- Copilot CLI で包括的なコードレビューを実行する +- レガシーコードを安全にリファクタリングする +- AI の支援でバグをデバッグする +- テストを自動的に生成する +- Copilot CLI を Git ワークフローに統合する + +> ⏱️ **目安時間**: 約 60 分(15 分読む + 45 分ハンズオン) + +--- + +## 🧩 現実世界のたとえ話: 大工のワークフロー + +大工はツールの使い方を知っているだけでなく、異なる作業に対する*ワークフロー*を持っています。 + +職人のワークショップ: 3 つのワークフローレーン、家具制作(計測、切断、組立、仕上げ)、損傷修復(評価、除去、修理、マッチング)、品質チェック(点検、継手テスト、整合確認) + +同様に、開発者も異なるタスクに対するワークフローを持っています。GitHub Copilot CLI はこれらのワークフローを強化し、日常的なコーディングタスクをより効率的かつ効果的にします。 + +--- + +# 5 つのワークフロー + +コードレビュー、テスト、デバッグ、リファクタリング、Git 統合ワークフローを表す 5 つの輝くネオンアイコン + +以下の各ワークフローは独立しています。現在のニーズに合ったものを選ぶか、すべて進めましょう。 + +--- + +## 自分のペースで選ぶ + +この章では開発者が通常使う 5 つのワークフローをカバーします。**すべてを一度に読む必要はありません!** 以下の折りたたみセクションの中に各ワークフローが独立して含まれています。現在のニーズに合うものを選び、現在のプロジェクトに最適なものを探してください。いつでも戻って他のものを探索できます。 + +5 つの開発ワークフロー: コードレビュー、リファクタリング、デバッグ、テスト生成、Git 統合が水平のスイムレーンとして表示 + +| 目的... | ジャンプ先 | +|---|---| +| マージ前にコードをレビューする | [ワークフロー 1: コードレビュー](#workflow-1-code-review) | +| ゴチャゴチャしたまたはレガシーコードを整理する | [ワークフロー 2: リファクタリング](#workflow-2-refactoring) | +| バグを追跡して修正する | [ワークフロー 3: デバッグ](#workflow-3-debugging) | +| コードのテストを生成する | [ワークフロー 4: テスト生成](#workflow-4-test-generation) | +| より良いコミットと PR を書く | [ワークフロー 5: Git 統合](#workflow-5-git-integration) | +| コーディング前に調査する | [クイックヒント: 計画やコーディング前に調査する](#quick-tip-research-before-you-plan-or-code) | +| バグ修正ワークフロー全体を見る | [すべてをまとめる](#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 +``` + +--- + +
+🎬 実際の動作を見てみましょう! + +![コードレビューデモ](../../../03-development-workflows/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 に特定のフォーマット(ここでは Issue に貼り付けられる深刻度分類された Markdown チェックリスト)で出力を構造化するよう頼みましょう。 + +```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 の 2 種類の変更を理解する必要があります。 + +| 変更の種類 | 意味 | 確認方法 | +|-------------|---------------|------------| +| **ステージ済みの変更** | `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 +``` + +> 💡 **リファクタリングが初めてですか?** 複雑な変換に取り組む前に、型ヒントの追加や変数名の改善などのシンプルなリクエストから始めましょう。 + +--- + +
+🎬 実際の動作を見てみましょう! + +![リファクタリングデモ](../../../03-development-workflows/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. +``` + +### エラーハンドリングを改善する + +2 つの関連ファイルを提供し、横断的な関心事を説明して、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. +``` + +### ドキュメントを追加する + +各ドキュメント文字列に含めるべき内容の詳細なリストを提供して、Copilot CLI が具体的に何を変更すべきか正確に理解できるようにします。 + +```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 +``` + +### テストを使った安全なリファクタリング + +複数ターンの会話で 2 つの関連するリクエストを連鎖させます。まずテストを生成し、そのテストを安全網としてリファクタリングします。 + +```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: デバッグ - バグの追跡、セキュリティ監査、ファイルをまたいだ問題のトレース + +デバッグワークフロー: エラーの理解、根本原因の特定、修正、テスト + +### シンプルなデバッグ + +> **まずこれを試す:** `@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.` + +何が問題かを説明するところから始めましょう。バグのあるブックアプリで試せる一般的なデバッグパターンです。各プロンプトは `@` ファイル参照と明確な症状の説明を組み合わせているので、Copilot CLI がバグを特定して診断できます。 + +```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 が残りを解決します。 + +--- + +
+🎬 実際の動作を見てみましょう! + +![バグ修正デモ](../../../03-development-workflows/images/fix-bug-demo.gif) + +*デモの出力は異なる場合があります。モデル、ツール、レスポンスはここに表示されているものと異なります。* + +
+ +--- + +### 「バグ探偵」- AI が関連するバグを発見する + +コンテキスト対応デバッグが輝く場面です。バグのあるブックアプリでこのシナリオを試してみましょう。`@` でファイル全体を提供し、ユーザーが報告した症状だけを説明します。Copilot CLI が根本原因をトレースし、近くの追加バグを発見することもあります。 + +```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 はファイル全体を読み込み、バグレポートのコンテキストを理解し、明確な説明とともに具体的な修正を提供します。 + +> 💡 **ボーナス**: Copilot CLI はファイル全体を分析するため、尋ねなかった*他の*問題も発見することがよくあります。例えば、著者検索を修正している間に、`find_book_by_title` の大文字小文字区別バグも気づくかもしれません! + +### 現実世界のセキュリティサイドバー + +自分のコードのデバッグも重要ですが、本番アプリケーションのセキュリティ脆弱性を理解することは非常に重要です。この例を試してみましょう: 知らないファイルに Copilot CLI を向けてセキュリティ問題の監査を頼みます。 + +```bash +copilot + +> @samples/buggy-code/python/user_service.py Find all security vulnerabilities in this Python user service +``` + +このファイルは本番アプリで遭遇する現実世界のセキュリティパターンを示しています。 + +> 💡 **遭遇する一般的なセキュリティ用語:** +> - **SQL インジェクション**: ユーザーの入力が直接データベースクエリに入れられ、攻撃者が悪意のあるコマンドを実行できるとき +> - **パラメータ化クエリ**: 安全な代替方法 - プレースホルダー(`?`)がユーザーデータを SQL コマンドから分離する +> - **レースコンディション**: 2 つの操作が同時に発生し互いに干渉するとき +> - **XSS(クロスサイトスクリプティング)**: 攻撃者が Web ページに悪意のあるスクリプトを注入するとき + +--- + +### エラーを理解する + +スタックトレースを `@` ファイル参照と一緒に直接プロンプトに貼り付けて、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 テスト対 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 +``` + +--- + +
+🎬 実際の動作を見てみましょう! + +![テスト生成デモ](../../../03-development-workflows/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 秒で、考えるのに 1 時間かかるエッジケーステストが完成します。 + +--- + +### ユニットテスト + +単一の関数を対象として、テストしたい入力カテゴリを列挙し、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 に質問しましょう。適切なシェルコマンドを生成できます。 + +```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 説明、/pr、/delegate、/diff + +Git 統合ワークフロー: 変更のステージング、メッセージの生成、コミット、PR の作成 + +> 💡 **このワークフローは基本的な Git の知識を前提としています**(ステージング、コミット、ブランチ)。Git が初めての場合は、まず他の 4 つのワークフローを試してください。 + +### コミットメッセージを生成する + +> **まずこれを試す:** `copilot -p "Generate a conventional commit message for: $(git diff --staged)"` — 変更をステージしてからこれを実行し、Copilot CLI がコミットメッセージを書くのを見てみましょう。 + +この例では `-p` インラインプロンプトフラグとシェルコマンド置換を使って、`git diff` の出力を直接 Copilot CLI に渡して一発でコミットメッセージを生成します。`$(...)` の構文は括弧内のコマンドを実行し、その出力を外側のコマンドに挿入します。 + +```bash + +# 何が変わったか確認する +git diff --staged + +# [Conventional Commit](../../../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 統合デモ](../../../03-development-workflows/images/git-integration-demo.gif) + +*デモの出力は異なる場合があります。モデル、ツール、レスポンスはここに表示されているものと異なります。* + +
+ +--- + +### 変更を説明する + +`git show` の出力を `-p` プロンプトに渡して、最後のコミットの平易な言葉による概要を取得します。 + +```bash +# このコミットは何を変更したか? +copilot -p "Explain what this commit does: $(git show HEAD --stat)" +``` + +### PR の説明 + +`git log` の出力と構造化プロンプトテンプレートを組み合わせて、完全なプルリクエストの説明を自動生成します。 + +```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)" +``` + +### 現在のブランチに対してインタラクティブモードで /pr を使用する + +Copilot CLI のインタラクティブモードでブランチを操作している場合、`/pr` コマンドを使ってプルリクエストを操作できます。`/pr` を使って PR を表示したり、新しい PR を作成したり、既存の PR を修正したり、ブランチの状態に基づいて Copilot CLI に自動決定させたりできます。 + +```bash +copilot + +> /pr [view|create|fix|auto] +``` + +### プッシュ前にレビューする + +`-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. ドラフトプルリクエストを開く +# 3. GitHub でバックグラウンドで作業する +# 4. 完了したらレビューをリクエストする +``` + +これは他の作業に集中している間に完了させたい明確に定義されたタスクに最適です。 + +### /diff を使ってセッションの変更をレビューする + +`/diff` コマンドは現在のセッション中に行われたすべての変更を表示します。コミットする前に Copilot CLI が変更したすべてを視覚的な差分で確認するためにこのスラッシュコマンドを使います。 + +```bash +copilot + +# 変更を加えた後... +> /diff + +# このセッションで変更されたすべてのファイルの視覚的な差分を表示する +# コミット前のレビューに最適 +``` + +
+ +--- + +## クイックヒント: 計画やコーディング前に調査する {#quick-tip-research-before-you-plan-or-code} + +ライブラリを調査したり、ベストプラクティスを理解したり、不慣れなトピックを探索したりする必要がある場合は、コードを書く前に `/research` を使って深い調査を実行しましょう。 + +```bash +copilot + +> /research What are the best Python libraries for validating user input in CLI apps? +``` + +Copilot は GitHub リポジトリとウェブソースを検索し、参照付きの概要を返します。新しい機能を始めようとしているときに、まず情報に基づいた決定をするのに役立ちます。`/share` を使って結果を共有できます。 + +> 💡 **ヒント**: `/research` は `/plan` の*前に*使うとよく機能します。アプローチを調査して、実装を計画しましょう。 + +--- + +## すべてをまとめる: バグ修正ワークフロー {#putting-it-all-together-bug-fix-workflow} + +報告されたバグを修正するための完全なワークフローです。 + +```bash + +# 1. バグレポートを理解する +copilot + +> Users report: 'Finding books by author name doesn't work for partial names' +> @samples/book-app-project/books.py Analyze and identify the likely cause + +# 2. 問題をデバッグして修正する(同じセッションで続ける) +> Based on the analysis, show me the find_by_author function and explain the issue + +> Fix the find_by_author function to handle partial name matches + +# 3. 修正のテストを生成する +> @samples/book-app-project/books.py Generate pytest tests specifically for: +> - Full author name match +> - Partial author name match +> - Case-insensitive matching +> - Author name not found + +# インタラクティブセッションを終了する + +> /exit + +# 4. git add を実行する + +# git diff --staged に何かを入れるために変更をステージする +git add . + +# 5. コミットメッセージを生成する +copilot -p "Generate commit message for: $(git diff --staged)" + +# 出力例: "fix(books): support partial author name search" + +# 6. 変更をコミットする(オプション) + +git commit -m "<生成されたメッセージを貼り付ける>" +``` + +### バグ修正ワークフローのまとめ + +| ステップ | アクション | Copilot コマンド | +|------|--------|-----------------| +| 1 | バグを理解する | `> [バグを説明する] @relevant-file.py Analyze the likely cause` | +| 2 | 分析と修正 | `> Show me the function and fix the issue` | +| 3 | テストを生成する | `> Generate tests for [特定のシナリオ]` | +| 4 | 変更をステージする | `git add .` | +| 5 | コミットメッセージを生成する | `copilot -p "Generate commit message for: $(git diff --staged)"` | +| 6 | 変更をコミットする | `git commit -m "<生成されたメッセージを貼り付ける>"` | + +--- + +# 練習 + +コードが表示されたモニター、ランプ、コーヒーカップ、ヘッドホンが置かれた居心地の良いデスク + +これらのワークフローを適用する番です。 + +--- + +## ▶️ 自分で試してみよう + +デモを完了した後、これらのバリエーションを試してみましょう。 + +1. **バグ探偵チャレンジ**: `samples/book-app-buggy/books_buggy.py` の `mark_as_read` 関数をデバッグするよう Copilot CLI に頼む。1 冊ではなくすべての本が既読としてマークされる理由を説明しましたか? + +2. **テストチャレンジ**: ブックアプリの `add_book` 関数のテストを生成する。Copilot CLI が含めたエッジケースで自分では思いつかなかったものはいくつありましたか? + +3. **コミットメッセージチャレンジ**: ブックアプリのファイルに小さな変更を加え、ステージし(`git add .`)、次を実行する: + ```bash + copilot -p "Generate a conventional commit message for: $(git diff --staged)" + ``` + 自分が素早く書いたメッセージよりも良いですか? + +**自己確認**: 「バグを見つける」より「このバグをデバッグする」の方が強力な理由を説明できれば開発ワークフローを理解しています(コンテキストが重要!)。 + +--- + +## 📝 課題 + +### メインチャレンジ: リファクタリング、テスト、そして出荷 + +ハンズオン例は `find_book_by_title` とコードレビューに焦点を当てていました。今度は `book-app-project` の異なる関数で同じワークフロースキルを練習しましょう。 + +1. **レビュー**: `books.py` の `remove_book()` をエッジケースと潜在的な問題についてレビューするよう Copilot CLI に頼む: + `@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. **リファクタリング**: 大文字小文字を区別しないマッチングや本が見つからなかったときの有用なフィードバックを返すなど、エッジケースを処理するよう `remove_book()` を改善するよう Copilot CLI に頼む +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 演習は Python ではなく **Node.js** を使用します。練習する GitHub Copilot CLI のテクニック(Issue の作成、コードの生成、ターミナルからのコラボレーション)はどの言語にも適用できます。 + +この演習では、GitHub Copilot CLI を使って Issue を作成し、コードを生成し、Node.js 計算機アプリを構築しながらターミナルからコラボレーションする方法を開発者に示します。CLI のインストール、テンプレートとエージェントの使用、反復的なコマンドライン駆動開発を練習します。 + +##### [「Copilot CLI でアプリケーションを作成する」Skills 演習を開始する](https://github.com/skills/create-applications-with-the-copilot-cli) + +--- + +
+🔧 よくある間違いとトラブルシューティング(クリックして展開) + +### よくある間違い + +| 間違い | 何が起こるか | 対処法 | +|---------|--------------|-----| +| 「Review this code」のような曖昧なプロンプトを使う | 特定の問題を見落とす一般的なフィードバック | 具体的に: 「Review for SQL injection, XSS, and auth issues」 | +| コードレビューに `/review` を使わない | 最適化されたコードレビューエージェントを見逃す | 高い信号対雑音比の出力に調整された `/review` を使う | +| コンテキストなしで「バグを見つける」と頼む | Copilot CLI は経験しているバグを知らない | 症状を説明する: 「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 を使う唯一の「正しい」方法はありません。自分のパターンを開発する際のヒントです。 + +> 📚 **公式ドキュメント**: GitHub からの推奨ワークフローとヒントについては [Copilot CLI のベストプラクティス](https://docs.github.com/copilot/how-tos/copilot-cli/cli-best-practices)をご覧ください。 + +- **些細でないことには `/plan` から始める。** 実行前に計画を洗練させましょう — 良い計画はより良い結果につながります。 +- **うまく機能するプロンプトを保存する。** Copilot CLI が間違えたとき、何が悪かったかをメモしましょう。時間が経つと、これが個人的なプレイブックになります。 +- **自由に実験する。** 長くて詳細なプロンプトを好む開発者もいれば、フォローアップ付きの短いプロンプトを好む開発者もいます。さまざまなアプローチを試して、何が自然に感じるかを確認しましょう。 + +> 💡 **次のステップ**: 第 04 章と第 05 章では、ベストプラクティスを Copilot CLI が自動的に読み込むカスタム指示とスキルにコード化する方法を学びます。 + +--- + +## ➡️ 次のステップ + +残りの章では Copilot CLI の機能を拡張する追加機能をカバーします。 + +| 章 | カバーする内容 | 必要になるとき | +|---------|----------------|---------------------| +| 第 04 章: エージェント | 特化した AI ペルソナを作成する | ドメインエキスパート(フロントエンド、セキュリティ)が必要なとき | +| 第 05 章: スキル | タスクの指示を自動読み込みする | 同じプロンプトを何度も繰り返すとき | +| 第 06 章: MCP | 外部サービスを接続する | GitHub、データベースからライブデータが必要なとき | + +**推奨**: コアワークフローを 1 週間試してから、特定のニーズがあるときに第 04〜06 章に戻りましょう。 + +--- + +## 追加トピックに進む + +**[第 04 章: エージェントとカスタム指示](../04-agents-custom-instructions/README.md)**では以下を学びます。 + +- 組み込みエージェント(`/plan`、`/review`)の使用 +- `.agent.md` ファイルを使った特化したエージェントの作成(フロントエンドエキスパート、セキュリティ監査員) +- マルチエージェントのコラボレーションパターン +- プロジェクト標準のカスタム指示ファイル + +--- + +**[← 第 02 章に戻る](../02-context-conversations/README.md)** | **[第 04 章に進む →](../04-agents-custom-instructions/README.md)** diff --git a/localization/ja-jp/04-agents-custom-instructions/README.md b/localization/ja-jp/04-agents-custom-instructions/README.md new file mode 100644 index 00000000..80adb2af --- /dev/null +++ b/localization/ja-jp/04-agents-custom-instructions/README.md @@ -0,0 +1,783 @@ +![第 04 章: エージェントとカスタム指示](../../../04-agents-custom-instructions/images/chapter-header.png) + +> **Python コードレビュアー、テストエキスパート、セキュリティレビュアーを 1 つのツールで雇えたら?** + +第 03 章では、コードレビュー、リファクタリング、デバッグ、テスト生成、Git 統合という必須ワークフローをマスターしました。それらで GitHub Copilot CLI を使った生産性は十分高まります。さらに一歩進めましょう。 + +これまでは Copilot CLI を汎用アシスタントとして使ってきました。エージェントを使うと、型ヒントと PEP 8 を強制するコードレビュアーや、pytest ケースを書くテストヘルパーなど、組み込みの基準を持つ特定のペルソナを与えることができます。同じプロンプトが対象を絞った指示を持つエージェントに処理されると、明らかに良い結果が得られることがわかります。 + +## 🎯 学習目標 + +この章を終えると、以下ができるようになります。 + +- 組み込みエージェントを使う: プラン(`/plan`)、コードレビュー(`/review`)、自動エージェント(Explore、Task)を理解する +- エージェントファイル(`.agent.md`)を使って特化したエージェントを作成する +- ドメイン固有のタスクにエージェントを使う +- `/agent` と `--agent` を使ってエージェントを切り替える +- プロジェクト固有の標準のためのカスタム指示ファイルを書く + +> ⏱️ **目安時間**: 約 55 分(20 分読む + 35 分ハンズオン) + +--- + +## 🧩 現実世界のたとえ話: 専門家を雇う + +家に問題があるとき、1 人の「汎用ヘルパー」を呼ぶわけではありません。専門家を呼びます。 + +| 問題 | 専門家 | 理由 | +|---------|------------|-----| +| 水漏れ | 配管工 | 配管規格を知り、専門ツールを持っている | +| 配線工事 | 電気工事士 | 安全要件を理解し、規格に準拠している | +| 屋根の葺き替え | 屋根工事業者 | 材料を知り、地域の気候を考慮している | + +エージェントも同じように機能します。汎用 AI の代わりに、特定のタスクに集中して適切なプロセスを知っているエージェントを使います。指示を一度設定して、そのスペシャリティが必要なときにいつでも再利用します: コードレビュー、テスト、セキュリティ、ドキュメント。 + +専門家を雇うたとえ話 - 家の修理に専門の職人を呼ぶように、AI エージェントはコードレビュー、テスト、セキュリティ、ドキュメントなどの特定タスクに特化している + +--- + +# エージェントを使う + +組み込みおよびカスタムエージェントをすぐに始めましょう。 + +--- + +## *エージェントが初めてですか?* ここから始めましょう! +エージェントを使ったことも作ったこともない場合は、このコースを始めるために知っておくべきことがすべてここにあります。 + +1. **今すぐ*組み込み*エージェントを試してみましょう:** + ```bash + copilot + > /plan Add input validation for book year in the book app + ``` + これはプランエージェントを呼び出してステップバイステップの実装計画を作成します。 + +2. **カスタムエージェントの例を見てみましょう:** エージェントの指示を定義するのは簡単です。提供されている [python-reviewer.agent.md](../../../.github/agents/python-reviewer.agent.md) ファイルを見てパターンを確認してください。 + +3. **コアコンセプトを理解する:** エージェントは汎用の専門家ではなく専門家に相談するようなものです。「フロントエンドエージェント」は自動的にアクセシビリティとコンポーネントパターンに集中します。エージェントの指示にすでに指定されているので、いちいち思い出させる必要はありません。 + + +## 組み込みエージェント + +**第 03 章の開発ワークフローですでにいくつかの組み込みエージェントを使っています!** +
`/plan` と `/review` は実際には組み込みエージェントです。ここで仕組みがわかります。完全なリストは以下のとおりです。 + +| エージェント | 呼び出し方 | 機能 | +|-------|---------------|--------------| +| **プラン** | `/plan` または `Shift+Tab`(モード切替) | コーディング前にステップバイステップの実装計画を作成する | +| **コードレビュー** | `/review` | ステージ済み/未ステージの変更を集中した実行可能なフィードバックでレビューする | +| **Init** | `/init` | プロジェクト設定ファイル(指示、エージェント)を生成する | +| **Explore** | *自動* | コードベースを探索・分析するよう Copilot に頼んだときに内部的に使用される | +| **Task** | *自動* | テスト、ビルド、リント、依存関係のインストールなどのコマンドを実行する | + +
+ +**組み込みエージェントの動作例** - プラン、コードレビュー、Explore、Task の呼び出し例 + +```bash +copilot + +# プランエージェントを呼び出して実装計画を作成する +> /plan Add input validation for book year in the book app + +# コードレビューエージェントを変更に対して呼び出す +> /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 にエージェントを追加する + +ワークフローの一部として独自のエージェントを簡単に定義できます!一度定義すれば、指示するだけです! + +特化したエージェントの機能を表す異なるツールを持つ 4 体のカラフルな AI ロボット + +## 🗂️ エージェントを追加する + +エージェントファイルは `.agent.md` 拡張子を持つ Markdown ファイルです。2 つの部分があります: YAML フロントマター(メタデータ)と Markdown 指示。 + +> 💡 **YAML フロントマターが初めてですか?** ファイルの先頭にある `---` マーカーで囲まれた設定の小さなブロックです。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 +``` + +> 💡 **必須対オプション**: `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) を参照してください + +
+ + +## 🚀 カスタムエージェントを使う 2 つの方法 + +### インタラクティブモード +インタラクティブモード内で、`/agent` を使ってエージェントをリストアップし、使用するエージェントを選択します。 +エージェントを選択して会話を続けます。 + +```bash +copilot +> /agent +``` + +別のエージェントに切り替えるか、デフォルトモードに戻るには、再度 `/agent` コマンドを使います。 + +### プログラマティックモード + +エージェントで直接新しいセッションを起動します。 + +```bash +copilot --agent python-reviewer +> Review @samples/book-app-project/books.py +``` + +> 💡 **エージェントの切り替え**: `/agent` または `--agent` を再度使うことで、いつでも別のエージェントに切り替えられます。標準の Copilot CLI 体験に戻るには、`/agent` を使って**エージェントなし**を選択します。 + +--- + +# エージェントをさらに深く学ぶ + +コンポーネントとツールに囲まれた作業台でロボットが組み立てられており、カスタムエージェントの作成を表している + +> 💡 **このセクションはオプションです。** 組み込みエージェント(`/plan`、`/review`)はほとんどのワークフローに十分強力です。作業全体で一貫して適用される特化した専門知識が必要なときにカスタムエージェントを作成します。 + +以下の各トピックは独立しています。**興味のあるものを選んで - すべてを一度に読む必要はありません。** + +| 目的... | ジャンプ先 | +|---|---| +| エージェントが汎用プロンプトより優れている理由を確認する | [専門家対汎用](#specialist-vs-generic-see-the-difference) | +| 機能でエージェントを組み合わせる | [複数エージェントで働く](#working-with-multiple-agents) | +| エージェントの整理、命名、共有 | [エージェントの整理と共有](#organizing--sharing-agents) | +| 常時オンのプロジェクトコンテキストを設定する | [Copilot のためのプロジェクト設定](#configuring-your-project-for-copilot) | +| YAML プロパティとツールを調べる | [エージェントファイルリファレンス](#agent-file-reference) | + +以下のシナリオを選択して展開します。 + +--- + + +
+専門家対汎用: 違いを確認する - エージェントが汎用プロンプトより優れた出力を生成する理由 + +## 専門家対汎用: 違いを確認する + +ここでエージェントがその価値を証明します。違いを見てみましょう。 + +### エージェントなし(汎用 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 を含む包括的なドキュメント文字列 +- ✅ 適切なエラーハンドリングを含む入力バリデーション +- ✅ より高いパフォーマンスのためのリスト内包表記 +- ✅ エッジケースの処理(欠落/無効な年の値) +- ✅ 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 レビュアーデモ](../../../04-agents-custom-instructions/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 がプロジェクトから読み込む 1 種類のファイルです。`/agent` を実行しなくても、すべてのセッションに自動的に適用される**指示ファイル**もサポートしています。 + +こう考えてください: エージェントは呼ぶ専門家で、指示ファイルは常に有効なチームルールです。 + +### ファイルを置く場所 + +2 つのメインの場所はすでに知っています(上記の[エージェントファイルを置く場所](#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` は推奨フォーマットです。Copilot と他の AI コーディングツールで機能する[オープン標準](https://agents.md/)です。リポジトリのルートに置くと Copilot が自動的に読み込みます。このプロジェクト自身の [AGENTS.md](../../../AGENTS.md) が動作例です。 + +典型的な `AGENTS.md` は、プロジェクトのコンテキスト、コードスタイル、セキュリティ要件、テスト標準を説明します。例のファイルのパターンに従って独自のものを書いてください。 + +### カスタム指示ファイル(.instructions.md) + +より細かい制御を望むチームには、指示をトピック固有のファイルに分割しましょう。各ファイルが 1 つの関心事をカバーし、自動的に適用されます。 + +``` +.github/ +└── instructions/ + ├── python-standards.instructions.md + ├── security-checklist.instructions.md + └── api-design.instructions.md +``` + +> 💡 **注意**: 指示ファイルはどの言語でも機能します。この例はコースプロジェクトに合わせて Python を使用していますが、チームが使用する TypeScript、Go、Rust、または他のテクノロジーに対して同様のファイルを作成できます。 + +**コミュニティ指示ファイルを見つける**: .NET、Angular、Azure、Python、Docker などの多くのテクノロジーをカバーするプリメイドの指示ファイルは [github/awesome-copilot](https://github.com/github/awesome-copilot) を参照してください。 + +### カスタム指示を無効にする + +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`、`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. `.github/agents/` に配置した、エージェントごとに 1 ファイルの 3 つのエージェントファイル(`.agent.md`)を作成する +2. エージェント: + - **data-validator**: `data.json` を欠落または不正なデータ(空の著者、year=0、欠落フィールド)でチェックする + - **error-handler**: Python コードを一貫しないエラーハンドリングでレビューし、統一されたアプローチを提案する + - **doc-writer**: ドキュメント文字列と 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` にドキュメント文字列を追加する +4. コラボレーション: `error-handler` を使ってエラーハンドリングのギャップを特定し、`doc-writer` で改善されたアプローチをドキュメント化する + +**成功基準**: 一貫した高品質の出力を生成する 3 つの動作するエージェントがあり、`/agent` で切り替えられます。 + +
+💡 ヒント(クリックして展開) + +**スターターテンプレート**: `.github/agents/` にエージェントごとに 1 ファイル作成します: + +`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 フロントマターの `description` フィールドはエージェントが機能するために必須です。 + +
+ +### ボーナスチャレンジ: 指示ライブラリ + +オンデマンドで呼び出すエージェントを構築しました。次はもう一方を試してみましょう: `/agent` なしで毎回のセッションで Copilot が自動的に読み込む**指示ファイル**。 + +`.github/instructions/` フォルダに少なくとも 3 つの指示ファイルを作成します: +- `python-style.instructions.md` - PEP 8 と型ヒントの規約を強制する +- `test-standards.instructions.md` - テストファイルの pytest 規約を強制する +- `data-quality.instructions.md` - JSON データエントリを検証する + +ブックアプリのコードで各指示ファイルをテストしましょう。 + +--- + +
+🔧 よくある間違いとトラブルシューティング(クリックして展開) + +### よくある間違い + +| 間違い | 何が起こるか | 対処法 | +|---------|--------------|-----| +| エージェントフロントマターに `description` がない | エージェントが読み込まれないか発見できない | YAML フロントマターには常に `description:` を含める | +| エージェントのファイル場所が間違っている | 使おうとするとエージェントが見つからない | `~/.copilot/agents/`(個人用)または `.github/agents/`(プロジェクト)に置く | +| `.agent.md` の代わりに `.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` は直接呼び出す; Explore と Task は自動的に機能する +2. **カスタムエージェント**は `.agent.md` ファイルで定義された専門家である +3. **良いエージェント**は明確な専門知識、標準、出力フォーマットを持っている +4. **マルチエージェントのコラボレーション**は専門知識を組み合わせることで複雑な問題を解決する +5. **指示ファイル**(`.instructions.md`)はチーム標準を自動適用のためにコード化する +6. **一貫した出力**は適切に定義されたエージェント指示から生まれる + +> 📋 **クイックリファレンス**: コマンドとキーボードショートカットの完全なリストは [GitHub Copilot CLI コマンドリファレンス](https://docs.github.com/en/copilot/reference/cli-command-reference)をご覧ください。 + +--- + +## ➡️ 次のステップ + +エージェントは Copilot がコードに*どのようにアプローチして対象を絞ったアクションを取るか*を変えます。次は**スキル**について学びます - これは*どのステップ*に従うかを変えます。エージェントとスキルの違いが気になりますか?第 05 章でそれを正面から取り上げます。 + +**[第 05 章: スキルシステム](../05-skills/README.md)**では以下を学びます。 + +- スキルがプロンプトから自動的にトリガーされる方法(スラッシュコマンド不要) +- コミュニティスキルのインストール +- SKILL.md ファイルを使ったカスタムスキルの作成 +- エージェント、スキル、MCP の違い +- それぞれをいつ使うか + +--- + +**[← 第 03 章に戻る](../03-development-workflows/README.md)** | **[第 05 章に進む →](../05-skills/README.md)** diff --git a/localization/ja-jp/05-skills/README.md b/localization/ja-jp/05-skills/README.md new file mode 100644 index 00000000..507316d4 --- /dev/null +++ b/localization/ja-jp/05-skills/README.md @@ -0,0 +1,886 @@ +![第 05 章: スキルシステム](../../../images/chapter-header.png) + +> **チームのベストプラクティスを毎回説明しなくても Copilot が自動的に適用してくれたら?** + +この章では、エージェントスキルについて学びます。スキルはタスクに関連するときに Copilot が自動的に読み込む指示のフォルダです。エージェントが Copilot の*思考方法*を変えるのに対して、スキルは Copilot に*タスクを完了する具体的な方法*を教えます。セキュリティについて質問するたびに Copilot が適用するセキュリティ監査スキルを作成し、一貫したコード品質を確保するチーム標準のレビュー基準を構築し、スキルが Copilot CLI、VS Code、GitHub Copilot クラウドエージェント全体でどのように機能するかを学びます。 + + +## 🎯 学習目標 + +この章を終えると、以下ができるようになります。 + +- エージェントスキルがどのように機能し、いつ使うべきかを理解する +- SKILL.md ファイルでカスタムスキルを作成する +- 共有リポジトリからコミュニティスキルを使用する +- スキル対エージェント対 MCP をいつ使うかを知る + +> ⏱️ **目安時間**: 約 55 分(20 分読む + 35 分ハンズオン) + +--- + +## 🧩 現実世界のたとえ話: 電動工具 + +汎用ドリルは便利ですが、特化したアタッチメントで強力になります。 +電動工具 - スキルが Copilot の機能を拡張する + + +スキルも同様に機能します。ドリルビットを異なる作業に交換するように、異なるタスクのために Copilot にスキルを追加できます。 + +| スキルアタッチメント | 目的 | +|------------|---------| +| `commit` | 一貫したコミットメッセージを生成する | +| `security-audit` | OWASP の脆弱性をチェックする | +| `generate-tests` | 包括的な pytest テストを作成する | +| `code-checklist` | チームのコード品質基準を適用する | + + + +*スキルは Copilot ができることを拡張する特化したアタッチメントです* + +--- + +# スキルの仕組み + +Copilot スキルを表す星空を背景に光のトレイルで繋がれた輝く RPG スタイルのスキルアイコン + +スキルとは何か、なぜ重要か、エージェントや MCP とどう違うかを学びましょう。 + +--- + +## *スキルが初めてですか?* ここから始めましょう! + +1. **すでに利用可能なスキルを確認する:** + ```bash + copilot + > /skills list + ``` + これは Copilot が見つけることができるすべてのスキルを表示します。CLI 自体に付属している**組み込みスキル**と、プロジェクトや個人フォルダのスキルが含まれます。 + + > 💡 **組み込みスキル**: Copilot CLI にはすぐに使えるスキルがプレインストールされています。たとえば、`customizing-copilot-cloud-agents-environment` スキルは Copilot クラウドエージェントの環境をカスタマイズするためのガイドを提供します。使用するために何も作成・インストールする必要はありません。`/skills list` を実行して何が利用可能かを確認してください。 + +2. **実際のスキルファイルを見てみましょう:** 提供されている [code-checklist SKILL.md](../../../.github/skills/code-checklist/SKILL.md) を確認してパターンを確認してください。YAML フロントマターと 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 +``` + +これにより、特定のスキルが使用されることを確認したいときに明示的な制御ができます。 + +#### 1 つのメッセージで複数のスキルを組み合わせる + +1 つのメッセージで**複数のスキルを呼び出す**ことができ、スキルのスラッシュコマンドはプロンプトのどこにでも置けます(最初だけではありません)。これは 2 種類のチェックを一度に行いたいときに便利です。 + +```bash +> Check @samples/book-app-project/book_app.py with /code-checklist and also run /generate-tests for it + +> Review the auth module /security-audit then /code-checklist the result +``` + +Copilot は同じレスポンスで各指定スキルを適用し、複数の別々のメッセージを送る手間を省きます。 + +> 💡 **ヒント**: スキルのスラッシュコマンドを文章の中で最も自然な場所に置いてください。メッセージの先頭、中間、末尾に置けます。 + +> 📝 **スキル対エージェントの呼び出し**: スキルの呼び出しとエージェントの呼び出しを混同しないでください。 +> - **スキル**: `/skill-name `、例: `/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? +``` + +### スキル対エージェント対 MCP + +スキルは GitHub Copilot の拡張モデルの一部に過ぎません。エージェントと MCP サーバーとの比較です。 + +> *MCP についてはまだ心配しないでください。[第 06 章](../06-mcp-servers/README.md)でカバーします。スキルが全体像にどう合うかがわかるようにここに含まれています。* + +エージェント、スキル、MCP サーバーの違いとワークフローへの組み合わせ方を示す比較図 + +| 機能 | 何をするか | いつ使うか | +|---------|--------------|-------------| +| **エージェント** | AI の思考方法を変える | 多くのタスクで特化した専門知識が必要なとき | +| **スキル** | タスク固有の指示を提供する | 詳細なステップを持つ特定の繰り返しタスク | +| **MCP** | 外部サービスに接続する | API からリアルタイムデータが必要なとき | + +幅広い専門知識にはエージェントを、特定のタスク指示にはスキルを、外部データには MCP を使います。エージェントは会話中に 1 つ以上のスキルを使用できます。たとえば、エージェントにコードチェックを頼むと、自動的に `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. リストアップしなくてもすべてのチェックを適用する + +スキルの自動トリガー方法 - Copilot がプロンプトを正しいスキルと自動的に一致させる 4 ステップのフロー + +*自然に聞くだけ。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 点を覚える必要があり、誰かが必ず 1 点を忘れます。`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 +``` + +**力の源**: すべてのチームメンバーが同じ標準を自動的に適用します。新入社員はチェックリストを覚える必要がありません。スキルが処理するからです。 + +--- + +# カスタムスキルを作成する + +スキルの作成と管理を表す輝く LEGO のようなブロックの壁を構築する人間とロボットの手 + +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 のフロントマターの `name`(小文字とハイフン)と一致させてください。 + +### SKILL.md フォーマット + +スキルは YAML フロントマターを持つシンプルな 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 +# コードレビュアーエージェントで始める +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 ファイルを作成または編集した後、Copilot を再起動せずに変更を取得するために `/skills reload` を実行します。 + +```bash +# スキルファイルを編集する +# 次に Copilot 内で: +> /skills reload +Skills reloaded successfully. +``` + +> 💡 **知っておくと便利**: スキルは会話履歴を要約するために `/compact` を使った後も有効です。コンパクト後に再読み込みする必要はありません。 + +--- + +## コミュニティスキルを見つけて使う + +### プラグインを使ってスキルをインストールする + +> 💡 **プラグインとは何ですか?** プラグインはスキル、エージェント、MCP サーバー設定をまとめてバンドルできるインストール可能なパッケージです。Copilot CLI の「アプリストア」拡張のようなものと考えてください。 + +`/plugin` コマンドを使って、これらのパッケージを参照してインストールできます。 + +```bash +copilot + +> /plugin list +# インストール済みプラグインを表示する + +> /plugin marketplace +# 利用可能なプラグインを参照する + +> /plugin install +# マーケットプレイスからプラグインをインストールする +``` + +ローカルプラグインカタログを最新に保つには、以下で更新します。 + +```bash +copilot plugin marketplace update +``` + +プラグインは複数の機能をまとめてバンドルできます。単一のプラグインに関連するスキル、エージェント、連携して機能する MCP サーバー設定が含まれることがあります。 + +### コミュニティスキルリポジトリ + +プリメイドスキルはコミュニティリポジトリからも入手できます。 + +- **[Awesome Copilot](https://github.com/github/awesome-copilot)** - スキルのドキュメントと例を含む公式 GitHub Copilot リソース + +### GitHub CLI でコミュニティスキルをインストールする + +GitHub リポジトリからスキルをインストールする最も簡単な方法は `gh skill install` コマンドを使用することです([GitHub CLI v2.90.0 以上](https://github.blog/changelog/2026-04-16-manage-agent-skills-with-github-cli/)が必要): + +```bash +# awesome-copilot からスキルを参照してインタラクティブに選択する +gh skill install github/awesome-copilot + +# または特定のスキルを直接インストールする +gh skill install github/awesome-copilot code-checklist + +# すべてのプロジェクトで個人使用のためにインストールする(ユーザースコープ) +gh skill install github/awesome-copilot code-checklist --scope user +``` + +> ⚠️ **インストール前に確認する**: スキルをインストールする前に必ずその `SKILL.md` を読んでください。スキルは Copilot の動作を制御するため、悪意のあるスキルが有害なコマンドを実行させたり、予期しない方法でコードを修正させたりする可能性があります。 + +--- + +# 練習 + +コードが表示されたモニター、ランプ、コーヒーカップ、ヘッドホンが置かれた居心地の良いデスク + +学んだことを実践して、独自のスキルを構築・テストしましょう。 + +--- + +## ▶️ 自分で試してみよう + +### さらにスキルを構築する + +異なるパターンを示す 2 つのスキルを以下に示します。上記「最初のスキルを作成する」と同じ `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. **スキル作成チャレンジ**: 3 点チェックリストを行う `quick-review` スキルを作成します: + - 裸の except 句 + - 欠落している型ヒント + - 不明確な変数名 + + テストするには: 「Do a quick review of books.py」と聞きます + +2. **スキル比較**: 詳細なセキュリティレビュープロンプトを手動で書く時間を計ります。次に「Check for security issues in this file」と聞いて、セキュリティ監査スキルが自動的に読み込まれるようにします。スキルはどれだけ時間を節約しましたか? + +3. **チームスキルチャレンジ**: チームのコードレビューチェックリストについて考えてください。スキルとしてコード化できますか?スキルが常にチェックすべき 3 つのことを書き留めてください。 + +**自己確認**: `description` フィールドが重要な理由を説明できれば(Copilot がスキルを読み込むかどうかを決める方法)、スキルを理解しています。 + +--- + +## 📝 課題 + +### メインチャレンジ: ブックサマリースキルを構築する + +上記の例は `pytest-gen` と `pr-review` スキルを作成しました。今度は全く異なる種類のスキルを作成する練習をしましょう: データからフォーマットされた出力を生成するスキルです。 + +1. 現在のスキルをリストアップする: Copilot を実行して `/skills list` を渡します。プロジェクトスキルを見るために `ls .github/skills/` または個人スキルのために `ls ~/.copilot/skills/` を使うこともできます。 +2. ブックコレクションのフォーマットされた Markdown サマリーを生成する `book-summary` スキルを `.github/skills/book-summary/SKILL.md` に作成する +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` で直接呼び出してみる + +**成功基準**: ブックコレクションについて聞いたときに Copilot が自動的に適用する動作する `book-summary` スキルがあります。 + +
+💡 ヒント(クリックして展開) + +**スターターテンプレート**: `.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. スキルをドキュメント化して、`copilot-skill` トピックで GitHub に共有する + +--- + +
+🔧 よくある間違いとトラブルシューティング(クリックして展開) + +### よくある間違い + +| 間違い | 何が起こるか | 対処法 | +|---------|--------------|-----| +| ファイル名を `SKILL.md` 以外にする | スキルが認識されない | ファイルは正確に `SKILL.md` と名付けなければならない | +| 曖昧な `description` フィールド | スキルが自動的に読み込まれない | 説明は主要な発見メカニズム。特定のトリガーワードを使う | +| フロントマターに `name` または `description` がない | スキルが読み込まれない | YAML フロントマターに両方のフィールドを追加する | +| フォルダ場所が間違っている | スキルが見つからない | `.github/skills/skill-name/`(プロジェクト)または `~/.copilot/skills/skill-name/`(個人)を使う | + +### トラブルシューティング + +**スキルが使われない** - 期待通りに 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 フォーマットを確認する**: フロントマターは必須: + ```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. **特定のチェックを探す**: スキルに特定のチェック(「50 行を超える関数」など)が含まれている場合、それらが出力に表示されるか確認する + +
+ +--- + +# まとめ + +## 🔑 重要なポイント + +1. **スキルは自動**: プロンプトがスキルの説明と一致するときに Copilot が読み込む +2. **直接呼び出し**: スラッシュコマンドとして `/skill-name` でスキルを直接呼び出すこともできる +3. **SKILL.md フォーマット**: YAML フロントマター(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.md)**では以下を学びます。 + +- MCP(Model Context Protocol)とは何か +- GitHub、ファイルシステム、ドキュメントサービスへの接続 +- MCP サーバーの設定 +- マルチサーバーワークフロー + +--- + +**[← 第 04 章に戻る](../04-agents-custom-instructions/README.md)** | **[第 06 章に進む →](../06-mcp-servers/README.md)** diff --git a/localization/ja-jp/06-mcp-servers/README.md b/localization/ja-jp/06-mcp-servers/README.md new file mode 100644 index 00000000..c3174cfb --- /dev/null +++ b/localization/ja-jp/06-mcp-servers/README.md @@ -0,0 +1,974 @@ +![第 06 章: MCP サーバー](../../../images/chapter-header.png) + +> **Copilot がターミナルから GitHub のイシューを読んで、データベースをチェックして、PR を作成できたら?** + +これまで Copilot は直接渡すもの: `@` で参照するファイル、会話履歴、自分のトレーニングデータしか使えませんでした。でも、GitHub リポジトリを確認したり、プロジェクトファイルを参照したり、ライブラリの最新ドキュメントを調べたりできたら? + +それが MCP(Model Context Protocol)の役割です。Copilot を外部サービスに接続して、実際のライブデータにアクセスできるようにする方法です。Copilot が接続する各サービスは「MCP サーバー」と呼ばれます。この章では、いくつかの接続を設定して、Copilot が劇的に便利になる様子を見ていきます。 + +> 💡 **MCP を既に知っていますか?** [クイックスタート](#-use-the-built-in-github-mcp)にジャンプして動作を確認し、サーバーの設定を始めましょう。 + +## 🎯 学習目標 + +この章を終えると、以下ができるようになります。 + +- MCP とは何か、なぜ重要かを理解する +- `/mcp` コマンドを使って MCP サーバーを管理する +- GitHub、ファイルシステム、ドキュメント向けに MCP サーバーを設定する +- ブックアプリプロジェクトで MCP を活用したワークフローを使う +- カスタム MCP サーバーをいつ・どう構築するかを知る(オプション) + +> ⏱️ **目安時間**: 約 50 分(15 分読む + 35 分ハンズオン) + +--- + +## 🧩 現実世界のたとえ話: ブラウザの拡張機能 + +MCP サーバーはブラウザの拡張機能のようなもの + +MCP サーバーをブラウザの拡張機能と考えてください。ブラウザ単体でも Web ページを表示できますが、拡張機能で追加サービスに接続できます。 + +| ブラウザ拡張機能 | 接続先 | MCP の対応 | +|-------------------|---------------------|----------------| +| パスワードマネージャー | パスワード保管庫 | **GitHub MCP** → リポジトリ、イシュー、PR | +| Grammarly | 文章解析サービス | **Context7 MCP** → ライブラリドキュメント | +| ファイルマネージャー | クラウドストレージ | **Filesystem MCP** → ローカルプロジェクトファイル | + +拡張機能なしでもブラウザは便利ですが、拡張機能があると強力なツールになります。MCP サーバーは Copilot に同じことをします。Copilot を実際のライブデータソースに接続して、GitHub のイシューを読んだり、ファイルシステムを探索したり、最新のドキュメントを取得したりできます。 + +***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 は*1 つ*のサーバーに過ぎません。この章では、さらに多く(ファイルシステムアクセス、最新ドキュメントなど)を追加する方法を示します。 + +--- + +## `/mcp show` コマンド + +`/mcp show` を使って、設定されている MCP サーバーと有効かどうかを確認します。 + +```bash +copilot + +> /mcp show + +MCP Servers: +✓ github (enabled) - GitHub integration +✓ filesystem (enabled) - File system access +``` + +> 💡 **GitHub サーバーしか表示されない?** それで正常です!まだ追加の MCP サーバーを追加していない場合、GitHub だけがリストされます。次のセクションでさらに追加します。 + +> 📚 **すべての MCP 管理コマンドを見たいですか?** チャット内の `/mcp` スラッシュコマンド、またはターミナルから直接 `copilot 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) - GitHub Copilot での MCP の仕組みの詳しい説明。 + +--- + +# MCP サーバーの設定 + +MCP サーバーの設定を表すプロフェッショナルなオーディオミキシングボードのノブとスライダーを調整する手 + +MCP の動作を確認したので、追加のサーバーを設定しましょう。サーバーを追加する方法は 2 つあります: **組み込みレジストリから**(最も簡単 — CLI 内でガイドされたセットアップ)または**設定ファイルを手動で編集**(より柔軟)。どちらを選ぶか確信がない場合はレジストリオプションから始めましょう。 + +--- + +## レジストリから MCP サーバーをインストールする + +CLI には、人気のサーバーをガイドされたセットアップで発見してインストールできる組み込みの MCP サーバーレジストリがあります — JSON の編集は不要です。 + +```bash +copilot + +> /mcp search +``` + +Copilot が利用可能なサーバーを示すインタラクティブなピッカーを開きます。1 つを選択すると、CLI が必要な設定(API キー、パスなど)を案内して、設定に自動的に追加します。 + +> 💡 **なぜレジストリを使うのですか?** 最も簡単に始める方法です — npm パッケージ名、コマンド引数、JSON 構造を知る必要がありません。CLI がすべてを処理します。 + +--- + +## MCP 設定ファイル + +MCP サーバーは `~/.copilot/mcp-config.json`(ユーザーレベル、すべてのプロジェクトに適用)または `.mcp.json`(プロジェクトレベル、プロジェクトのルートに配置)で設定されます。上記で `/mcp search` を使用した場合、CLI はすでにこのファイルを作成または更新しています。ただし、カスタマイズのためにフォーマットを理解しておくと便利です。 + +> ⚠️ **注意**: `.vscode/mcp.json` は MCP 設定ソースとしてサポートされなくなりました。既存の `.vscode/mcp.json` がある場合は、プロジェクトルートの `.mcp.json` に移行してください。古い設定ファイルを検出すると CLI が移行ヒントを表示します。 + +```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 サーバー](#filesystem-server) | +| 最新のライブラリドキュメントを取得する | [Context7 サーバー](#context7-server-documentation) | +| オプションの追加機能(カスタムサーバー、web_fetch)を探る | [基本を超えて](#beyond-the-basics) | + +
+Filesystem サーバー - Copilot がプロジェクトファイルを探索できるようにする + + +### Filesystem サーバー + +```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 を再起動します。 + +
+ +
+基本を超えて - カスタムサーバーと Web アクセス(オプション) + + +これらは上記のコアサーバーに慣れた後のオプションの追加機能です。 + +### Microsoft Learn MCP サーバー + +これまで見てきた MCP サーバー(filesystem、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 設定ファイルを手動で編集する代わりに、1 つのコマンドでインストールできます。 + +```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` で Web アクセス + +Copilot CLI には任意の URL からコンテンツを取得できる組み込みの `web_fetch` ツールが含まれています。ターミナルを離れずに README、API ドキュメント、リリースノートを引き込むのに便利です。MCP サーバーは不要です。 + +アクセス可能な URL を `~/.copilot/config.json`(一般的な Copilot 設定)で制御できます。これは `~/.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 サーバーを構築する + +独自の API、データベース、内部ツールに Copilot を接続したいですか?Python でカスタム MCP サーバーを構築できます。これは完全にオプションです。プリビルドのサーバー(GitHub、filesystem、Context7)がほとんどのユースケースをカバーします。 + +📖 ブックアプリを例として使った完全なウォークスルーは [カスタム MCP サーバーガイド](mcp-custom-server.md)を参照してください。 + +📚 さらなる背景については [MCP for Beginners コース](https://github.com/microsoft/mcp-for-beginners)を参照してください。 + +
+ + + +### 完全な設定ファイル + +filesystem と 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` として保存するか、プロジェクト固有の設定にはプロジェクトルートの `.mcp.json` として保存します。 + +--- + +# MCP サーバーを使う + +MCP サーバーを設定したので、何ができるかを見てみましょう。 + +MCP サーバーを使う - GitHub、Filesystem、Context7、カスタム/Web Fetch サーバーに接続された開発者 CLI を示すハブアンドスポーク図 + +--- + +## サーバーの使用例 + +**探索するサーバーを選ぶか、順番に進めてください。** + +| 試したいこと... | ジャンプ先 | +|---|---| +| GitHub のリポジトリ、イシュー、PR | [GitHub サーバー](#github-server-built-in) | +| プロジェクトファイルの参照 | [Filesystem サーバーの使用方法](#filesystem-server-usage) | +| ライブラリドキュメントの検索 | [Context7 サーバーの使用方法](#context7-server-usage) | +| カスタムサーバー、Microsoft Learn MCP、web_fetch の使用 | [基本を超えての使用方法](#beyond-the-basics-usage) | + +
+GitHub サーバー(組み込み) - リポジトリ、イシュー、PR などにアクセスする + + +### GitHub サーバー(組み込み) + +GitHub MCP サーバーは**組み込み**です。Copilot にログインした(初期設定時に行った)場合、すでに動作しています。設定は不要! + +> 💡 **動作しない場合?** `/login` を実行して GitHub で再認証してください。 + +
+開発コンテナでの認証 + +- **GitHub Codespaces**(推奨): 認証は自動的です。`gh` CLI は Codespace トークンを継承します。操作は不要です。 +- **ローカル開発コンテナ(Docker)**: コンテナ起動後に `gh auth login` を実行して、Copilot を再起動します。 + +**認証のトラブルシューティング:** +```bash +# 認証されているか確認する +gh auth status + +# されていない場合はログインする +gh auth login + +# GitHub MCP が接続されているか確認する +copilot +> /mcp show +``` + +
+ +| 機能 | 例 | +|---------|----------| +| **リポジトリ情報** | コミット、ブランチ、コントリビューターを表示する | +| **イシュー** | イシューをリストアップ、作成、検索、コメントする | +| **プルリクエスト** | PR、差分、PR 作成、ステータス確認 | +| **コード検索** | リポジトリ全体でコードを検索する | +| **Actions** | ワークフロー実行とステータスを照会する | + +```bash +copilot + +# このリポジトリの最近のアクティビティを確認する +> 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) +... + +# リポジトリ構造を探索する +> What branches exist in this repository? + +Branches: +- main (default) +- chapter6 (current) + +# リポジトリ全体でコードパターンを検索する +> Search this repository for files that import pytest + +Found 1 file: +- samples/book-app-project/tests/test_books.py +``` + +> 💡 **自分のフォークで作業していますか?** このコースリポジトリをフォークした場合、イシューの作成やプルリクエストなどの書き込み操作も試せます。以下の演習で練習します。 + +> ⚠️ **結果が表示されない?** GitHub MCP はローカルファイルだけでなく、リポジトリのリモート(github.com 上)で動作します。リポジトリにリモートがあることを確認してください: `git remote -v` で確認します。 + +
+ +
+Filesystem サーバー - プロジェクトファイルを参照・分析する + + +### Filesystem サーバー + +設定すると、filesystem 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 は公式の pytest パターンを知っており +# samples/book-app-project/tests/test_books.py に適用できる +``` + +
+ +
+基本を超えて - カスタムサーバーと web_fetch の使用方法 + + +### 基本を超えて + +**カスタム MCP サーバー**: [カスタム MCP サーバーガイド](mcp-custom-server.md)から book-lookup サーバーを構築した場合、書籍コレクションを直接照会できます。 + +```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**: 組み込みの `web_fetch` ツールを使って任意の URL からコンテンツを取得できます。 + +```bash +copilot + +> Fetch and summarize the README from https://github.com/facebook/react +``` + +
+ +--- + +## マルチサーバーワークフロー + +これらのワークフローは、開発者が「もうこれなしでは働きたくない」と言う理由を示しています。各例は 1 つのセッションで複数の MCP サーバーを組み合わせています。 + +MCP を使った issue から PR へのワークフロー - GitHub イシューの取得からプルリクエスト作成までの完全なフローを示す + +*完全な MCP ワークフロー: GitHub MCP がリポジトリデータを取得し、Filesystem MCP がコードを見つけ、Context7 MCP がベストプラクティスを提供し、Copilot が分析を処理する* + +以下の各例は独立しています。**興味のあるものを選ぶか、すべて読んでください。** + +| 見たいこと... | ジャンプ先 | +|---|---| +| 複数のサーバーが連携して動作する | [マルチサーバー探索](#multi-server-exploration) | +| 1 つのセッションでイシューから PR へ | [Issue-to-PR ワークフロー](#issue-to-pr-workflow) | +| クイックプロジェクト健全性チェック | [ヘルスダッシュボード](#health-dashboard) | + +
+マルチサーバー探索 - filesystem、GitHub、Context7 を 1 つのセッションで組み合わせる + + +#### 複数の MCP サーバーでブックアプリを探索する + +```bash +copilot + +# ステップ 1: filesystem MCP を使ってブックアプリを探索する +> 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 + +# ステップ 2: GitHub MCP を使って最近の変更を確認する +> 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) + +# ステップ 3: Context7 MCP でベストプラクティスを取得する +> 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 + +# ステップ 4: 推奨事項をまとめる +> 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) + +*デモの出力は異なります。モデル、ツール、レスポンスはここに表示されているものと異なります。* + +
+ +**結果**: コード探索 → 履歴確認 → ベストプラクティス検索 → 改善計画。**3 つの MCP サーバーを使って、すべて 1 つのターミナルセッションから。** + +
+ +
+Issue-to-PR ワークフロー - ターミナルを離れずに GitHub イシューからプルリクエストへ + + +#### Issue-to-PR ワークフロー(自分のリポジトリで) + +これは書き込みアクセスを持つ自分のフォークやリポジトリで最もよく機能します。 + +> 💡 **今すぐ試せなくても大丈夫です。** 読み取り専用クローンの場合、課題でこれを練習します。今はフローを理解するために読み進めてください。 + +```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 +``` + +**コピー&ペーストなし。コンテキスト切り替えなし。1 つのターミナルセッション。** + +
+ +
+ヘルスダッシュボード - 複数のサーバーを使ってクイックプロジェクト健全性チェックを行う + + +#### ブックアプリヘルスダッシュボード + +```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: Filesystem MCP でブックアプリを探索する + +filesystem サーバーを設定した場合は、ブックアプリを探索するために使います。 + +```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` とその関数をリストアップします。 + +> 💡 **filesystem MCP をまだ設定していませんか?** 上記の[完全な設定](#complete-configuration-file)セクションから設定ファイルを作成してください。そして 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 サーバーを組み合わせる + +filesystem と GitHub MCP を 1 つのセッションで組み合わせます。 + +```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 ファイルを読み込み(filesystem MCP)、「The Hobbit」、「1984」、「Dune」、「To Kill a Mockingbird」、「Mysterious Book」を含む 5 冊の本をリストアップし、コミット履歴を GitHub に照会します。 + +**自己確認**: 「`git log` を手動で実行してプロンプトに出力を貼り付けるより、『リポジトリのコミット履歴を確認して』の方がなぜ良いか」を説明できれば MCP を理解しています。 + +--- + +## 📝 課題 + +### メインチャレンジ: ブックアプリ MCP 探索 + +ブックアプリプロジェクトで MCP サーバーを一緒に使う練習をしましょう。1 つの Copilot セッションでこれらのステップを完了します。 + +1. **MCP が動作していることを確認する**: `/mcp show` を実行して少なくとも GitHub サーバーが有効になっていることを確認する +2. **filesystem MCP を設定する**(まだの場合): filesystem サーバーの設定で `~/.copilot/mcp-config.json` を作成する +3. **コードを探索する**: filesystem サーバーを使って Copilot に以下を依頼する: + - `samples/book-app-project/books.py` のすべての関数をリストアップする + - `samples/book-app-project/utils.py` で型ヒントが欠けている関数を確認する + - `samples/book-app-project/data.json` を読んでデータ品質の問題を特定する(ヒント: 最後のエントリを確認する) +4. **リポジトリアクティビティを確認する**: GitHub MCP を使って Copilot に以下を依頼する: + - `samples/book-app-project/` のファイルに触れた最近のコミットをリストアップする + - オープンなイシューやプルリクエストがあるか確認する +5. **サーバーを組み合わせる**: 1 つのプロンプトで Copilot に以下を依頼する: + - `samples/book-app-project/tests/test_books.py` のテストファイルを読む + - テストされた関数を `books.py` のすべての関数と比較する + - 欠けているテストカバレッジをまとめる + +**成功基準**: 1 つの Copilot セッションで filesystem と GitHub MCP データをシームレスに組み合わせ、各 MCP サーバーがレスポンスに何を貢献したかを説明できます。 + +
+💡 ヒント(クリックして展開) + +**ステップ 1: MCP を確認する** +```bash +copilot +> /mcp show +# "github" が有効として表示されるはず +# 表示されない場合は実行: /login +``` + +**ステップ 2: 設定ファイルを作成する** + +上記の[完全な設定](#complete-configuration-file)セクションの JSON を使って `~/.copilot/mcp-config.json` として保存します。 + +**ステップ 3: 探すデータ品質の問題** + +`data.json` の最後の本は以下です: +```json +{ + "title": "Mysterious Book", + "author": "", + "year": 0, + "read": false +} +``` +著者が空で年が 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.md)に従って、任意の API に接続する Python の独自 MCP サーバーを構築してください。 + +--- + +
+🔧 よくある間違いとトラブルシューティング(クリックして展開) + +### よくある間違い + +| 間違い | 何が起こるか | 対処法 | +|---------|--------------|-----| +| GitHub MCP が組み込みであることを知らない | 手動でインストール/設定しようとする | GitHub MCP はデフォルトで含まれている。試してみてください: 「List the recent commits in this repo」 | +| 設定が間違った場所にある | MCP 設定を見つけたり編集できない | ユーザーレベルの設定は `~/.copilot/mcp-config.json`、プロジェクトレベルはプロジェクトルートの `.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 +# サーバーがリストされて有効になっているか確認する +``` + +サーバーが無効の場合、再有効化の方法は以下の[追加の `/mcp` コマンド](#-additional-mcp-commands)を参照してください。 + +
+ +--- + +
+📚 追加の MCP コマンド(クリックして展開) + + +MCP サーバーを管理する方法は 2 つあります: **チャットセッション内のスラッシュコマンド**を使うか、**ターミナルから直接 `copilot mcp` コマンド**を使います(チャットセッション不要)。 + +### オプション 1: スラッシュコマンド(チャットセッション内) + +`copilot` 内にいるときに機能します: + +| コマンド | 機能 | +|---------|--------------| +| `/mcp show` | 設定されたすべての MCP サーバーとそのステータスを表示する | +| `/mcp add` | 新しいサーバーを追加するためのインタラクティブなセットアップ | +| `/mcp edit ` | 既存のサーバー設定を編集する | +| `/mcp enable ` | 無効なサーバーを有効にする(セッション間で持続する) | +| `/mcp disable ` | サーバーを無効にする(セッション間で持続する) | +| `/mcp delete ` | サーバーを恒久的に削除する | +| `/mcp auth ` | OAuth を使う MCP サーバーで再認証する(例: アカウントを切り替えた後) | + +### オプション 2: `copilot mcp` コマンド(ターミナルから) + +チャットセッションを開始せずにターミナルから直接 MCP サーバーを管理することもできます: + +```bash +# 設定されたすべての MCP サーバーをリストアップする +copilot mcp list + +# サーバーを有効にする +copilot mcp enable filesystem + +# サーバーを無効にする +copilot mcp disable context7 +``` + +> 💡 **どちらをいつ使うか?** チャットセッション中はすでにいる場合は `/mcp` スラッシュコマンドを使います。セッションを始める前にサーバー設定を素早く確認・変更したい場合はターミナルから `copilot mcp` を使います。 + +このコースのほとんどでは、`/mcp show` があれば十分です。他のコマンドは時間をかけてより多くのサーバーを管理するにつれて便利になります。 + +
+ +--- + +# まとめ + +## 🔑 重要なポイント + +1. **MCP** は Copilot を外部サービス(GitHub、filesystem、ドキュメント)に接続する +2. **GitHub MCP は組み込み** - 設定は不要、`/login` だけ +3. **Filesystem と Context7** は `~/.copilot/mcp-config.json` で設定する +4. **マルチサーバーワークフロー**は 1 つのセッションで複数のソースからデータを組み合わせる +5. **サーバーを管理する 2 つの方法**: チャット内の `/mcp` スラッシュコマンド、またはターミナルからの `copilot mcp` を使う +6. **カスタムサーバー**はどの API にも接続できる(オプション、付録ガイドでカバー) + +> 📋 **クイックリファレンス**: コマンドとキーボードショートカットの完全なリストは [GitHub Copilot CLI コマンドリファレンス](https://docs.github.com/en/copilot/reference/cli-command-reference)をご覧ください。 + +--- + +## ➡️ 次のステップ + +これですべてのビルディングブロックが揃いました: モード、コンテキスト、ワークフロー、エージェント、スキル、MCP。すべてを組み合わせる時間です。 + +**[第 07 章: すべてをまとめる](../07-putting-it-together/README.md)**では以下を学びます。 + +- エージェント、スキル、MCP を統合ワークフローで組み合わせる +- アイデアからマージされた PR までの完全な機能開発 +- フックによる自動化 +- チーム環境でのベストプラクティス + +--- + +**[← 第 05 章に戻る](../05-skills/README.md)** | **[第 07 章に進む →](../07-putting-it-together/README.md)** diff --git a/localization/ja-jp/06-mcp-servers/mcp-custom-server.md b/localization/ja-jp/06-mcp-servers/mcp-custom-server.md new file mode 100644 index 00000000..49c9400c --- /dev/null +++ b/localization/ja-jp/06-mcp-servers/mcp-custom-server.md @@ -0,0 +1,176 @@ +# カスタム MCP サーバーを構築する + +> ⚠️ **この内容は完全にオプションです。** プリビルドの MCP サーバー(GitHub、filesystem、Context7)だけで Copilot CLI を非常に生産的に使えます。このガイドはカスタムの内部 API に Copilot を接続したい開発者向けです。詳細は [MCP for Beginners コース](https://github.com/microsoft/mcp-for-beginners)を参照してください。 +> +> **前提条件:** +> - Python に慣れている +> - `async`/`await` パターンを理解している +> - システムで `pip` が利用可能(この開発コンテナに含まれている) +> +> **[← 第 06 章: MCP サーバーに戻る](README.md)** + +--- + +Copilot を独自の API に接続したいですか?このコース全体で使用してきたブックアプリプロジェクトに結び付けて、書籍情報を検索するシンプルな MCP サーバーを Python で構築する方法を説明します。 + +## プロジェクトのセットアップ + +```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 + +# MCP サーバーを作成する +mcp = FastMCP("book-lookup") + +# サンプル書籍データベース(実際のサーバーでは API やデータベースを照会できる) +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 が呼び出せるツールとして登録する | +| 型ヒント + ドキュメント文字列 | 各ツールが何をするか、どのパラメータが必要かを Copilot に伝える | +| `mcp.run()` | サーバーを起動してリクエストを待機する | + +> 💡 **なぜデコレーターを使うのですか?** `@mcp.tool()` デコレーターだけで十分です。MCP SDK は関数の名前、型ヒント、ドキュメント文字列を自動的に読み込んでツールスキーマを生成します。手動の JSON スキーマは不要です! + +## 設定 + +`~/.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 + +[データベース内のすべての本を ISBN とともに表示する] +``` + +## 次のステップ + +基本的なサーバーを構築したら、以下ができます。 + +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 for Beginners コース](https://github.com/microsoft/mcp-for-beginners) + +--- + +**[← 第 06 章: MCP サーバーに戻る](README.md)** diff --git a/localization/ja-jp/07-putting-it-together/README.md b/localization/ja-jp/07-putting-it-together/README.md new file mode 100644 index 00000000..f585deee --- /dev/null +++ b/localization/ja-jp/07-putting-it-together/README.md @@ -0,0 +1,512 @@ +![第 07 章: すべてをまとめる](../../../images/chapter-header.png) + +> **学んだすべてがここで融合します。1 つのセッションでアイデアからマージされた PR へ。** + +この章では、学んだすべてを完全なワークフローにまとめます。マルチエージェントのコラボレーションを使って機能を構築し、コミット前にセキュリティの問題を検出するプリコミットフックを設定し、Copilot を CI/CD パイプラインに統合し、1 つのターミナルセッションで機能のアイデアからマージされた PR へ進みます。これが GitHub Copilot CLI が真のフォースマルチプライヤーになる場所です。 + +> 💡 **注意**: この章では学んだすべてを組み合わせる方法を示します。**エージェント、スキル、MCP がなくても生産的になれます(非常に便利ですが)。** コアワークフロー — 説明、計画、実装、テスト、レビュー、リリース — は第 00〜03 章の組み込み機能だけで機能します。 + +## 🎯 学習目標 + +この章を終えると、以下ができるようになります。 + +- エージェント、スキル、MCP(Model Context Protocol)を統合ワークフローで組み合わせる +- マルチツールアプローチを使って完全な機能を構築する +- フックで基本的な自動化を設定する +- プロフェッショナルな開発のベストプラクティスを適用する + +> ⏱️ **目安時間**: 約 75 分(15 分読む + 60 分ハンズオン) + +--- + +## 🧩 現実世界のたとえ話: オーケストラ + +オーケストラのたとえ話 - 統合ワークフロー + +交響楽団には多くのセクションがあります: +- **弦楽器**が基礎を提供する(コアワークフローのように) +- **金管楽器**が力を加える(特化した専門知識を持つエージェントのように) +- **木管楽器**が色を加える(機能を拡張するスキルのように) +- **打楽器**がリズムを刻む(外部システムに接続する MCP のように) + +個々では各セクションの音は限られています。一緒に、うまく指揮されると、素晴らしいものが生まれます。 + +**この章が教えることがそれです!**
+*指揮者がオーケストラを指揮するように、エージェント、スキル、MCP を統合ワークフローに指揮する* + +コードを変更し、テストを生成し、レビューし、PR を作成するシナリオを 1 つのセッションでウォークスルーすることから始めましょう。 + +--- + +## 1 つのセッションでアイデアからマージされた PR へ + +エディター、ターミナル、テストランナー、GitHub UI の間を切り替えてコンテキストを失うのではなく、1 つのターミナルセッションですべてのツールを組み合わせることができます。このパターンは以下の[統合パターン](#the-integration-pattern-for-power-users)セクションで詳しく説明します。 + +```bash +# インタラクティブモードで Copilot を起動する +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 が高レベルの計画を作成する... + +# PYTHON-REVIEWER エージェントに切り替える +> /agent +# "python-reviewer" を選択する + +> @samples/book-app-project/books.py Design a get_unread_books method. +> What is the best approach? + +# python-reviewer エージェントが生成するもの: +# - メソッドシグネチャと戻り型 +# - リスト内包表記を使ったフィルター実装 +# - 空のコレクションのエッジケース処理 + +# PYTEST-HELPER エージェントに切り替える +> /agent +# "pytest-helper" を選択する + +> @samples/book-app-project/tests/test_books.py Design test cases for +> filtering unread books. + +# pytest-helper エージェントが生成するもの: +# - 空のコレクションのテストケース +# - 読了/未読の本が混在するテストケース +# - すべての本が読了済みのテストケース + +# 実装する +> 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 + +# テストする +> Generate comprehensive tests for the new feature + +# 以下のようなテストが複数生成される: +# - ハッピーパス(3 テスト)— 正しくフィルタリング、読了済みを除外、未読を含む +# - エッジケース(4 テスト)— 空のコレクション、すべて読了、未読なし、1 冊 +# - パラメータ化(5 ケース)— @pytest.mark.parametrize で読了/未読の比率を変える +# - 統合(4 テスト)— mark_as_read、remove_book、add_book、データ整合性との連携 + +# 変更をレビューする +> /review + +# レビューが通ったら /pr を使って現在のブランチのプルリクエストを操作する +> /pr [view|create|fix|auto] + +# または Copilot にターミナルから下書きを作成させたい場合は自然に聞く +> 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 が効果をどのように乗数倍するかを示します。 + +## 統合パターン + +すべてを組み合わせるためのメンタルモデルです。 + +統合パターン - 4 フェーズのワークフロー: コンテキストの収集(MCP)、分析と計画(エージェント)、実行(スキル + 手動)、完了(MCP) + +--- + +## ワークフロー 1: バグ調査と修正 + +完全なツール統合による実際のバグ修正: + +```bash +copilot + +# フェーズ 1: GitHub からバグを理解する(MCP がこれを提供する) +> Get the details of issue #1 + +# 学ぶ: "find_by_author は部分的な名前では機能しない" + +# フェーズ 2: ベストプラクティスを調査する(Web と GitHub ソースで深く調査する) +> /research Best practices for Python case-insensitive string matching + +# フェーズ 3: 関連するコードを見つける +> @samples/book-app-project/books.py Show me the find_by_author method + +# フェーズ 4: 専門家の分析を取得する +> /agent +# "python-reviewer" を選択する + +> Analyze this method for issues with partial name matching + +# エージェントが特定する: メソッドが部分文字列マッチではなく完全一致を使っている + +# フェーズ 5: エージェントのガイダンスで修正する +> Implement the fix using lowercase comparison and 'in' operator + +# フェーズ 6: テストを生成する +> /agent +# "pytest-helper" を選択する + +> Generate pytest tests for find_by_author with partial matches +> Include test cases: partial name, case variations, no matches + +# フェーズ 7: コミットして PR を作成する +> Generate a commit message for this fix + +> Create a pull request linking to issue #1 +``` + +--- + +## ワークフロー 2: コードレビューの自動化(オプション) + +> 💡 **このセクションはオプションです。** プリコミットフックはチームに便利ですが、生産性向上のために必須ではありません。始めたばかりであればスキップしてください。 +> +> ⚠️ **パフォーマンスに関する注意**: このフックは各ステージされたファイルに対して `copilot -p` を呼び出し、ファイルごとに数秒かかります。大きなコミットでは、重要なファイルに制限するか、代わりに `/review` で手動でレビューを実行することを検討してください。 + +**git フック**は Git が特定の時点(例えばコミット直前)に自動的に実行するスクリプトです。これを使ってコードの自動チェックを実行できます。コミットで自動的な Copilot レビューを設定する方法です。 + +```bash +# プリコミットフックを作成する +cat > .git/hooks/pre-commit << 'EOF' +#!/bin/bash + +# ステージされたファイルを取得する(Python ファイルのみ) +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..." + + # タイムアウトを使ってハングを防ぐ(ファイルごとに 60 秒) + # --allow-all はファイルの読み書きを自動承認するのでフックが無人で実行できる。 + # これは自動化されたスクリプトでのみ使用する。インタラクティブなセッションでは Copilot に許可を求めさせる。 + REVIEW=$(timeout 60 copilot --allow-all -p "Quick security review of @$file - critical issues only" 2>/dev/null) + + # タイムアウトが発生したか確認する + 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 ユーザーへ**: `timeout` コマンドは macOS にデフォルトで含まれていません。`brew install coreutils` でインストールするか、タイムアウトガードなしのシンプルな呼び出しに `timeout 60` を置き換えてください。 + +> 📚 **公式ドキュメント**: [フックを使う](https://docs.github.com/copilot/how-tos/copilot-cli/use-hooks)と[フック設定リファレンス](https://docs.github.com/copilot/reference/hooks-configuration) - 完全なフック API。 +> +> 💡 **組み込みの代替手段**: Copilot CLI にはプリコミットなどのイベントで自動的に実行できる組み込みフックシステム(`copilot hooks`)もあります。上記の手動 git フックは完全な制御を提供し、組み込みシステムは設定が簡単です。どちらのアプローチがワークフローに合うかは上記のドキュメントを参照してください。 + +これですべてのコミットがクイックなセキュリティレビューを受けます。 + +```bash +git add samples/book-app-project/books.py +git commit -m "Update book collection methods" + +# 出力: +# 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 +# インタラクティブモードで Copilot を起動する +copilot + +# フェーズ 1: コンテキストで全体像を把握する +> @samples/book-app-project/ Explain the high-level architecture of this codebase + +# フェーズ 2: 特定のフローを理解する +> @samples/book-app-project/book_app.py Walk me through what happens +> when a user runs "python book_app.py add" + +# フェーズ 3: エージェントで専門家の分析を取得する +> /agent +# "python-reviewer" を選択する + +> @samples/book-app-project/books.py Are there any design issues, +> missing error handling, or improvements you would recommend? + +# フェーズ 4: 作業するものを見つける(MCP が GitHub アクセスを提供する) +> List open issues labeled "good first issue" + +# フェーズ 5: コントリビューションを始める +> Pick the simplest open issue and outline a plan to fix it +``` + +このワークフローは `@` コンテキスト、エージェント、MCP を 1 つのオンボーディングセッションに組み合わせます。この章の前半の統合パターンそのものです。 + +--- + +# ベストプラクティスと自動化 + +ワークフローをより効果的にするパターンと習慣です。 + +--- + +## ベストプラクティス + +### 1. 分析の前にコンテキストを収集する + +分析を求める前に常にコンテキストを収集します。 + +```bash +# 良い例 +> Get the details of issue #42 +> /agent +# python-reviewer を選択する +> Analyze this issue + +# 効果の低い例 +> /agent +# python-reviewer を選択する +> Fix login bug +# エージェントがイシューのコンテキストを持っていない +``` + +### 2. エージェント、スキル、カスタム指示の違いを知る + +各ツールには得意な領域があります。 + +```bash +# エージェント: 明示的に有効化する特化したペルソナ +> /agent +# python-reviewer を選択する +> Review this authentication code for security issues + +# スキル: プロンプトがスキルの説明と一致するときに自動的に有効化されるモジュラー機能 +# (使用するには事前に作成する必要がある — 第 05 章を参照) +> Generate comprehensive tests for this code +# テストスキルが設定されていれば自動的に有効化される + +# カスタム指示(.github/copilot-instructions.md): 切り替えやトリガーなしで +# すべてのセッションに適用される常時オンのガイダンス +``` + +> 💡 **重要なポイント**: エージェントもスキルもコードの分析と生成の両方ができます。本当の違いは**有効化の方法** — エージェントは明示的(`/agent`)、スキルは自動(プロンプトマッチ)、カスタム指示は常時オン。 + +### 3. セッションを集中させる + +セッションにラベルを付けるために `/rename` を使い(履歴で簡単に見つけられる)、クリーンに終了するために `/exit` を使います。 + +```bash +# 良い例: セッションごとに 1 つの機能 +> /rename list-unread-feature +# 未読リストの作業をする +> /exit + +copilot +> /rename export-csv-feature +# CSV エクスポートの作業をする +> /exit + +# 効果の低い例: すべてを 1 つの長いセッションで +``` + +### 4. Copilot でワークフローを再利用可能にする + +ワークフローを Wiki に文書化するだけでなく、Copilot が使えるリポジトリに直接エンコードします。 + +- **カスタム指示**(`.github/copilot-instructions.md`): コーディング標準、アーキテクチャルール、ビルド/テスト/デプロイのステップのための常時オンガイダンス。すべてのセッションが自動的に従う。 +- **プロンプトファイル**(`.github/prompts/`): チームが共有できる再利用可能でパラメータ化されたプロンプト — コードレビュー、コンポーネント生成、PR の説明のテンプレートのようなもの。 +- **カスタムエージェント**(`.github/agents/`): チームの誰もが `/agent` で有効化できる特化したペルソナ(例: セキュリティレビュアーやドキュメントライター)をエンコードする。 +- **カスタムスキル**(`.github/skills/`): 関連するときに自動有効化されるステップバイステップのワークフロー指示をパッケージ化する。 + +> 💡 **成果**: 新しいチームメンバーがワークフローを無料で得られます — リポジトリに組み込まれており、誰かの頭の中にロックされていません。 + +--- + +## ボーナス: プロダクションパターン + +これらはオプションですが、プロフェッショナルな環境で価値があります。 + +### PR 説明ジェネレーター + +```bash +# 包括的な PR の説明を生成する +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 レビューを自動化できます。これにはレビューコメントの自動投稿と重要な問題のフィルタリングが含まれます。 + +> 📖 **詳細**: 完全な GitHub Actions ワークフロー、設定オプション、トラブルシューティングのヒントは [CI/CD 統合](../appendices/ci-cd-integration.md)を参照してください。 + +--- + +# 練習 + +コードが表示されたモニター、ランプ、コーヒーカップ、ヘッドホンが置かれた居心地の良いデスク + +完全なワークフローを実践しましょう。 + +--- + +## ▶️ 自分で試してみよう + +デモを完了した後、これらのバリエーションを試してみましょう。 + +1. **エンドツーエンドチャレンジ**: 小さな機能を選んでください(例:「未読の本をリストアップ」または「CSV にエクスポート」)。完全なワークフローを使います: + - `/plan` で計画する + - エージェントで設計する(python-reviewer、pytest-helper) + - 実装する + - テストを生成する + - PR を作成する + +2. **自動化チャレンジ**: コードレビューの自動化ワークフローのプリコミットフックを設定します。意図的なファイルパスの脆弱性でコミットを作成します。ブロックされますか? + +3. **自分のプロダクションワークフロー**: よく行う一般的なタスクの独自のワークフローを設計します。チェックリストとして書き留めます。どの部分をスキル、エージェント、フックで自動化できますか? + +**自己確認**: エージェント、スキル、MCP がどのように連携するか、そしてそれぞれをいつ使うかを同僚に説明できれば、コースを完了しています。 + +--- + +## 📝 課題 + +### メインチャレンジ: エンドツーエンドの機能 + +ハンズオン例では「未読の本をリストアップ」機能の構築をウォークスルーしました。今度は別の機能の完全なワークフローを練習しましょう: **年の範囲で本を検索する**: + +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 エージェントと README 更新のための doc-writer エージェント。 + +
+💡 ヒント(クリックして展開) + +**この章の上部にある[「アイデアからマージされた 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` を使ってアプローチを考える | +| 1 つのツールだけ使う | 遅く、徹底性に欠ける | 組み合わせる: 分析にエージェント → 実行にスキル → 統合に MCP | +| コミット前にレビューしない | セキュリティの問題やバグが見過ごされる | 常に `/review` を実行するか[プリコミットフック](#workflow-2-code-review-automation-optional)を使う | +| ワークフローをチームと共有しない | 各人がゼロから発明する | 共有エージェント、スキル、指示にパターンを文書化する | + +
+ +--- + +# まとめ + +## 🔑 重要なポイント + +1. **統合 > 孤立**: 最大の効果のためにツールを組み合わせる +2. **コンテキストが先**: 分析の前に必要なコンテキストを常に収集する +3. **エージェントが分析し、スキルが実行する**: 適切なジョブに適切なツールを使う +4. **繰り返しを自動化する**: フックとスクリプトが効果を乗数倍する +5. **ワークフローを文書化する**: 共有可能なパターンがチーム全体に恩恵をもたらす + +> 📋 **クイックリファレンス**: コマンドとキーボードショートカットの完全なリストは [GitHub Copilot CLI コマンドリファレンス](https://docs.github.com/en/copilot/reference/cli-command-reference)をご覧ください。 + +--- + +## 🎓 コース完了! + +おめでとうございます!以下を学びました。 + +| 章 | 学んだこと | +|---------|-------------------| +| 00 | Copilot CLI のインストールとクイックスタート | +| 01 | 3 つのインタラクションモード | +| 02 | @ 構文によるコンテキスト管理 | +| 03 | 開発ワークフロー | +| 04 | 特化したエージェント | +| 05 | 拡張可能なスキル | +| 06 | MCP による外部接続 | +| 07 | 統合プロダクションワークフロー | + +これで GitHub Copilot CLI を開発ワークフローの真のフォースマルチプライヤーとして使う準備が整いました。 + +## ➡️ 次のステップ + +学習はここで止まりません: + +1. **毎日練習する**: 実際の作業に Copilot CLI を使う +2. **カスタムツールを構築する**: 特定のニーズに合わせたエージェントとスキルを作成する +3. **知識を共有する**: チームがこれらのワークフローを採用するのを助ける +4. **最新情報を追う**: 新機能のために GitHub Copilot の更新情報をフォローする + +### リソース + +- [GitHub Copilot CLI ドキュメント](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) +- [MCP サーバーレジストリ](https://github.com/modelcontextprotocol/servers) +- [コミュニティスキル](https://github.com/topics/copilot-skill) + +--- + +**素晴らしい仕事をしました!今度は素晴らしいものを作りましょう。** + +**[← 第 06 章に戻る](../06-mcp-servers/README.md)** | **[コースホームに戻る →](../README.md)** diff --git a/localization/ja-jp/README.md b/localization/ja-jp/README.md new file mode 100644 index 00000000..58ff8126 --- /dev/null +++ b/localization/ja-jp/README.md @@ -0,0 +1,110 @@ +![GitHub Copilot CLI for Beginners](../../images/copilot-banner.png) + +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](../../LICENSE)  +[![Open project in 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)  +[![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  +[![Join 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) + +# GitHub Copilot CLI for Beginners + +> **✨ AI を活用したコマンドライン支援で、開発ワークフローを超強化する方法を学びましょう。** + +GitHub Copilot CLI は、AI 支援機能をターミナルに直接提供します。ブラウザやコードエディタに切り替えることなく、コマンドラインを離れずに質問したり、フル機能のアプリケーションを生成したり、コードをレビューしたり、テストを生成したり、問題をデバッグしたりできます。 + +24 時間 365 日利用可能な知識豊富な同僚のようなもので、コードを読んで複雑なパターンを説明し、より速く作業できるよう手伝ってくれます! + +> 📘 **Web 体験をご希望ですか?** このコースは GitHub 上でそのまま進めることも、[Awesome Copilot](https://awesome-copilot.github.com/learning-hub/cli-for-beginners/) で従来のブラウジング体験として閲覧することもできます。 + +このコースは以下の方を対象としています。 + +- コマンドラインから AI を活用したい**ソフトウェア開発者** +- IDE 統合よりキーボード主体のワークフローを好む**ターミナルユーザー** +- AI を活用したコードレビューと開発プラクティスを標準化したい**チーム** + + + + GitHub Copilot Dev Days - イベントを見つけるか開催しましょう + + + +## 🎯 学習内容 {#what-youll-learn} + +このハンズオンコースは、GitHub Copilot CLI をゼロから実践的に使いこなせるようになることを目的としています。すべての章を通して 1 つの Python 製ブックコレクションアプリを使用し、AI 支援ワークフローで段階的に改善します。最終的には、ターミナルからコードのレビュー、テスト生成、バグのデバッグ、ワークフローの自動化を自信を持って行えるようになります。 + +**AI 経験は不要です。** ターミナルが使えれば、このコースを学ぶことができます。 + +**最適な対象者:** 開発者、学生、ソフトウェア開発の経験がある方。 + +## ✅ 前提条件 {#prerequisites} + +開始前に、以下を準備してください。 + +- **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 ファミリーを理解する {#understanding-the-github-copilot-family} + +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 など | エージェントモード、チャット、インライン提案 | +| [**Copilot on GitHub.com**](https://github.com/copilot) | GitHub | リポジトリに関する本格的なチャット、エージェント作成など | +| [**GitHub Copilot cloud agent**](https://docs.github.com/copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks) | GitHub | Issue をエージェントに割り当て、PR を受け取る | + +このコースは **GitHub Copilot CLI** に焦点を当て、AI 支援機能をターミナルに直接提供します。 + +## 📚 コース構成 {#course-structure} + +![GitHub Copilot CLI 学習パス](../../images/learning-path.png) + +| 章 | タイトル | 作るもの | +|:-------:|-------|-------------------| +| 00 | 🚀 [クイックスタート](./00-quick-start/README.md) | インストールと動作確認 | +| 01 | 👋 [はじめの一歩](./01-setup-and-first-steps/README.md) | ライブデモと 3 つのインタラクションモード | +| 02 | 🔍 [コンテキストと会話](./02-context-conversations/README.md) | マルチファイルプロジェクト分析 | +| 03 | ⚡ [開発ワークフロー](./03-development-workflows/README.md) | コードレビュー、デバッグ、テスト生成 | +| 04 | 🤖 [特化型 AI アシスタントの作成](./04-agents-custom-instructions/README.md) | ワークフロー向けカスタムエージェント | +| 05 | 🛠️ [繰り返し作業の自動化](./05-skills/README.md) | 自動的に読み込まれるスキル | +| 06 | 🔌 [GitHub・データベース・API との連携](./06-mcp-servers/README.md) | MCP サーバーの統合 | +| 07 | 🎯 [すべてを組み合わせる](./07-putting-it-together/README.md) | 完全な機能ワークフロー | + +## 📖 このコースの進め方 + +各章は同じパターンで構成されています。 + +1. **現実世界のたとえ話**: 身近な比較でコンセプトを理解する +2. **コアコンセプト**: 必須知識を学ぶ +3. **ハンズオン例**: 実際のコマンドを実行して結果を確認する +4. **課題**: 学んだことを実践する +5. **次のステップ**: 次の章のプレビュー + +**コード例は実行可能です。** このコースのすべての copilot テキストブロックは、コピーしてターミナルで実行できます。 + +## 📋 GitHub Copilot CLI コマンドリファレンス {#-github-copilot-cli-command-reference} + +**[GitHub Copilot CLI コマンドリファレンス](https://docs.github.com/en/copilot/reference/cli-command-reference)** では、Copilot CLI を効果的に使うためのコマンドやキーボードショートカットを確認できます。 + +## 🙋 ヘルプを得るには + +- 🐛 **バグを見つけた場合?** [Issue を開く](https://github.com/github/copilot-cli-for-beginners/issues) +- 📚 **公式ドキュメント:** [GitHub Copilot CLI ドキュメント](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) + +## コントリビュート + +> **注意**: コースで使用されているコードは、レビュー・説明・デバッグ中に特定の種類の出力を生成するよう設計されているため、既存のコードを変更する PR は受け付けられません。 + +**コントリビュートの方法:** + +1. このリポジトリをフォークして自分のマシンにクローンする +2. フィーチャーブランチを作成する (`git checkout -b my-improvement`) +3. 変更を加える +4. プルリクエストを提出する + +## ライセンス + +このプロジェクトは MIT オープンソースライセンスの条件のもとでライセンスされています。詳細な条件については [LICENSE](../../LICENSE) ファイルを参照してください。 diff --git a/localization/ja-jp/appendices/README.md b/localization/ja-jp/appendices/README.md new file mode 100644 index 00000000..a34f276d --- /dev/null +++ b/localization/ja-jp/appendices/README.md @@ -0,0 +1,12 @@ +# 付録 + +これらの付録は、コアコースの内容を拡張する追加トピックをカバーします。特定の機能が必要なときのオプションの読み物です。 + +| 付録 | 説明 | 前提条件 | +|----------|-------------|--------------| +| [追加のコンテキスト機能](additional-context.md) | 画像の操作と複数ディレクトリの権限管理 | 第 02 章 | +| [CI/CD 統合](ci-cd-integration.md) | 自動レビューのための GitHub Actions ワークフロー | 第 07 章 | + +--- + +**[← コースホームに戻る](../README.md)** diff --git a/localization/ja-jp/appendices/additional-context.md b/localization/ja-jp/appendices/additional-context.md new file mode 100644 index 00000000..4738fc19 --- /dev/null +++ b/localization/ja-jp/appendices/additional-context.md @@ -0,0 +1,140 @@ +# 追加のコンテキスト機能 + +> 📖 **前提条件**: この付録を読む前に[第 02 章: コンテキストと会話](../02-context-conversations/README.md)を完了してください。 + +この付録では 2 つの追加コンテキスト機能をカバーします: 画像の操作と複数ディレクトリにわたる権限管理です。 + +--- + +## 画像の操作 + +`@` 構文を使って会話に画像を含めることができます。Copilot はスクリーンショット、モックアップ、図表、その他のビジュアルコンテンツを分析できます。 + +### 基本的な画像の参照 + +```bash +copilot + +> @screenshot.png この UI で何が起きていますか? + +# Copilot が画像を分析して応答する + +> @mockup.png @current-design.png これら 2 つのデザインを比較してください + +# 画像をドラッグ&ドロップするか、クリップボードから貼り付けることもできる +``` + +### サポートされている画像フォーマット + +| フォーマット | 最適な用途 | +|--------|----------| +| 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 の 2 つのバージョンで何が変わりましたか? +``` + +### 画像とコードの組み合わせ + +画像はコードのコンテキストと組み合わせるとさらに強力になります: + +```bash +copilot + +> @screenshot-of-bug.png @src/components/Header.jsx +> スクリーンショットではヘッダーがおかしく見えます。コードのどこが原因ですか? +``` + +### 画像のヒント + +- **スクリーンショットをトリミングする** — 関連する部分だけ表示する(コンテキストトークンを節約できる) +- **高コントラストを使う** — 分析してほしい UI 要素には高コントラストが効果的 +- **必要に応じてアノテーションを付ける** — アップロード前に問題箇所を丸で囲んだりハイライトしたりする +- **1 つのコンセプトに 1 枚の画像** — 複数の画像も使えるが、焦点を絞ること + +--- + +## 権限パターン + +デフォルトでは、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 +# 許可されているすべてのディレクトリを確認する + +> /yolo +# /allow-all のクイックエイリアス — すべての権限プロンプトを自動承認する +``` + +### 自動化のために + +```bash +# 非インタラクティブなスクリプトのためにすべての権限を許可する +copilot -p "Review @src/" --allow-all + +# または覚えやすいエイリアスを使う +copilot -p "Review @src/" --yolo +``` + +### 複数ディレクトリアクセスが必要なとき + +これらの権限が必要となる一般的なシナリオ: + +1. **モノレポ作業** — パッケージ間でコードを比較する +2. **クロスプロジェクトのリファクタリング** — 共有ライブラリを更新する +3. **ドキュメントプロジェクト** — 複数のコードベースを参照する +4. **移行作業** — 古い実装と新しい実装を比較する + +--- + +**[← 第 02 章に戻る](../02-context-conversations/README.md)** | **[付録に戻る](README.md)** diff --git a/localization/ja-jp/appendices/ci-cd-integration.md b/localization/ja-jp/appendices/ci-cd-integration.md new file mode 100644 index 00000000..0a007931 --- /dev/null +++ b/localization/ja-jp/appendices/ci-cd-integration.md @@ -0,0 +1,199 @@ +# CI/CD 統合 + +> 📖 **前提条件**: この付録を読む前に[第 07 章: すべてをまとめる](../07-putting-it-together/README.md)を完了してください。 +> +> ⚠️ **この付録は既存の CI/CD パイプラインを持つチーム向けです。** GitHub Actions や CI/CD の概念に不慣れな場合は、第 07 章の[コードレビューの自動化](../07-putting-it-together/README.md#workflow-3-code-review-automation-optional)セクションにあるよりシンプルなプリコミットフックのアプローチから始めてください。 + +この付録では、プルリクエストの自動コードレビューのために GitHub Copilot CLI を CI/CD パイプラインに統合する方法を示します。 + +--- + +## GitHub Actions ワークフロー + +このワークフローはプルリクエストが開かれたり更新されたりしたとき、変更されたファイルを自動的にレビューします: + +```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 # メインブランチとの比較に必要 + + - 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 レビューボット + +より高度なレビューワークフローには、GitHub Copilot クラウドエージェントの使用を検討してください: + +```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 で「認証に失敗しました」 + +ワークフローに正しい権限があることを確認します: + +```yaml +permissions: + contents: read + pull-requests: write + issues: write +``` + +### レビューがタイムアウトする + +タイムアウトを増やすかスコープを減らします: + +```bash +timeout 120 copilot --allow-all -p "Quick review of @$file - critical issues only" --silent +``` + +### 大きなファイルでトークン制限に達する + +非常に大きなファイルをスキップします: + +```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.md)** | **[付録に戻る](README.md)** From 90877ea37bec5331a7e5c45f15ab6d8a319a7ff5 Mon Sep 17 00:00:00 2001 From: Justin Yoo Date: Wed, 13 May 2026 19:59:00 +0900 Subject: [PATCH 2/8] Add localisation docs --- localization/es-es/00-quick-start/README.md | 290 ++++++ .../es-es/01-setup-and-first-steps/README.md | 690 +++++++++++++ .../es-es/02-context-conversations/README.md | 908 ++++++++++++++++ .../es-es/03-development-workflows/README.md | 972 +++++++++++++++++ .../04-agents-custom-instructions/README.md | 783 ++++++++++++++ localization/es-es/05-skills/README.md | 886 ++++++++++++++++ localization/es-es/06-mcp-servers/README.md | 974 ++++++++++++++++++ .../es-es/06-mcp-servers/mcp-custom-server.md | 176 ++++ .../es-es/07-putting-it-together/README.md | 512 +++++++++ localization/es-es/README.md | 110 ++ localization/es-es/appendices/README.md | 12 + .../es-es/appendices/additional-context.md | 140 +++ .../es-es/appendices/ci-cd-integration.md | 199 ++++ localization/ja-jp/05-skills/README.md | 18 +- localization/ja-jp/06-mcp-servers/README.md | 16 +- .../ja-jp/07-putting-it-together/README.md | 8 +- localization/ko-kr/00-quick-start/README.md | 290 ++++++ .../ko-kr/01-setup-and-first-steps/README.md | 690 +++++++++++++ .../ko-kr/02-context-conversations/README.md | 909 ++++++++++++++++ .../ko-kr/03-development-workflows/README.md | 972 +++++++++++++++++ .../04-agents-custom-instructions/README.md | 783 ++++++++++++++ localization/ko-kr/05-skills/README.md | 886 ++++++++++++++++ localization/ko-kr/06-mcp-servers/README.md | 974 ++++++++++++++++++ .../ko-kr/06-mcp-servers/mcp-custom-server.md | 176 ++++ .../ko-kr/07-putting-it-together/README.md | 512 +++++++++ localization/ko-kr/README.md | 110 ++ localization/ko-kr/appendices/README.md | 12 + .../ko-kr/appendices/additional-context.md | 140 +++ .../ko-kr/appendices/ci-cd-integration.md | 199 ++++ localization/pt-br/00-quick-start/README.md | 290 ++++++ .../pt-br/01-setup-and-first-steps/README.md | 690 +++++++++++++ .../pt-br/02-context-conversations/README.md | 908 ++++++++++++++++ .../pt-br/03-development-workflows/README.md | 972 +++++++++++++++++ .../04-agents-custom-instructions/README.md | 783 ++++++++++++++ localization/pt-br/05-skills/README.md | 886 ++++++++++++++++ localization/pt-br/06-mcp-servers/README.md | 974 ++++++++++++++++++ .../pt-br/06-mcp-servers/mcp-custom-server.md | 176 ++++ .../pt-br/07-putting-it-together/README.md | 512 +++++++++ localization/pt-br/README.md | 110 ++ localization/pt-br/appendices/README.md | 12 + .../pt-br/appendices/additional-context.md | 140 +++ .../pt-br/appendices/ci-cd-integration.md | 199 ++++ localization/zh-cn/00-quick-start/README.md | 290 ++++++ .../zh-cn/01-setup-and-first-steps/README.md | 690 +++++++++++++ .../zh-cn/02-context-conversations/README.md | 908 ++++++++++++++++ .../zh-cn/03-development-workflows/README.md | 972 +++++++++++++++++ .../04-agents-custom-instructions/README.md | 783 ++++++++++++++ localization/zh-cn/05-skills/README.md | 886 ++++++++++++++++ localization/zh-cn/06-mcp-servers/README.md | 974 ++++++++++++++++++ .../zh-cn/06-mcp-servers/mcp-custom-server.md | 176 ++++ .../zh-cn/07-putting-it-together/README.md | 512 +++++++++ localization/zh-cn/README.md | 110 ++ localization/zh-cn/appendices/README.md | 12 + .../zh-cn/appendices/additional-context.md | 140 +++ .../zh-cn/appendices/ci-cd-integration.md | 199 ++++ 55 files changed, 26630 insertions(+), 21 deletions(-) create mode 100644 localization/es-es/00-quick-start/README.md create mode 100644 localization/es-es/01-setup-and-first-steps/README.md create mode 100644 localization/es-es/02-context-conversations/README.md create mode 100644 localization/es-es/03-development-workflows/README.md create mode 100644 localization/es-es/04-agents-custom-instructions/README.md create mode 100644 localization/es-es/05-skills/README.md create mode 100644 localization/es-es/06-mcp-servers/README.md create mode 100644 localization/es-es/06-mcp-servers/mcp-custom-server.md create mode 100644 localization/es-es/07-putting-it-together/README.md create mode 100644 localization/es-es/README.md create mode 100644 localization/es-es/appendices/README.md create mode 100644 localization/es-es/appendices/additional-context.md create mode 100644 localization/es-es/appendices/ci-cd-integration.md create mode 100644 localization/ko-kr/00-quick-start/README.md create mode 100644 localization/ko-kr/01-setup-and-first-steps/README.md create mode 100644 localization/ko-kr/02-context-conversations/README.md create mode 100644 localization/ko-kr/03-development-workflows/README.md create mode 100644 localization/ko-kr/04-agents-custom-instructions/README.md create mode 100644 localization/ko-kr/05-skills/README.md create mode 100644 localization/ko-kr/06-mcp-servers/README.md create mode 100644 localization/ko-kr/06-mcp-servers/mcp-custom-server.md create mode 100644 localization/ko-kr/07-putting-it-together/README.md create mode 100644 localization/ko-kr/README.md create mode 100644 localization/ko-kr/appendices/README.md create mode 100644 localization/ko-kr/appendices/additional-context.md create mode 100644 localization/ko-kr/appendices/ci-cd-integration.md create mode 100644 localization/pt-br/00-quick-start/README.md create mode 100644 localization/pt-br/01-setup-and-first-steps/README.md create mode 100644 localization/pt-br/02-context-conversations/README.md create mode 100644 localization/pt-br/03-development-workflows/README.md create mode 100644 localization/pt-br/04-agents-custom-instructions/README.md create mode 100644 localization/pt-br/05-skills/README.md create mode 100644 localization/pt-br/06-mcp-servers/README.md create mode 100644 localization/pt-br/06-mcp-servers/mcp-custom-server.md create mode 100644 localization/pt-br/07-putting-it-together/README.md create mode 100644 localization/pt-br/README.md create mode 100644 localization/pt-br/appendices/README.md create mode 100644 localization/pt-br/appendices/additional-context.md create mode 100644 localization/pt-br/appendices/ci-cd-integration.md create mode 100644 localization/zh-cn/00-quick-start/README.md create mode 100644 localization/zh-cn/01-setup-and-first-steps/README.md create mode 100644 localization/zh-cn/02-context-conversations/README.md create mode 100644 localization/zh-cn/03-development-workflows/README.md create mode 100644 localization/zh-cn/04-agents-custom-instructions/README.md create mode 100644 localization/zh-cn/05-skills/README.md create mode 100644 localization/zh-cn/06-mcp-servers/README.md create mode 100644 localization/zh-cn/06-mcp-servers/mcp-custom-server.md create mode 100644 localization/zh-cn/07-putting-it-together/README.md create mode 100644 localization/zh-cn/README.md create mode 100644 localization/zh-cn/appendices/README.md create mode 100644 localization/zh-cn/appendices/additional-context.md create mode 100644 localization/zh-cn/appendices/ci-cd-integration.md diff --git a/localization/es-es/00-quick-start/README.md b/localization/es-es/00-quick-start/README.md new file mode 100644 index 00000000..9f159a6f --- /dev/null +++ b/localization/es-es/00-quick-start/README.md @@ -0,0 +1,290 @@ +![Capítulo 00: Inicio rápido](../../../00-quick-start/images/chapter-header.png) + +¡Bienvenido! En este capítulo instalarás GitHub Copilot CLI (Command Line Interface), iniciarás sesión con tu cuenta de GitHub y verificarás que todo funciona. Es un capítulo corto de configuración. Una vez que esté funcionando, ¡las demos de verdad empiezan en el Capítulo 01! + +## 🎯 Objetivos de aprendizaje + +Al final de este capítulo, habrás: + +- Instalado GitHub Copilot CLI +- Iniciado sesión con tu cuenta de GitHub +- Verificado que funciona con una prueba sencilla + +> ⏱️ **Tiempo estimado**: ~10 minutos (5 min de lectura + 5 min de práctica) + +--- + +## ✅ Requisitos previos + +- **Cuenta de GitHub** con acceso a Copilot. [Consulta las opciones de suscripción](https://github.com/features/copilot/plans). Estudiantes y profesores pueden acceder a Copilot Pro de [forma gratuita a través de GitHub Education](https://education.github.com/pack). +- **Conocimientos básicos de terminal**: te resulta cómodo usar comandos como `cd` y `ls` + +### Qué significa "acceso a Copilot" + +GitHub Copilot CLI requiere una suscripción activa a Copilot. Puedes consultar tu estado en [github.com/settings/copilot](https://github.com/settings/copilot). Deberías ver una de estas opciones: + +- **Copilot Individual**: suscripción personal +- **Copilot Business**: a través de tu organización +- **Copilot Enterprise**: a través de tu empresa +- **GitHub Education**: gratis para estudiantes y profesores verificados + +Si ves "You don't have access to GitHub Copilot", tendrás que usar la opción gratuita, suscribirte a un plan o unirte a una organización que te dé acceso. + +--- + +## Instalación + +> ⏱️ **Estimación de tiempo**: la instalación tarda entre 2 y 5 minutos. La autenticación añade otros 1 o 2 minutos. + +### GitHub Codespaces (cero configuración) + +Si no quieres instalar ninguno de los requisitos previos, puedes usar GitHub Codespaces, que ya trae GitHub Copilot CLI listo para usar (solo tendrás que iniciar sesión) y trae Python y pytest preinstalados. + +1. [Haz un fork de este repositorio](https://github.com/github/copilot-cli-for-beginners/fork) en tu cuenta de GitHub +2. Selecciona **Code** > **Codespaces** > **Create codespace on main** +3. Espera unos minutos a que se construya el contenedor +4. ¡Ya está! La terminal se abrirá automáticamente en el entorno del Codespace. + +> 💡 **Verifica en el Codespace**: ejecuta `cd samples/book-app-project && python book_app.py help` para confirmar que Python y la app de ejemplo funcionan. + +### Instalación local + +Sigue estos pasos si quieres ejecutar Copilot CLI en tu máquina local con los ejemplos del curso. + +1. Clona el repo para tener los ejemplos del curso en tu máquina: + + ```bash + git clone https://github.com/github/copilot-cli-for-beginners + cd copilot-cli-for-beginners + ``` + +2. Instala Copilot CLI usando una de las siguientes opciones. + + > 💡 **¿No sabes cuál elegir?** Usa `npm` si tienes Node.js instalado. En caso contrario, elige la opción que se ajuste a tu sistema. + + ### Todas las plataformas (npm) + + ```bash + # Si tienes Node.js instalado, esta es una forma rápida de obtener el CLI + npm install -g @github/copilot + ``` + + ### macOS/Linux (Homebrew) + + ```bash + brew install copilot-cli + ``` + + ### Windows (WinGet) + + ```bash + winget install GitHub.Copilot + ``` + + ### macOS/Linux (script de instalación) + + ```bash + curl -fsSL https://gh.io/copilot-install | bash + ``` + +
+Opcional: habilitar la autocompletado del shell con Tab + +La autocompletado con Tab del shell te permite pulsar **Tab** para completar subcomandos de `copilot`, opciones de comando y algunos valores de opciones. Es opcional, pero puede resultar muy útil cuando ya te sientas cómodo usando el CLI. + +Copilot CLI actualmente soporta scripts de autocompletado para Bash, Zsh y Fish: + +```shell +# Bash, solo en la sesión actual +source <(copilot completion bash) + +# Bash, persistente en Linux +copilot completion bash | sudo tee /etc/bash_completion.d/copilot + +# Zsh +copilot completion zsh > "${fpath[1]}/_copilot" + +# Fish +copilot completion fish > ~/.config/fish/completions/copilot.fish +``` + +Reinicia tu shell después de añadir la autocompletado persistente. PowerShell está soportado para ejecutar Copilot CLI en Windows, pero `copilot completion` actualmente solo soporta Bash, Zsh y Fish. + +
+ +--- + +## Autenticación + +Abre una ventana de terminal en la raíz del repositorio `copilot-cli-for-beginners`, inicia el CLI y permite el acceso a la carpeta. + +```bash +copilot +``` + +Se te pedirá que confíes en la carpeta que contiene el repositorio (si aún no lo has hecho). Puedes confiar en ella por una vez o para todas las sesiones futuras. + +Confiando en archivos de una carpeta con el Copilot CLI + +Después de confiar en la carpeta, puedes iniciar sesión con tu cuenta de GitHub. + +``` +> /login +``` + +**Lo que ocurre a continuación:** + +1. Copilot CLI muestra un código de un solo uso (como `ABCD-1234`) +2. Tu navegador se abre en la página de autorización de dispositivos de GitHub. Inicia sesión en GitHub si aún no lo has hecho. +3. Introduce el código cuando se te pida +4. Selecciona "Authorize" para conceder acceso a GitHub Copilot CLI +5. Vuelve a tu terminal: ¡ya tienes la sesión iniciada! + +Flujo de autorización de dispositivo: muestra el proceso de 5 pasos desde el inicio de sesión en la terminal hasta la confirmación de sesión iniciada + +*El flujo de autorización de dispositivo: tu terminal genera un código, lo verificas en el navegador y Copilot CLI queda autenticado.* + +**Tip**: el inicio de sesión persiste entre sesiones. Solo necesitas hacerlo una vez, salvo que tu token caduque o cierres sesión explícitamente. + +--- + +## Verifica que funciona + +### Paso 1: prueba Copilot CLI + +Ahora que tienes la sesión iniciada, vamos a verificar que Copilot CLI te funciona. En la terminal, inicia el CLI si aún no lo has hecho: + +```bash +> Say hello and tell me what you can help with +``` + +Después de recibir una respuesta, puedes salir del CLI: + +```bash +> /exit +``` + +--- + +
+🎬 ¡Míralo en acción! + +![Demo de hola](../../../00-quick-start/images/hello-demo.gif) + +*La salida de la demo varía. Tu modelo, herramientas y respuestas serán distintos a los que se muestran aquí.* + +
+ +--- + +**Salida esperada**: una respuesta amistosa que enumera las capacidades de Copilot CLI. + +### Paso 2: ejecuta la app de ejemplo de libros + +El curso incluye una app de ejemplo que explorarás y mejorarás a lo largo del curso usando el CLI *(puedes ver el código en /samples/book-app-project)*. Comprueba que la *app de terminal de colección de libros en Python* funciona antes de empezar. Ejecuta `python` o `python3` según tu sistema. + +> **Nota:** los ejemplos principales del curso usan Python (`samples/book-app-project`), así que necesitarás tener [Python 3.10+](https://www.python.org/downloads/) disponible en tu máquina local si elegiste esa opción (el Codespace ya lo trae instalado). También están disponibles las versiones en JavaScript (`samples/book-app-project-js`) y C# (`samples/book-app-project-cs`) por si prefieres trabajar con esos lenguajes. Cada ejemplo tiene un README con instrucciones para ejecutar la app en ese lenguaje. + +```bash +cd samples/book-app-project +python book_app.py list +``` + +**Salida esperada**: una lista de 5 libros que incluye "The Hobbit", "1984" y "Dune". + +### Paso 3: prueba Copilot CLI con la app de libros + +Vuelve primero a la raíz del repositorio (si has ejecutado el Paso 2): + +```bash +cd ../.. # Vuelve a la raíz del repositorio si es necesario +copilot +> What does @samples/book-app-project/book_app.py do? +``` + +**Salida esperada**: un resumen de las funciones y comandos principales de la app de libros. + +Si ves un error, consulta la [sección de solución de problemas](#troubleshooting) más abajo. + +Cuando termines puedes salir de Copilot CLI: + +```bash +> /exit +``` + +--- + +## ✅ ¡Estás listo! + +Eso es todo en cuanto a la instalación. La diversión de verdad empieza en el Capítulo 01, donde: + +- Verás cómo la IA revisa la app de libros y encuentra problemas de calidad de código al instante +- Aprenderás tres formas distintas de usar Copilot CLI +- Generarás código funcional a partir de inglés sencillo + +**[Continuar al Capítulo 01: Primeros pasos →](../01-setup-and-first-steps/README.md)** + +--- + +## Solución de problemas + +### "copilot: command not found" + +El CLI no está instalado. Prueba con otro método de instalación: + +```bash +# Si brew falló, prueba npm: +npm install -g @github/copilot + +# O el script de instalación: +curl -fsSL https://gh.io/copilot-install | bash +``` + +### "You don't have access to GitHub Copilot" + +1. Verifica que tienes una suscripción a Copilot en [github.com/settings/copilot](https://github.com/settings/copilot) +2. Comprueba que tu organización permite el acceso al CLI si usas una cuenta de trabajo + +### "Authentication failed" + +Vuelve a autenticarte: + +```bash +copilot +> /login +``` + +### El navegador no se abre automáticamente + +Visita manualmente [github.com/login/device](https://github.com/login/device) e introduce el código que aparece en tu terminal. + +### Token caducado + +Simplemente vuelve a ejecutar `/login`: + +```bash +copilot +> /login +``` + +### ¿Sigues atascado? + +- Consulta la [documentación de GitHub Copilot CLI](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) +- Busca en [GitHub Issues](https://github.com/github/copilot-cli/issues) + +--- + +## 🔑 Conclusiones clave + +1. **Un GitHub Codespace es una forma rápida de empezar**: Python, pytest y GitHub Copilot CLI vienen preinstalados, así que puedes saltar directamente a las demos +2. **Varios métodos de instalación**: elige el que funcione en tu sistema (Homebrew, WinGet, npm o script de instalación) +3. **Autenticación de una sola vez**: el inicio de sesión persiste hasta que el token caduca +4. **La app de libros funciona**: usarás `samples/book-app-project` durante todo el curso + +> 📚 **Documentación oficial**: [Instalar Copilot CLI](https://docs.github.com/copilot/how-tos/copilot-cli/cli-getting-started) para opciones de instalación y requisitos. + +> 📋 **Referencia rápida**: consulta la [referencia de comandos de GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para ver la lista completa de comandos y atajos. + +--- + +**[Continuar al Capítulo 01: Primeros pasos →](../01-setup-and-first-steps/README.md)** diff --git a/localization/es-es/01-setup-and-first-steps/README.md b/localization/es-es/01-setup-and-first-steps/README.md new file mode 100644 index 00000000..e188fc59 --- /dev/null +++ b/localization/es-es/01-setup-and-first-steps/README.md @@ -0,0 +1,690 @@ +![Capítulo 01: Primeros pasos](../../../01-setup-and-first-steps/images/chapter-header.png) + +> **Mira cómo la IA encuentra bugs al instante, explica código confuso y genera scripts funcionales. Después aprende tres formas distintas de usar GitHub Copilot CLI.** + +¡En este capítulo empieza la magia! Vivirás de primera mano por qué los desarrolladores describen GitHub Copilot CLI como tener a un ingeniero senior en marcación rápida. Verás cómo la IA encuentra bugs de seguridad en segundos, te explica código complejo en lenguaje sencillo y genera scripts funcionales al instante. Después dominarás los tres modos de interacción (Interactivo, Plan y Programático) para que sepas exactamente cuál usar en cada tarea. + +> ⚠️ **Requisitos previos**: Asegúrate de haber completado primero **[Capítulo 00: Inicio rápido](../00-quick-start/README.md)**. Necesitarás GitHub Copilot CLI instalado y autenticado antes de ejecutar las demos siguientes. + +## 🎯 Objetivos de aprendizaje + +Al final de este capítulo, podrás: + +- Experimentar el aumento de productividad que ofrece GitHub Copilot CLI mediante demos prácticas +- Elegir el modo correcto (Interactivo, Plan o Programático) para cualquier tarea +- Usar comandos slash para controlar tus sesiones + +> ⏱️ **Tiempo estimado**: ~45 minutos (15 min de lectura + 30 min de práctica) + +--- + +# Tu primera experiencia con Copilot CLI + +Desarrollador sentado en un escritorio con código en el monitor y partículas brillantes que representan la asistencia de la IA + +Lánzate de lleno y descubre lo que Copilot CLI puede hacer. + +--- + +## Tomando confianza: tus primeros prompts + +Antes de meterte en las demos impresionantes, empecemos con algunos prompts sencillos que puedes probar ahora mismo. **¡No necesitas ningún repositorio de código!** Solo abre una terminal e inicia Copilot CLI: + +```bash +copilot +``` + +Prueba estos prompts aptos para principiantes: + +``` +> 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 +``` + +¿No usas Python? ¡No hay problema! Solo haz preguntas sobre el lenguaje que prefieras. + +Fíjate en lo natural que se siente. Solo haz preguntas como se las harías a un colega. Cuando termines de explorar, escribe `/exit` para salir de la sesión. + +**La idea clave**: GitHub Copilot CLI es conversacional. No necesitas ninguna sintaxis especial para empezar. Solo haz preguntas en lenguaje natural. + +## Míralo en acción + +Ahora veamos por qué los desarrolladores lo llaman "tener a un ingeniero senior en marcación rápida". + +> 📖 **Cómo leer los ejemplos**: Las líneas que empiezan con `>` son prompts que escribes dentro de una sesión interactiva de Copilot CLI. Las líneas sin el prefijo `>` son comandos de shell que ejecutas en tu terminal. + +> 💡 **Sobre los ejemplos de salida**: Los ejemplos de salida que se muestran en este curso son ilustrativos. Como las respuestas de Copilot CLI varían cada vez, tus resultados serán distintos en redacción, formato y nivel de detalle. Concéntrate en el *tipo* de información devuelta, no en el texto exacto. + +### Demo 1: revisión de código en segundos + +El curso incluye archivos de ejemplo con problemas intencionales de calidad de código. Si trabajas en tu máquina local y aún no has clonado el repositorio, ejecuta el comando `git clone` que aparece abajo, navega a la carpeta `copilot-cli-for-beginners` y luego ejecuta el comando `copilot`. + +```bash +# Clona el repositorio del curso si trabajas localmente y aún no lo has hecho +git clone https://github.com/github/copilot-cli-for-beginners +cd copilot-cli-for-beginners + +# Inicia Copilot +copilot +``` + +Una vez dentro de la sesión interactiva de Copilot CLI, ejecuta lo siguiente: + +``` +> Review @samples/book-app-project/book_app.py for code quality issues and suggest improvements +``` + +> 💡 **¿Para qué sirve el símbolo `@`?** El símbolo `@` le indica a Copilot CLI que lea un archivo. Aprenderás todo sobre esto en el Capítulo 02. Por ahora, solo copia el comando exactamente como se muestra. + +--- + +
+🎬 ¡Míralo en acción! + +![Demo de revisión de código](../../../01-setup-and-first-steps/images/code-review-demo.gif) + +*La salida de la demo varía. Tu modelo, herramientas y respuestas serán distintos a los que se muestran aquí.* + +
+ +--- + +**La conclusión**: una revisión de código profesional en segundos. Una revisión manual tardaría... bueno... bastante más que eso. + +--- + +### Demo 2: explicar código confuso + +¿Alguna vez te has quedado mirando código preguntándote qué hace? Prueba esto en tu sesión de Copilot CLI: + +``` +> Explain what @samples/book-app-project/books.py does in simple terms +``` + +--- + +
+🎬 ¡Míralo en acción! + +![Demo de explicación de código](../../../01-setup-and-first-steps/images/explain-code-demo.gif) + +*La salida de la demo varía. Tu modelo, herramientas y respuestas serán distintos a los que se muestran aquí.* + +
+ +--- + +**Lo que ocurre**: (tu salida será distinta) Copilot CLI lee el archivo, entiende el código y lo explica en lenguaje natural. + +``` +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 +``` + +**La conclusión**: código complejo explicado como lo haría un mentor paciente. + +--- + +### Demo 3: generar código funcional + +¿Necesitas una función para la que normalmente pasarías 15 minutos buscando en Google? Sigue en tu sesión: + +``` +> Write a Python function that takes a list of books and returns statistics: + total count, number read, number unread, oldest and newest book +``` + +--- + +
+🎬 ¡Míralo en acción! + +![Demo de generación de código](../../../01-setup-and-first-steps/images/generate-code-demo.gif) + +*La salida de la demo varía. Tu modelo, herramientas y respuestas serán distintos a los que se muestran aquí.* + +
+ +--- + +**Lo que ocurre**: una función completa y funcional en segundos que puedes copiar, pegar y ejecutar. + +Cuando termines de explorar, sal de la sesión: + +``` +> /exit +``` + +**La conclusión**: gratificación instantánea, y has permanecido en una sola sesión continua todo el tiempo. + +--- + +# Modos y comandos + +Panel de control futurista con pantallas brillantes, mandos y ecualizadores que representan los modos y comandos de Copilot CLI + +Acabas de ver lo que Copilot CLI puede hacer. Ahora entendamos *cómo* usar estas capacidades de forma efectiva. La clave está en saber cuál de los tres modos de interacción usar en cada situación. + +> 💡 **Nota**: Copilot CLI también tiene un modo **Autopilot** en el que trabaja en las tareas sin esperar tu intervención. Es potente, pero requiere conceder permisos completos y consume premium requests de forma autónoma. Este curso se centra en los tres modos siguientes. Te indicaremos cuándo pasar a Autopilot una vez que te sientas cómodo con lo básico. + +--- + +## 🧩 Analogía con el mundo real: salir a comer + +Piensa en usar GitHub Copilot CLI como salir a comer. Desde planificar la salida hasta hacer tu pedido, distintas situaciones piden distintos enfoques: + +| Modo | Analogía gastronómica | Cuándo usarlo | +|------|----------------|-------------| +| **Plan** | Ruta de GPS hasta el restaurante | Tareas complejas: traza la ruta, revisa las paradas, acuerda el plan y luego conduce | +| **Interactivo** | Hablar con el camarero | Exploración e iteración: haz preguntas, personaliza, recibe feedback en tiempo real | +| **Programático** | Pedir en el autoservicio | Tareas rápidas y específicas: quédate en tu entorno, obtén un resultado rápido | + +Igual que cuando sales a comer, irás aprendiendo de forma natural cuándo cada enfoque encaja mejor. + +Tres formas de usar GitHub Copilot CLI - Modo Plan (ruta GPS al restaurante), Modo Interactivo (hablar con el camarero), Modo Programático (autoservicio) + +*Elige tu modo según la tarea: Plan para trazar el camino primero, Interactivo para colaboración de ida y vuelta, Programático para resultados rápidos de un solo disparo* + +### ¿Con qué modo debería empezar? + +**Empieza con el modo Interactivo.** +- Puedes experimentar y hacer preguntas de seguimiento +- El contexto se va construyendo de forma natural a través de la conversación +- Los errores son fáciles de corregir con `/clear` + +Cuando te sientas cómodo, prueba: +- **Modo Programático** (`copilot -p ""`) para preguntas rápidas y puntuales +- **Modo Plan** (`/plan`) cuando necesites planificar las cosas con más detalle antes de programar + +--- + +## Los tres modos + +### Modo 1: Modo Interactivo (empieza aquí) + +Modo Interactivo - Como hablar con un camarero que puede responder preguntas y ajustar el pedido + +**Mejor para**: exploración, iteración, conversaciones de varios turnos. Como hablar con un camarero que puede responder preguntas, recibir feedback y ajustar el pedido sobre la marcha. + +Inicia una sesión interactiva: + +```bash +copilot +``` + +Como has visto hasta ahora, verás un prompt donde puedes escribir de forma natural. Para obtener ayuda sobre los comandos disponibles, simplemente escribe: + +``` +> /help +``` + +**Idea clave**: el modo Interactivo mantiene el contexto. Cada mensaje se construye sobre los anteriores, igual que en una conversación real. + +#### Ejemplo del modo Interactivo + +```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 +``` + +Fíjate cómo cada prompt se apoya en la respuesta anterior. Estás manteniendo una conversación, no empezando de cero cada vez. + +--- + +### Modo 2: Modo Plan + +Modo Plan - Como planificar una ruta antes de un viaje usando GPS + +**Mejor para**: tareas complejas en las que quieres revisar el enfoque antes de la ejecución. Similar a planificar una ruta antes de un viaje usando el GPS. + +El modo Plan te ayuda a crear un plan paso a paso antes de escribir cualquier código. Usa el comando `/plan` o pulsa **Shift+Tab** para alternar al modo Plan: + +```bash +copilot + +> /plan Add a "mark as read" command to the book app +``` + +> 💡 **Tip**: **Shift+Tab** alterna entre modos: Interactivo → Plan → Autopilot. Púlsalo en cualquier momento durante una sesión interactiva para cambiar de modo sin escribir un comando. + +También puedes lanzar Copilot CLI directamente en modo Plan usando el flag `--plan`: + +```bash +copilot --plan +``` + +**Salida del modo Plan:** (tu salida puede variar) + +``` +📋 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] +``` + +**Idea clave**: el modo Plan te permite revisar y modificar el enfoque antes de que se escriba cualquier código. Una vez que un plan esté completo, incluso puedes pedirle a Copilot CLI que lo guarde en un archivo para futuras consultas. Por ejemplo, "Save this plan to `mark_as_read_plan.md`" crearía un archivo Markdown con los detalles del plan. + +> 💡 **¿Quieres algo más complejo?** Prueba: `/plan Add search and filter capabilities to the book app`. El modo Plan escala desde funcionalidades simples hasta aplicaciones completas. + +> 📚 **Modo Autopilot**: Quizá hayas notado que Shift+Tab pasa por un tercer modo llamado **Autopilot**. En el modo Autopilot, Copilot trabaja en un plan completo sin esperar tu intervención después de cada paso, como entregarle una tarea a un colega y decirle "avísame cuando termines". El flujo de trabajo típico es planificar → aceptar → autopilot, lo que significa que primero debes ser bueno escribiendo planes. También puedes lanzar directamente en autopilot con `copilot --autopilot`. Familiarízate primero con los modos Interactivo y Plan, y después consulta la [documentación oficial](https://docs.github.com/copilot/concepts/agents/copilot-cli/autopilot) cuando estés listo. + +--- + +### Modo 3: Modo Programático + +Modo Programático - Como usar el autoservicio para un pedido rápido + +**Mejor para**: automatización, scripts, CI/CD, comandos de un solo disparo. Como usar el autoservicio para un pedido rápido sin necesidad de hablar con el camarero. + +Usa el flag `-p` para comandos puntuales que no necesitan interacción: + +```bash +# Generar código +copilot -p "Write a function that checks if a number is even or odd" + +# Obtener ayuda rápida +copilot -p "How do I read a JSON file in Python?" +``` + +**Idea clave**: el modo Programático te da una respuesta rápida y sale. Sin conversación, solo entrada → salida. + +
+📚 Yendo más allá: usar el modo Programático en scripts (haz clic para expandir) + +Una vez que te sientas cómodo, puedes usar `-p` en scripts de shell: + +```bash +#!/bin/bash + +# Generar mensajes de commit automáticamente +COMMIT_MSG=$(copilot -p "Generate a commit message for: $(git diff --staged)") +git commit -m "$COMMIT_MSG" + +# Revisar un archivo +copilot --allow-all -p "Review @myfile.py for issues" +``` +> ⚠️ **Sobre `--allow-all`**: este flag salta todos los avisos de permisos, permitiendo que Copilot CLI lea archivos, ejecute comandos y acceda a URLs sin preguntar primero. Esto es necesario para el modo programático (`-p`) porque no hay una sesión interactiva que apruebe las acciones. Usa `--allow-all` solo con prompts que hayas escrito tú mismo y en directorios en los que confíes. Nunca lo uses con entrada no confiable o en directorios sensibles. + +
+ +--- + +## Comandos slash esenciales + +Estos comandos son perfectos para aprender al principio mientras te familiarizas con Copilot CLI: + +| Comando | Qué hace | Cuándo usarlo | +|---------|--------------|-------------| +| `/ask` | Hace una pregunta rápida sin que afecte al historial de tu conversación | Cuando quieres una respuesta rápida sin desviar la tarea actual | +| `/clear` | Limpia la conversación y empieza de cero | Cuando cambias de tema | +| `/help` | Muestra todos los comandos disponibles | Cuando olvidas un comando | +| `/model` | Muestra o cambia el modelo de IA | Cuando quieres cambiar el modelo de IA | +| `/plan` | Planifica tu trabajo antes de programar | Para funcionalidades más complejas | +| `/research` | Investigación profunda usando GitHub y fuentes web | Cuando necesitas investigar un tema antes de programar | +| `/exit` | Termina la sesión | Cuando hayas terminado | + +> 💡 **`/ask` vs el chat normal**: normalmente cada mensaje que envías pasa a formar parte de la conversación en curso y afecta a las respuestas futuras. `/ask` es un atajo "off the record": perfecto para preguntas rápidas y puntuales como `/ask What does YAML mean?` sin contaminar el contexto de tu sesión. + +> 💡 **Autocompletado con Tab**: cuando estés escribiendo un comando slash, pulsa **Tab** para autocompletar el nombre del comando o pasar por los subcomandos y argumentos disponibles. Resulta especialmente útil cuando no recuerdas el nombre exacto de un comando. + +¡Eso es todo para empezar! Conforme te sientas cómodo, podrás explorar comandos adicionales. + +> 📚 **Documentación oficial**: [Referencia de comandos del CLI](https://docs.github.com/copilot/reference/cli-command-reference) para la lista completa de comandos y flags. + +
+📚 Comandos adicionales (haz clic para expandir) + +> 💡 Los comandos esenciales de arriba cubren gran parte de lo que harás en el día a día. Esta referencia está aquí para cuando estés listo para explorar más. + +### Entorno del agente + +| Comando | Qué hace | +|---------|--------------| +| `/agent` | Explora y selecciona entre los agentes disponibles | +| `/env` | Muestra los detalles del entorno cargado: qué instrucciones, servidores MCP, skills, agentes y plugins están activos | +| `/init` | Inicializa instrucciones de Copilot para tu repositorio | +| `/mcp` | Gestiona la configuración del servidor MCP | +| `/skills` | Gestiona skills para capacidades ampliadas | + +> 💡 Los agentes se cubren en el [Capítulo 04](../04-agents-custom-instructions/README.md), los skills en el [Capítulo 05](../05-skills/README.md) y los servidores MCP en el [Capítulo 06](../06-mcp-servers/README.md). + +### Modelos y subagentes + +| Comando | Qué hace | +|---------|--------------| +| `/delegate` | Delega la tarea al agente en la nube de GitHub Copilot | +| `/fleet` | Divide una tarea compleja en subtareas paralelas para completarla más rápido | +| `/model` | Muestra o cambia el modelo de IA | +| `/tasks` | Muestra los subagentes en segundo plano y las sesiones de shell desacopladas | + +### Código + +| Comando | Qué hace | +|---------|--------------| +| `/diff` | Revisa los cambios realizados en el directorio actual | +| `/pr` | Opera sobre los pull requests de la rama actual | +| `/research` | Ejecuta una investigación profunda usando GitHub y fuentes web | +| `/review` | Ejecuta el agente de code-review para analizar los cambios | +| `/terminal-setup` | Habilita la entrada multilínea (shift+enter y ctrl+enter) | + +### Permisos + +| Comando | Qué hace | +|---------|--------------| +| `/add-dir ` | Añade un directorio a la lista de permitidos | +| `/allow-all [on\|off\|show]` | Autoaprueba todos los avisos de permisos; usa `on` para activarlo, `off` para desactivarlo, `show` para ver el estado actual | +| `/yolo` | Alias rápido para `/allow-all on`: autoaprueba todos los avisos de permisos. | +| `/cwd`, `/cd [directory]` | Muestra o cambia el directorio de trabajo | +| `/list-dirs` | Muestra todos los directorios permitidos | + +> ⚠️ **Usar con precaución**: `/allow-all` y `/yolo` saltan los avisos de confirmación. Excelentes para proyectos de confianza, pero ten cuidado con código no confiable. + +### Sesión + +| Comando | Qué hace | +|---------|--------------| +| `/clear` | Abandona la sesión actual (sin guardar historial) y empieza una conversación nueva | +| `/compact` | Resume la conversación para reducir el uso de contexto | +| `/context` | Muestra el uso de tokens de la ventana de contexto y su visualización | +| `/keep-alive` | Evita que tu sistema entre en suspensión mientras Copilot CLI esté activo: práctico para tareas largas en un portátil | +| `/new` | Termina la sesión actual (guardándola en el historial para búsqueda/resume) y empieza una conversación nueva. | +| `/resume` | Cambia a una sesión distinta (opcionalmente puedes especificar el ID o nombre de la sesión) | +| `/rename` | Renombra la sesión actual (omite el nombre para autogenerar uno) | +| `/rewind` | Abre un selector de línea de tiempo para volver a un punto anterior de la conversación | +| `/usage` | Muestra métricas y estadísticas de uso de la sesión | +| `/session` | Muestra información de la sesión y un resumen del workspace; usa `/session delete`, `/session delete ` o `/session delete-all` para eliminar sesiones | +| `/share` | Exporta la sesión como un archivo Markdown, un gist de GitHub o un archivo HTML autocontenido | + +### Visualización + +| Comando | Qué hace | +|---------|--------------| +| `/statusline` (o `/footer`) | Personaliza qué elementos aparecen en la barra de estado al final de la sesión (directorio, rama, esfuerzo, ventana de contexto, cuota) | +| `/theme` | Visualiza o establece el tema del terminal | + +### Ayuda y feedback + +| Comando | Qué hace | +|---------|--------------| +| `/changelog` | Muestra el changelog de las versiones del CLI | +| `/feedback` | Envía feedback a GitHub | +| `/help` | Muestra todos los comandos disponibles | + +### Comandos de shell rápidos + +Ejecuta comandos de shell directamente sin pasar por la IA prefijándolos con `!`: + +```bash +copilot + +> !git status +# Ejecuta git status directamente, saltándose la IA + +> !python -m pytest tests/ +# Ejecuta pytest directamente +``` + +### Cambiar de modelo + +Copilot CLI soporta varios modelos de IA de OpenAI, Anthropic, Google y otros. Los modelos disponibles para ti dependen de tu nivel de suscripción y de la región. Usa `/model` para ver tus opciones y cambiar entre ellas: + +```bash +copilot +> /model + +# Muestra los modelos disponibles y te deja elegir uno. Selecciona Sonnet 4.5. +``` + +> 💡 **Tip**: algunos modelos cuestan más "premium requests" que otros. Los modelos marcados como **1x** (como Claude Sonnet 4.5) son una opción por defecto excelente. Son capaces y eficientes. Los modelos con multiplicador más alto consumen tu cuota de premium requests más rápido, así que resérvalos para cuando realmente los necesites. + +> 💡 **¿No sabes qué modelo elegir?** Selecciona **`Auto`** en el selector de modelos para que Copilot elija automáticamente el mejor modelo disponible para cada sesión. Es una opción por defecto excelente si estás empezando y no quieres pensar en la selección de modelos. + +
+ +--- + +# Práctica + +Escritorio acogedor con un monitor mostrando código, una lámpara, una taza de café y unos auriculares listos para la práctica + +Es hora de poner en práctica lo que has aprendido. + +--- + +## ▶️ Pruébalo tú mismo + +### Exploración interactiva + +Inicia Copilot y usa prompts de seguimiento para mejorar la app de libros de forma iterativa: + +```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 +``` + +### Planifica una funcionalidad + +Usa `/plan` para que Copilot CLI trace una implementación antes de escribir código: + +```bash +copilot + +> /plan Add a search feature to the book app that can find books by title or author + +# Revisa el plan +# Apruébalo o modifícalo +# Mira cómo lo implementa paso a paso +``` + +### Automatiza con el modo Programático + +El flag `-p` te permite ejecutar Copilot CLI directamente desde tu terminal sin entrar en modo interactivo. Copia y pega el siguiente script en tu terminal (no dentro de Copilot) desde la raíz del repositorio para revisar todos los archivos Python de la app de libros. + +```bash +# Revisa todos los archivos Python en la app de libros +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 +# Revisa todos los archivos Python en la app de libros +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" +} +``` + +--- + +Después de completar las demos, prueba estas variaciones: + +1. **Reto interactivo**: inicia `copilot` y explora la app de libros. Pregunta sobre `@samples/book-app-project/books.py` y solicita mejoras 3 veces seguidas. + +2. **Reto en modo Plan**: ejecuta `/plan Add rating and review features to the book app`. Lee el plan con atención. ¿Tiene sentido? + +3. **Reto programático**: ejecuta `copilot --allow-all -p "List all functions in @samples/book-app-project/book_app.py and describe what each does"`. ¿Funcionó al primer intento? + +--- + +## 💡 Tip: controla tu sesión del CLI desde la web o el móvil + +GitHub Copilot CLI soporta **sesiones remotas**, que te permiten monitorizar e interactuar con una sesión del CLI en ejecución desde un navegador web (en escritorio o móvil) o desde la app GitHub Mobile sin estar físicamente delante de tu terminal. + +Inicia una sesión remota con el flag `--remote`: + +```bash +copilot --remote +``` + +Copilot CLI mostrará un enlace y dará acceso a un código QR. Abre el enlace en tu teléfono o en una pestaña del navegador del escritorio para ver la sesión en tiempo real, enviar prompts de seguimiento, revisar planes y guiar al agente de forma remota. Las sesiones son específicas de cada usuario, así que solo puedes acceder a tus propias sesiones de Copilot CLI. + +También puedes habilitar el acceso remoto desde dentro de una sesión activa en cualquier momento: + +``` +> /remote +``` + +Encontrarás más detalles sobre las sesiones remotas en la [documentación de Copilot CLI](https://docs.github.com/copilot/how-tos/copilot-cli/steer-remotely). + +--- + +## 📝 Tarea + +### Reto principal: mejora las utilidades de la app de libros + +Los ejemplos prácticos se centraron en revisar y refactorizar `book_app.py`. Ahora practica las mismas habilidades sobre un archivo distinto, `utils.py`: + +1. Inicia una sesión interactiva: `copilot` +2. Pide a Copilot CLI que resuma el archivo: "Summarize @samples/book-app-project/utils.py and explain what each function in this file does" +3. Pídele que añada validación de entrada: "Add validation to `get_user_choice()` so it handles empty input and non-numeric entries" +4. Pídele que mejore el manejo de errores: "What happens if `get_book_details()` receives an empty string for the title? Add guards for that." +5. Pide un docstring: "Add a comprehensive docstring to `get_book_details()` with parameter descriptions and return values" +6. Observa cómo el contexto se mantiene entre prompts. Cada mejora se construye sobre la anterior +7. Sal con `/exit` + +**Criterios de éxito**: deberías acabar con un `utils.py` mejorado con validación de entrada, manejo de errores y un docstring, todo construido a través de una conversación de varios turnos. + +
+💡 Pistas (haz clic para expandir) + +**Prompts de ejemplo para probar:** +```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 +``` + +**Problemas comunes:** +- Si Copilot CLI hace preguntas aclaratorias, simplemente respóndelas con naturalidad +- El contexto se mantiene, así que cada prompt se construye sobre el anterior +- Usa `/clear` si quieres empezar de nuevo + +
+ +### Reto extra: compara los modos + +Los ejemplos usaron `/plan` para una funcionalidad de búsqueda y `-p` para revisiones en lote. Ahora prueba los tres modos sobre una nueva tarea: añadir un método `list_by_year()` a la clase `BookCollection`: + +1. **Interactivo**: `copilot` → pídele que diseñe y construya el método paso a paso +2. **Plan**: `/plan Add a list_by_year(start, end) method to BookCollection that filters books by publication year range` +3. **Programático**: `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"` + +**Reflexión**: ¿qué modo te resultó más natural? ¿Cuándo usarías cada uno? + +--- + +
+🔧 Errores comunes y solución de problemas (haz clic para expandir) + +### Errores comunes + +| Error | Qué pasa | Cómo arreglarlo | +|---------|--------------|-----| +| Escribir `exit` en vez de `/exit` | Copilot CLI trata "exit" como un prompt, no como un comando | Los comandos slash siempre empiezan por `/` | +| Usar `-p` para conversaciones de varios turnos | Cada llamada a `-p` está aislada y no recuerda llamadas anteriores | Usa el modo interactivo (`copilot`) para conversaciones que se construyan sobre el contexto | +| Olvidar las comillas en prompts con `$` o `!` | El shell interpreta los caracteres especiales antes de que Copilot CLI los vea | Envuelve los prompts entre comillas: `copilot -p "What does $HOME mean?"` | +| Pulsar Esc una vez para cancelar una tarea en ejecución | Una sola pulsación de Esc ya no cancela el trabajo en curso (para evitar accidentes) | Pulsa **Esc dos veces** para cancelar mientras Copilot CLI está procesando | + +### Solución de problemas + +**"Model not available"**: tu suscripción puede no incluir todos los modelos. Usa `/model` para ver lo que está disponible. + +**"Context too long"**: tu conversación ha consumido toda la ventana de contexto. Usa `/clear` para reiniciar, o inicia una nueva sesión. + +**"Rate limit exceeded"**: espera unos minutos e inténtalo de nuevo. Considera usar el modo programático para operaciones en lote con retardos. + +
+ +--- + +# Resumen + +## 🔑 Conclusiones clave + +1. **El modo Interactivo** es para exploración e iteración: el contexto se mantiene. Es como tener una conversación con alguien que recuerda lo que has dicho hasta ese momento. +2. **El modo Plan** se usa normalmente para tareas más complejas. Revisa antes de implementar. +3. **El modo Programático** es para automatización. No requiere interacción. +4. **Los comandos esenciales** (`/ask`, `/help`, `/clear`, `/plan`, `/research`, `/model`, `/exit`) cubren la mayor parte del uso diario. + +> 📋 **Referencia rápida**: consulta la [referencia de comandos de GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para ver una lista completa de comandos y atajos. + +--- + +## ➡️ Qué sigue + +Ahora que entiendes los tres modos, vamos a aprender a darle a Copilot CLI contexto sobre tu código. + +En **[Capítulo 02: Contexto y conversaciones](../02-context-conversations/README.md)** aprenderás: + +- La sintaxis `@` para referenciar archivos y directorios +- Gestión de sesiones con `--resume` y `--continue` +- Cómo la gestión de contexto hace que Copilot CLI sea verdaderamente potente + +--- + +**[← Volver al inicio del curso](../README.md)** | **[Continuar al Capítulo 02 →](../02-context-conversations/README.md)** diff --git a/localization/es-es/02-context-conversations/README.md b/localization/es-es/02-context-conversations/README.md new file mode 100644 index 00000000..87780a35 --- /dev/null +++ b/localization/es-es/02-context-conversations/README.md @@ -0,0 +1,908 @@ +![Capítulo 02: Contexto y conversaciones](../../../02-context-conversations/images/chapter-header.png) + +> **¿Y si la IA pudiera ver toda tu base de código, no solo un archivo a la vez?** + +En este capítulo desbloquearás el verdadero poder de GitHub Copilot CLI: el contexto. Aprenderás a usar la sintaxis `@` para referenciar archivos y directorios, dándole a Copilot CLI un conocimiento profundo de tu base de código. Descubrirás cómo mantener conversaciones entre sesiones, retomar el trabajo días después justo donde lo dejaste y verás cómo el análisis entre archivos detecta errores que las revisiones de un solo archivo pasan por alto. + +## 🎯 Objetivos de aprendizaje + +Al final de este capítulo, podrás: + +- Usar la sintaxis `@` para referenciar archivos, directorios e imágenes +- Reanudar sesiones anteriores con `--resume` y `--continue` +- Comprender cómo funcionan las [ventanas de contexto](../../../GLOSSARY.md#context-window) +- Escribir conversaciones efectivas de varios turnos +- Gestionar permisos de directorios para flujos de trabajo multiproyecto + +> ⏱️ **Tiempo estimado**: ~50 minutos (20 min de lectura + 30 min de práctica) + +--- + +## 🧩 Analogía del mundo real: trabajar con un colega + +El contexto marca la diferencia: sin contexto vs con contexto + +*Igual que tus colegas, Copilot CLI no lee la mente. ¡Proporcionar más información ayuda tanto a las personas como a Copilot a brindar soporte específico!* + +Imagina explicarle un error a un colega: + +> **Sin contexto**: "La app de libros no funciona." + +> **Con contexto**: "Mira `books.py`, especialmente la función `find_book_by_title`. No está haciendo coincidencias sin distinguir entre mayúsculas y minúsculas." + +Para proporcionar contexto a Copilot CLI usa *la sintaxis `@`* para apuntar Copilot CLI a archivos específicos. + +--- + +# Esencial: contexto básico + +Bloques de código brillantes conectados por estelas de luz que representan cómo fluye el contexto a través de las conversaciones de Copilot CLI + +Esta sección cubre todo lo que necesitas para trabajar de forma efectiva con el contexto. Domina primero estos fundamentos. + +--- + +## La sintaxis @ + +El símbolo `@` referencia archivos y directorios en tus prompts. Es la forma de decirle a Copilot CLI "mira este archivo". + +> 💡 **Nota**: Todos los ejemplos de este curso usan la carpeta `samples/` incluida en este repositorio, así puedes probar cada comando directamente. + +### Pruébalo ahora (sin configuración) + +Puedes probar esto con cualquier archivo de tu equipo: + +```bash +copilot + +# Apunta a cualquier archivo que tengas +> Explain what @package.json does +> Summarize @README.md +> What's in @.gitignore and why? +``` + +> 💡 **¿No tienes un proyecto a mano?** Crea un archivo de prueba rápido: +> ```bash +> echo "def greet(name): return 'Hello ' + name" > test.py +> copilot +> > What does @test.py do? +> ``` + +### Patrones básicos de @ + +| Patrón | Qué hace | Ejemplo de uso | +|---------|--------------|-------------| +| `@file.py` | Referencia un único archivo | `Review @samples/book-app-project/books.py` | +| `@folder/` | Referencia todos los archivos de un directorio | `Review @samples/book-app-project/` | +| `@file1.py @file2.py` | Referencia varios archivos | `Compare @samples/book-app-project/book_app.py @samples/book-app-project/books.py` | + +### Referenciar un único archivo + +```bash +copilot + +> Explain what @samples/book-app-project/utils.py does +``` + +--- + +
+🎬 ¡Míralo en acción! + +![Demo de contexto de archivo](../../../02-context-conversations/images/file-context-demo.gif) + +*La salida del demo varía. Tu modelo, herramientas y respuestas serán diferentes a lo mostrado aquí.* + +
+ +--- + +### Referenciar varios archivos + +```bash +copilot + +> Compare @samples/book-app-project/book_app.py and @samples/book-app-project/books.py for consistency +``` + +### Referenciar un directorio completo + +```bash +copilot + +> Review all files in @samples/book-app-project/ for error handling +``` + +--- + +## Inteligencia entre archivos + +Aquí es donde el contexto se convierte en un superpoder. El análisis de un solo archivo es útil. El análisis entre archivos es transformador. + +Inteligencia entre archivos: comparación entre análisis de un solo archivo y análisis entre archivos, mostrando cómo analizar archivos juntos revela errores, flujo de datos y patrones invisibles de forma aislada + +### Demo: encontrar errores que abarcan varios archivos + +```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? +``` + +> 💡 **Opción avanzada**: Para análisis entre archivos enfocado en seguridad, prueba los ejemplos de seguridad en Python: +> ```bash +> > @samples/buggy-code/python/user_service.py @samples/buggy-code/python/payment_processor.py +> > Find security vulnerabilities that span BOTH files +> ``` + +--- + +
+🎬 ¡Míralo en acción! + +![Demo multiarchivo](../../../02-context-conversations/images/multi-file-demo.gif) + +*La salida del demo varía. Tu modelo, herramientas y respuestas serán diferentes a lo mostrado aquí.* + +
+ +--- + +**Lo que descubre 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 +``` + +**Por qué importa esto**: Una revisión de un solo archivo se perdería el panorama general. Solo el análisis entre archivos revela: +- **Código duplicado** que debería consolidarse +- **Patrones de flujo de datos** que muestran cómo interactúan los componentes +- **Problemas arquitectónicos** que afectan la mantenibilidad + +--- + +### Demo: entender una base de código en 60 segundos + +Comparación en pantalla dividida que muestra una revisión manual de código tomando 1 hora frente al análisis asistido por IA tomando 10 segundos + +¿Nuevo en un proyecto? Aprende sobre él rápidamente usando Copilot CLI. + +```bash +copilot + +> @samples/book-app-project/ +> +> In one paragraph, what does this app do and what are its biggest quality issues? +``` + +**Lo que obtienes**: +``` +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. +``` + +**Resultado**: Lo que toma una hora de lectura de código se reduce a 10 segundos. Sabes exactamente dónde concentrarte. + +--- + +## Ejemplos prácticos + +### Ejemplo 1: revisión de código con contexto + +```bash +copilot + +> @samples/book-app-project/books.py Review this file for potential bugs + +# Copilot CLI now has the full file content and can give specific feedback: +# "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? + +# Now reviewing book_app.py, but still aware of books.py context +``` + +### Ejemplo 2: entender una base de código + +```bash +copilot + +> @samples/book-app-project/books.py What does this module do? + +# Copilot CLI reads books.py and understands the BookCollection class + +> @samples/book-app-project/ Give me an overview of the code structure + +# Copilot CLI scans the directory and summarizes + +> How does the app save and load books? + +# Copilot CLI can trace through the code it's already seen +``` + +
+🎬 ¡Mira una conversación de varios turnos en acción! + +![Demo multiturno](../../../02-context-conversations/images/multi-turn-demo.gif) + +*La salida del demo varía. Tu modelo, herramientas y respuestas serán diferentes a lo mostrado aquí.* + +
+ +### Ejemplo 3: refactorización entre archivos + +```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 sees both files and can suggest how to merge the duplicate code +``` + +--- + +## Gestión de sesiones + +Las sesiones se guardan automáticamente mientras trabajas. Puedes reanudar sesiones anteriores para continuar donde lo dejaste. + +### Las sesiones se guardan automáticamente + +Cada conversación se guarda automáticamente. Solo sal con normalidad: + +```bash +copilot + +> @samples/book-app-project/ Let's improve error handling across all modules + +[... do some work ...] + +> /exit +``` + +### Reanudar la sesión más reciente + +```bash +# Continue where you left off +copilot --continue +``` + +### Reanudar una sesión específica + +```bash +# Pick from a list of sessions interactively +copilot --resume + +# Or resume a specific session by ID +copilot --resume=abc123 + +# Or resume by the name you gave the session +copilot --resume="my book app review" +``` + +> 💡 **¿Cómo encuentro un ID de sesión?** No necesitas memorizarlos. Ejecutar `copilot --resume` sin un ID muestra una lista interactiva de tus sesiones anteriores, sus nombres, IDs y cuándo estuvieron activas por última vez. Solo elige la que quieras. +> +> **¿Y con varias terminales?** Cada ventana de terminal es su propia sesión con su propio contexto. Si tienes Copilot CLI abierto en tres terminales, son tres sesiones separadas. Ejecutar `--resume` desde cualquier terminal te permite explorarlas todas. La opción `--continue` toma primero la sesión del directorio de trabajo actual; si no existe ninguna allí, elige la sesión activa más reciente. +> +> **¿Puedo cambiar de sesión sin reiniciar?** Sí. Usa el comando de barra `/resume` desde dentro de una sesión activa: +> ``` +> > /resume +> # Shows a list of sessions to switch to +> ``` + +### Organiza tus sesiones + +Dale a las sesiones nombres significativos para que puedas encontrarlas más adelante. Puedes nombrar una sesión al iniciarla, o renombrarla en cualquier momento desde dentro de la sesión: + +```bash +# Name a session right when you start it +copilot --name book-app-review + +# Or rename the current session from inside +copilot + +> /rename book-app-review +# Session renamed for easier identification +``` + +Una vez nombrada una sesión, puedes reanudarla directamente por nombre sin navegar por una lista: + +```bash +copilot --resume=book-app-review +``` + +Para limpiar las sesiones que ya no necesitas, usa `/session delete` desde dentro de una sesión: + +```bash +copilot + +> /session delete # Deletes the current session +> /session delete abc123 # Deletes a specific session by ID +> /session delete-all # Deletes all sessions (use with care!) +``` + +### Verifica y gestiona el contexto + +A medida que añades archivos y conversación, la [ventana de contexto](../../../GLOSSARY.md#context-window) de Copilot CLI se llena. Hay varios comandos disponibles para ayudarte a mantener el control: + +```bash +copilot + +> /context +Context usage: 62k/200k tokens (31%) + +> /clear +# Abandons the current session (no history saved) and starts a fresh conversation + +> /new +# Ends the current session (saving it to history for search/resume) and starts a fresh conversation + +> /rewind +# Opens a timeline picker allowing you to roll back to an earlier point in your conversation +``` + +> 💡 **Cuándo usar `/clear` o `/new`**: Si has estado revisando books.py y quieres cambiar a discutir utils.py, ejecuta /new primero (o /clear si no necesitas el historial de la sesión). De lo contrario, el contexto obsoleto del tema anterior puede confundir las respuestas. + +> 💡 **¿Cometiste un error o quieres probar un enfoque diferente?** Usa `/rewind` (o pulsa Esc dos veces) para abrir un **selector de línea de tiempo** que te permite retroceder a cualquier punto anterior de tu conversación, no solo al más reciente. Esto es útil cuando tomaste el camino equivocado y quieres dar marcha atrás sin empezar todo de nuevo. + +--- + +### Continúa donde lo dejaste + +Línea de tiempo que muestra cómo persisten las sesiones de GitHub Copilot CLI a lo largo de varios días: comenzar el lunes, reanudar el miércoles con todo el contexto restaurado + +*Las sesiones se guardan automáticamente al salir. Reanúdalas días después con todo el contexto: archivos, problemas y progreso, todo recordado.* + +Imagina este flujo de trabajo a lo largo de varios días: + +```bash +# Monday: Start book app review with a name right from the beginning +copilot --name 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) +# Work on the fix... + +> /exit +``` + +```bash +# Wednesday: Resume exactly where you left off, by name +copilot --resume=book-app-review + +> 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 +``` + +**Lo que hace esto poderoso**: Días después, Copilot CLI recuerda: +- El archivo exacto en el que estabas trabajando +- La lista numerada de problemas +- Cuáles ya has abordado +- El contexto de tu conversación + +Sin volver a explicar. Sin volver a leer archivos. Solo continúa trabajando. + +--- + +**🎉 ¡Ahora conoces lo esencial!** La sintaxis `@`, la gestión de sesiones (`--name`/`--continue`/`--resume`/`/rename`) y los comandos de contexto (`/context`/`/clear`) son suficientes para ser muy productivo. Todo lo de abajo es opcional. Vuelve a ello cuando estés listo. + +--- + +# Opcional: profundiza más + +Cueva de cristal abstracta en tonos azules y morados que representa una exploración más profunda de los conceptos de contexto + +Estos temas se construyen sobre los esenciales anteriores. **Elige lo que te interese o salta directamente a [Práctica](#practice).** + +| Quiero aprender sobre... | Saltar a | +|---|---| +| Patrones comodín y comandos de sesión avanzados | [Patrones @ adicionales y comandos de sesión](#additional-patterns) | +| Construir contexto a través de varios prompts | [Conversaciones conscientes del contexto](#context-aware-conversations) | +| Límites de tokens y `/compact` | [Entender las ventanas de contexto](#understanding-context-windows) | +| Cómo elegir los archivos correctos para referenciar | [Elegir qué referenciar](#choosing-what-to-reference) | +| Analizar capturas de pantalla y mockups | [Trabajar con imágenes](#working-with-images) | + +
+Patrones @ adicionales y comandos de sesión + + +### Patrones @ adicionales + +Para usuarios avanzados, Copilot CLI admite patrones comodín y referencias a imágenes: + +| Patrón | Qué hace | +|---------|--------------| +| `@folder/*.py` | Todos los archivos .py en folder | +| `@**/test_*.py` | Comodín recursivo: encuentra todos los archivos de test en cualquier lugar | +| `@image.png` | Archivo de imagen para revisión de UI | + +```bash +copilot + +> Find all TODO comments in @samples/book-app-project/**/*.py +``` + +### Ver información de la sesión + +```bash +copilot + +> /session +# Shows current session details and workspace summary + +> /usage +# Shows session metrics and statistics +``` + +### Compartir tu sesión + +```bash +copilot + +> /share file ./my-session.md +# Exports session as a markdown file + +> /share gist +# Creates a GitHub gist with the session + +> /share html +# Exports session as a self-contained interactive HTML file +# Useful for sharing polished session reports with teammates or saving for reference +``` + +
+ +
+Conversaciones conscientes del contexto + + +### Conversaciones conscientes del contexto + +La magia ocurre cuando tienes conversaciones de varios turnos que se construyen unas sobre otras. + +#### Ejemplo: mejora progresiva + +```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..." +[Shows typed version] + +> Now improve error handling + +Copilot CLI: "Building on the typed version, here's improved error handling..." +[Adds validation and proper exceptions] + +> Generate tests for this final version + +Copilot CLI: "Based on the class with types and error handling..." +[Generates comprehensive tests] +``` + +Observa cómo cada prompt se basa en el trabajo anterior. Este es el poder del contexto. + +
+ +
+Entender las ventanas de contexto + + +### Entender las ventanas de contexto + +Ya conoces `/context` y `/clear` desde lo esencial. Aquí está la imagen más profunda de cómo funcionan las ventanas de contexto. + +Toda IA tiene una "ventana de contexto", que es la cantidad de texto que puede considerar a la vez. + +Visualización de la ventana de contexto + +*La ventana de contexto es como un escritorio: solo puede contener cierta cantidad a la vez. Los archivos, el historial de conversación y los prompts del sistema ocupan espacio.* + +#### Qué ocurre en el límite + +```bash +copilot + +> /context + +Context usage: 45,000 / 128,000 tokens (35%) + +# As you add more files and conversation, this grows + +> @large-codebase/ + +Context usage: 120,000 / 128,000 tokens (94%) + +# Warning: Approaching context limit + +> @another-large-file.py + +Context limit reached. Older context will be summarized. +``` + +#### El comando `/compact` + +Cuando tu contexto se está llenando pero no quieres perder la conversación, `/compact` resume tu historial para liberar tokens: + +```bash +copilot + +> /compact +# Summarizes conversation history, freeing up context space +# Your key findings and decisions are preserved +``` + +#### Consejos de eficiencia de contexto + +| Situación | Acción | Por qué | +|-----------|--------|-----| +| Iniciar nuevo tema | `/clear` | Elimina el contexto irrelevante | +| Tomaste el camino equivocado | `/rewind` | Retrocede a cualquier punto anterior | +| Conversación larga | `/compact` | Resume el historial, libera tokens | +| Necesitas un archivo específico | `@file.py` y no `@folder/` | Carga solo lo que necesitas | +| Llegando a los límites | `/new` o `/clear` | Contexto fresco | +| Varios temas | Usa `/rename` por tema | Es fácil reanudar la sesión correcta | + +#### Buenas prácticas para bases de código grandes + +1. **Sé específico**: `@samples/book-app-project/books.py` en lugar de `@samples/book-app-project/` +2. **Limpia el contexto entre temas**: Usa `/new` o `/clear` cuando cambies de enfoque +3. **Usa `/compact`**: Resume la conversación para liberar contexto +4. **Usa varias sesiones**: Una sesión por característica o tema + +
+ +
+Elegir qué referenciar + + +### Elegir qué referenciar + +No todos los archivos son iguales cuando se trata de contexto. Aquí te explicamos cómo elegir sabiamente: + +#### Consideraciones sobre el tamaño del archivo + +| Tamaño del archivo | [Tokens](../../../GLOSSARY.md#token) aproximados | Estrategia | +|-----------|-------------------|----------| +| Pequeño (<100 líneas) | ~500-1.500 tokens | Referencia con libertad | +| Mediano (100-500 líneas) | ~1.500-7.500 tokens | Referencia archivos específicos | +| Grande (500+ líneas) | 7.500+ tokens | Sé selectivo, usa archivos específicos | +| Muy grande (1000+ líneas) | 15.000+ tokens | Considera dividir o apuntar a secciones | + +**Ejemplos concretos:** +- Los 4 archivos Python de la app de libros combinados ≈ 2.000-3.000 tokens +- Un módulo Python típico (200 líneas) ≈ 3.000 tokens +- Un archivo de API Flask (400 líneas) ≈ 6.000 tokens +- Tu package.json ≈ 200-500 tokens +- Un prompt corto + respuesta ≈ 500-1.500 tokens + +> 💡 **Estimación rápida para código:** Multiplica las líneas de código por ~15 para obtener los tokens aproximados. Ten en cuenta que esto es solo una estimación. + +#### Qué incluir vs. qué excluir + +**Alto valor** (incluye estos): +- Puntos de entrada (`book_app.py`, `main.py`, `app.py`) +- Los archivos específicos sobre los que estás preguntando +- Archivos importados directamente por tu archivo objetivo +- Archivos de configuración (`requirements.txt`, `pyproject.toml`) +- Modelos de datos o dataclasses + +**Menor valor** (considera excluirlos): +- Archivos generados (salida compilada, recursos empaquetados) +- Módulos de Node o directorios de proveedores +- Archivos de datos grandes o fixtures +- Archivos no relacionados con tu pregunta + +#### El espectro de especificidad + +``` +Less specific ────────────────────────► More specific +@samples/book-app-project/ @samples/book-app-project/books.py:47-52 + │ │ + └─ Scans everything └─ Just what you need + (uses more context) (preserves context) +``` + +**Cuándo ir amplio** (`@samples/book-app-project/`): +- Exploración inicial de la base de código +- Encontrar patrones a través de muchos archivos +- Revisiones de arquitectura + +**Cuándo ir específico** (`@samples/book-app-project/books.py`): +- Depurar un problema concreto +- Revisión de código de un archivo específico +- Preguntar sobre una sola función + +#### Ejemplo práctico: carga de contexto por etapas + +```bash +copilot + +# Step 1: Start with structure +> @package.json What frameworks does this project use? + +# Step 2: Narrow based on answer +> @samples/book-app-project/ Show me the project structure + +# Step 3: Focus on what matters +> @samples/book-app-project/books.py Review the BookCollection class + +# Step 4: Add related files only as needed +> @samples/book-app-project/book_app.py @samples/book-app-project/books.py How does the CLI use the BookCollection? +``` + +Este enfoque por etapas mantiene el contexto enfocado y eficiente. + +
+ +
+Trabajar con imágenes + + +### Trabajar con imágenes + +Puedes incluir imágenes en tus conversaciones usando la sintaxis `@`, o simplemente **pegar desde el portapapeles** (Cmd+V / Ctrl+V). Copilot CLI puede analizar capturas de pantalla, mockups y diagramas para ayudarte con depuración de UI, implementación de diseños y análisis de errores. + +```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. +``` + +> 📖 **Aprende más**: Consulta [Funciones de contexto adicionales](../appendices/additional-context.md#working-with-images) para conocer formatos compatibles, casos de uso prácticos y consejos para combinar imágenes con código. + +
+ +--- + +# Práctica + +Configuración acogedora de escritorio con monitor mostrando código, lámpara, taza de café y auriculares listos para la práctica + +Es momento de aplicar tus habilidades de contexto y gestión de sesiones. + +--- + +## ▶️ Pruébalo tú mismo + +### Revisión completa del proyecto + +El curso incluye archivos de muestra que puedes revisar directamente. Inicia copilot y ejecuta el prompt que se muestra a continuación: + +```bash +copilot + +> @samples/book-app-project/ Give me a code quality review of this project + +# Copilot CLI will identify issues like: +# - Duplicate display functions +# - Missing input validation +# - Inconsistent error handling +``` + +> 💡 **¿Quieres probar con tus propios archivos?** Crea un pequeño proyecto Python (`mkdir -p my-project/src`), añade algunos archivos .py y luego usa `@my-project/src/` para revisarlos. ¡Puedes pedirle a copilot que cree código de muestra para ti si lo deseas! + +### Flujo de trabajo de sesión + +```bash +copilot + +> /rename book-app-review +> @samples/book-app-project/books.py Let's add input validation for empty titles + +[Copilot CLI suggests validation approach] + +> Implement that fix +> Now consolidate the duplicate display functions in @samples/book-app-project/ +> /exit + +# Later - resume where you left off +copilot --continue + +> Generate tests for the changes we made +``` + +--- + +Tras completar los demos, prueba estas variaciones: + +1. **Reto entre archivos**: Analiza cómo book_app.py y books.py trabajan juntos: + ```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. **Reto de sesión**: Inicia una sesión, nómbrala con `/rename my-first-session`, trabaja en algo, sal con `/exit`, luego ejecuta `copilot --continue`. ¿Recuerda lo que estabas haciendo? + +3. **Reto de contexto**: Ejecuta `/context` a mitad de la sesión. ¿Cuántos tokens estás usando? Prueba `/compact` y vuelve a verificar. (Consulta [Entender las ventanas de contexto](#understanding-context-windows) en Profundiza más para más información sobre `/compact`.) + +**Autocomprobación**: Entiendes el contexto cuando puedes explicar por qué `@folder/` es más potente que abrir cada archivo individualmente. + +--- + +## 📝 Tarea + +### Reto principal: traza el flujo de datos + +Los ejemplos prácticos se centraron en revisiones de calidad del código y validación de entrada. Ahora practica las mismas habilidades de contexto en una tarea diferente, trazando cómo se mueven los datos a través de la app: + +1. Inicia una sesión interactiva: `copilot` +2. Referencia `books.py` y `book_app.py` juntos: + `@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. Trae el archivo de datos para contexto adicional: + `@samples/book-app-project/data.json What happens if this JSON file is missing or corrupted? Which functions would fail?` +4. Pide una mejora entre archivos: + `@samples/book-app-project/books.py @samples/book-app-project/utils.py Suggest a consistent error-handling strategy that works across both files.` +5. Renombra la sesión: `/rename data-flow-analysis` +6. Sal con `/exit`, luego reanuda con `copilot --continue` y haz una pregunta de seguimiento sobre el flujo de datos + +**Criterios de éxito**: Puedes trazar datos a través de varios archivos, reanudar una sesión nombrada y obtener sugerencias entre archivos. + +
+💡 Pistas (haz clic para expandir) + +**Para empezar:** +```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 +``` + +Luego reanuda con: `copilot --continue` + +**Comandos útiles:** +- `@file.py` - Referencia un único archivo +- `@folder/` - Referencia todos los archivos de una carpeta (nota la `/` final) +- `/context` - Comprueba cuánto contexto estás usando +- `/rename ` - Nombra tu sesión para reanudarla fácilmente + +
+ +### Reto extra: límites de contexto + +1. Referencia todos los archivos de la app de libros a la vez con `@samples/book-app-project/` +2. Haz varias preguntas detalladas sobre diferentes archivos (`books.py`, `utils.py`, `book_app.py`, `data.json`) +3. Ejecuta `/context` para ver el uso. ¿Qué tan rápido se llena? +4. Practica usando `/compact` para recuperar espacio, luego continúa la conversación +5. Prueba a ser más específico con las referencias a archivos (por ejemplo, `@samples/book-app-project/books.py` en lugar de toda la carpeta) y observa cómo afecta al uso de contexto + +--- + +
+🔧 Errores comunes y solución de problemas (haz clic para expandir) + +### Errores comunes + +| Error | Qué ocurre | Solución | +|---------|--------------|-----| +| Olvidar el `@` antes de los nombres de archivo | Copilot CLI trata "books.py" como texto plano | Usa `@samples/book-app-project/books.py` para referenciar archivos | +| Esperar que las sesiones persistan automáticamente | Iniciar `copilot` desde cero pierde todo el contexto anterior | Usa `--continue` (última sesión) o `--resume` (elegir una sesión) | +| Referenciar archivos fuera del directorio actual | Errores "Permission denied" o "File not found" | Usa `/add-dir /path/to/directory` para conceder acceso | +| No usar `/clear` al cambiar de tema | El contexto antiguo confunde las respuestas sobre el nuevo tema | Ejecuta `/clear` antes de empezar una tarea diferente | + +### Solución de problemas + +**Errores "File not found"** - Asegúrate de estar en el directorio correcto: + +```bash +pwd # Check current directory +ls # List files + +# Then start copilot and use relative paths +copilot + +> Review @samples/book-app-project/books.py +``` + +**"Permission denied"** - Añade el directorio a tu lista permitida: + +```bash +copilot --add-dir /path/to/directory + +# Or in a session: +> /add-dir /path/to/directory +``` + +**El contexto se llena demasiado rápido**: +- Sé más específico con las referencias a archivos +- Usa `/clear` entre temas diferentes +- Divide el trabajo entre varias sesiones + +
+ +--- + +# Resumen + +## 🔑 Conclusiones clave + +1. **La sintaxis `@`** le da a Copilot CLI contexto sobre archivos, directorios e imágenes +2. **Las conversaciones de varios turnos** se construyen unas sobre otras conforme se acumula el contexto +3. **Las sesiones se guardan automáticamente**: nómbralas al inicio con `--name`, reanúdalas por nombre con `--resume=`, o usa `--continue` para retomar la sesión más reciente +4. **Las ventanas de contexto** tienen límites: gestiónalas con `/clear`, `/compact`, `/context`, `/new` y `/rewind` +5. **Las opciones de permisos** (`--add-dir`, `--allow-all`) controlan el acceso multidirectorio. ¡Úsalas con cuidado! +6. **Las referencias a imágenes** (`@screenshot.png`) ayudan a depurar visualmente problemas de UI + +> 📚 **Documentación oficial**: [Use Copilot CLI](https://docs.github.com/copilot/how-tos/copilot-cli/use-copilot-cli) para la referencia completa sobre contexto, sesiones y trabajo con archivos. + +> 📋 **Referencia rápida**: Consulta la [referencia de comandos de GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para ver una lista completa de comandos y atajos. + +--- + +## ➡️ Qué sigue + +Ahora que puedes darle contexto a Copilot CLI, vamos a ponerlo a trabajar en tareas reales de desarrollo. Las técnicas de contexto que acabas de aprender (referencias a archivos, análisis entre archivos y gestión de sesiones) son la base de los potentes flujos de trabajo del próximo capítulo. + +En el **[Capítulo 03: Flujos de trabajo de desarrollo](../03-development-workflows/README.md)** aprenderás: + +- Flujos de trabajo de revisión de código +- Patrones de refactorización +- Asistencia para depuración +- Generación de tests +- Integración con git + +--- + +**[← Volver al Capítulo 01](../01-setup-and-first-steps/README.md)** | **[Continuar al Capítulo 03 →](../03-development-workflows/README.md)** diff --git a/localization/es-es/03-development-workflows/README.md b/localization/es-es/03-development-workflows/README.md new file mode 100644 index 00000000..879ff318 --- /dev/null +++ b/localization/es-es/03-development-workflows/README.md @@ -0,0 +1,972 @@ +![Capítulo 03: Flujos de trabajo de desarrollo](../../../03-development-workflows/images/chapter-header.png) + +> **¿Y si la IA pudiera encontrar errores que ni siquiera sabías que tenías que preguntar?** + +En este capítulo, GitHub Copilot CLI se convierte en tu compañero diario. Lo usarás dentro de los flujos de trabajo en los que ya confías cada día: pruebas, refactorización, depuración y Git. + +## 🎯 Objetivos de aprendizaje + +Al final de este capítulo, podrás: + +- Realizar revisiones exhaustivas de código con Copilot CLI +- Refactorizar código heredado de forma segura +- Depurar problemas con asistencia de IA +- Generar tests automáticamente +- Integrar Copilot CLI con tu flujo de trabajo de git + +> ⏱️ **Tiempo estimado**: ~60 minutos (15 min de lectura + 45 min de práctica) + +--- + +## 🧩 Analogía del mundo real: el flujo de trabajo de un carpintero + +Un carpintero no solo sabe usar herramientas, tiene *flujos de trabajo* para distintas tareas: + +Taller de artesano que muestra tres carriles de flujo de trabajo: Construir muebles (Medir, Cortar, Ensamblar, Acabar), Reparar daños (Evaluar, Quitar, Reparar, Igualar) y Control de calidad (Inspeccionar, Probar uniones, Verificar alineación) + +De forma similar, los desarrolladores tienen flujos de trabajo para distintas tareas. GitHub Copilot CLI mejora cada uno de estos flujos, haciéndote más eficiente y efectivo en tus tareas diarias de programación. + +--- + +# Los cinco flujos de trabajo + +Cinco iconos de neón brillantes que representan los flujos de revisión de código, pruebas, depuración, refactorización e integración con git + +Cada flujo de trabajo a continuación es autocontenido. Elige los que se ajusten a tus necesidades actuales o trabaja con todos. + +--- + +## Elige tu propia aventura + +Este capítulo cubre cinco flujos de trabajo que los desarrolladores suelen usar. **¡Sin embargo, no necesitas leerlos todos a la vez!** Cada flujo de trabajo es autocontenido en una sección colapsable a continuación. Elige los que se ajusten a lo que necesitas y que mejor encajen con tu proyecto actual. Siempre puedes volver y explorar los demás más adelante. + +Cinco flujos de trabajo de desarrollo: Revisión de código, Refactorización, Depuración, Generación de tests e Integración con Git mostrados como carriles horizontales + +| Quiero... | Saltar a | +|---|---| +| Revisar código antes de fusionar | [Flujo 1: Revisión de código](#workflow-1-code-review) | +| Limpiar código desordenado o heredado | [Flujo 2: Refactorización](#workflow-2-refactoring) | +| Localizar y corregir un error | [Flujo 3: Depuración](#workflow-3-debugging) | +| Generar tests para mi código | [Flujo 4: Generación de tests](#workflow-4-test-generation) | +| Escribir mejores commits y PRs | [Flujo 5: Integración con Git](#workflow-5-git-integration) | +| Investigar antes de codificar | [Consejo rápido: investiga antes de planificar o codificar](#quick-tip-research-before-you-plan-or-code) | +| Ver un flujo completo de corrección de errores de principio a fin | [Poniéndolo todo junto](#putting-it-all-together-bug-fix-workflow) | + +**Selecciona un flujo de trabajo a continuación para expandirlo** y ver cómo GitHub Copilot CLI puede mejorar tu proceso de desarrollo en esa área. + +--- + + +
+Flujo 1: Revisión de código - Revisar archivos, usar el agente /review, crear listas de verificación por severidad + +Flujo de revisión de código: revisar, identificar problemas, priorizar, generar lista de verificación. + +### Revisión básica + +Este ejemplo usa el símbolo `@` para referenciar un archivo, dándole a Copilot CLI acceso directo a su contenido para su revisión. + +```bash +copilot + +> Review @samples/book-app-project/book_app.py for code quality +``` + +--- + +
+🎬 ¡Míralo en acción! + +![Demo de revisión de código](../../../03-development-workflows/images/code-review-demo.gif) + +*La salida del demo varía. Tu modelo, herramientas y respuestas serán diferentes a lo mostrado aquí.* + +
+ +--- + +### Revisión de validación de entrada + +Pídele a Copilot CLI que enfoque su revisión en una preocupación específica (aquí, validación de entrada) listando las categorías que te importan en el prompt. + +```text +copilot + +> Review @samples/book-app-project/utils.py for input validation issues. Check for: missing validation, error handling gaps, and edge cases +``` + + +### Revisión de proyecto entre archivos + +Referencia un directorio completo con `@` para que Copilot CLI escanee todos los archivos del proyecto a la vez. + +```bash +copilot + +> @samples/book-app-project/ Review this entire project. Create a markdown checklist of issues found, categorized by severity +``` + +### Revisión de código interactiva + +Usa una conversación de varios turnos para profundizar. Empieza con una revisión amplia, luego haz preguntas de seguimiento sin reiniciar. + +```bash +copilot + +> @samples/book-app-project/book_app.py Review this file for: +> - Input validation +> - Error handling +> - Code style and best practices + +# Copilot CLI provides detailed review + +> The user input handling - are there any edge cases I'm missing? + +# Copilot CLI shows potential issues with empty strings, special characters + +> Create a checklist of all issues found, prioritized by severity + +# Copilot CLI generates prioritized action items +``` + +### Plantilla de lista de verificación de revisión + +Pídele a Copilot CLI que estructure su salida en un formato específico (aquí, una lista de verificación markdown categorizada por severidad que puedes pegar en un 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) +``` + +### Entender los cambios de Git (importante para /review) + +Antes de usar el comando `/review`, necesitas entender dos tipos de cambios en git: + +| Tipo de cambio | Qué significa | Cómo verlo | +|-------------|---------------|------------| +| **Cambios en stage** | Archivos que has marcado para el próximo commit con `git add` | `git diff --staged` | +| **Cambios fuera de stage** | Archivos que has modificado pero aún no has añadido | `git diff` | + +```bash +# Quick reference +git status # Shows both staged and unstaged +git add file.py # Stage a file for commit +git diff # Shows unstaged changes +git diff --staged # Shows staged changes +``` + +### Usando el comando /review + +El comando `/review` invoca el **agente code-review** integrado, que está optimizado para analizar cambios en stage y fuera de stage con una salida de alta relación señal-ruido. Usa un comando de barra para activar un agente integrado especializado en lugar de escribir un prompt libre. + +```bash +copilot + +> /review +# Invokes the code-review agent on staged/unstaged changes +# Provides focused, actionable feedback + +> /review Check for security issues in authentication +# Run review with specific focus area +``` + +> 💡 **Consejo**: El agente code-review funciona mejor cuando tienes cambios pendientes. Pasa tus archivos a stage con `git add` para revisiones más enfocadas. + +
+ +--- + + +
+Flujo 2: Refactorización - Reestructurar código, separar responsabilidades, mejorar el manejo de errores + +Flujo de refactorización: evaluar el código, planificar cambios, implementar, verificar el comportamiento. + +### Refactorización simple + +> **Prueba esto primero:** `@samples/book-app-project/book_app.py The command handling uses if/elif chains. Refactor it to use a dictionary dispatch pattern.` + +Empieza con mejoras sencillas. Pruébalas en la app de libros. Cada prompt usa una referencia de archivo `@` junto con una instrucción específica de refactorización para que Copilot CLI sepa exactamente qué cambiar. + +```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 +``` + +> 💡 **¿Nuevo en la refactorización?** Empieza con peticiones sencillas como añadir type hints o mejorar nombres de variables antes de abordar transformaciones complejas. + +--- + +
+🎬 ¡Míralo en acción! + +![Demo de refactorización](../../../03-development-workflows/images/refactor-demo.gif) + +*La salida del demo varía. Tu modelo, herramientas y respuestas serán diferentes a lo mostrado aquí.* + +
+ +--- + +### Separar responsabilidades + +Referencia varios archivos con `@` en un solo prompt para que Copilot CLI pueda mover código entre ellos como parte de la refactorización. + +```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. +``` + +### Mejorar el manejo de errores + +Proporciona dos archivos relacionados y describe la preocupación transversal para que Copilot CLI pueda sugerir una solución consistente en ambos. + +```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. +``` + +### Añadir documentación + +Usa una lista detallada de viñetas para especificar exactamente qué debe contener cada 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 +``` + +### Refactorización segura con tests + +Encadena dos peticiones relacionadas en una conversación de varios turnos. Primero genera tests, luego refactoriza con esos tests como red de seguridad. + +```bash +copilot + +> @samples/book-app-project/books.py Before refactoring, generate tests for current behavior + +# Get tests first + +> Now refactor the BookCollection class to use a context manager for file operations + +# Refactor with confidence - tests verify behavior is preserved +``` + +
+ +--- + + +
+Flujo 3: Depuración - Localizar errores, auditorías de seguridad, rastrear problemas entre archivos + +Flujo de depuración: entender el error, localizar la causa raíz, corregir, probar. + +### Depuración simple + +> **Prueba esto primero:** `@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.` + +Empieza describiendo qué falla. Aquí tienes patrones comunes de depuración que puedes probar con la app de libros con errores. Cada prompt empareja una referencia de archivo `@` con una descripción clara del síntoma para que Copilot CLI pueda localizar y diagnosticar el error. + +```bash +copilot + +# Pattern: "Expected X but got 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. + +# Pattern: "Unexpected behavior" +> @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. + +# Pattern: "Wrong results" +> @samples/book-app-buggy/books_buggy.py When I mark one book as read, ALL books get marked. What's the bug? +``` + +> 💡 **Consejo de depuración**: Describe el *síntoma* (lo que ves) y la *expectativa* (lo que debería ocurrir). Copilot CLI averigua el resto. + +--- + +
+🎬 ¡Míralo en acción! + +![Demo de corrección de error](../../../03-development-workflows/images/fix-bug-demo.gif) + +*La salida del demo varía. Tu modelo, herramientas y respuestas serán diferentes a lo mostrado aquí.* + +
+ +--- + +### El "Detective de errores" - La IA encuentra errores RELACIONADOS + +Aquí es donde brilla la depuración consciente del contexto. Prueba este escenario con la app de libros con errores. Proporciona el archivo completo mediante `@` y describe solo el síntoma reportado por el usuario. Copilot CLI rastreará la causa raíz y puede detectar errores adicionales cercanos. + +```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 +``` + +**Lo que hace 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()] +``` + +**Por qué importa esto**: Copilot CLI lee el archivo completo, entiende el contexto de tu reporte de error y te da una corrección específica con una explicación clara. + +> 💡 **Bonus**: Como Copilot CLI analiza todo el archivo, a menudo descubre *otros* problemas que no preguntaste. Por ejemplo, mientras corrige la búsqueda por autor, ¡Copilot CLI también podría notar el error de sensibilidad a mayúsculas en `find_book_by_title`! + +### Apartado de seguridad del mundo real + +Si bien depurar tu propio código es importante, entender vulnerabilidades de seguridad en aplicaciones de producción es crítico. Prueba este ejemplo: Apunta Copilot CLI a un archivo desconocido y pídele que audite problemas de seguridad. + +```bash +copilot + +> @samples/buggy-code/python/user_service.py Find all security vulnerabilities in this Python user service +``` + +Este archivo demuestra patrones de seguridad reales que encontrarás en apps de producción. + +> 💡 **Términos comunes de seguridad que encontrarás:** +> - **Inyección SQL**: Cuando la entrada del usuario se inserta directamente en una consulta de base de datos, permitiendo a atacantes ejecutar comandos maliciosos +> - **Consultas parametrizadas**: La alternativa segura - los marcadores de posición (`?`) separan los datos del usuario de los comandos SQL +> - **Condición de carrera**: Cuando dos operaciones ocurren al mismo tiempo e interfieren entre sí +> - **XSS (Cross-Site Scripting)**: Cuando los atacantes inyectan scripts maliciosos en páginas web + +--- + +### Entender un error + +Pega un stack trace directamente en tu prompt junto con una referencia de archivo `@` para que Copilot CLI pueda mapear el error al código fuente. + +```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 +``` + +### Depuración con caso de prueba + +Describe la entrada exacta y la salida observada para darle a Copilot CLI un caso de prueba concreto y reproducible sobre el que razonar. + +```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. +``` + +### Rastrear un problema a través del código + +Referencia varios archivos y pídele a Copilot CLI que siga el flujo de datos a través de ellos para localizar dónde se origina el problema. + +```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 +``` + +### Entender problemas de datos + +Incluye un archivo de datos junto al código que lo lee para que Copilot CLI entienda el panorama completo al sugerir mejoras en el manejo de errores. + +```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? +``` + +
+ +--- + + +
+Flujo 4: Generación de tests - Generar tests exhaustivos y casos límite automáticamente + +Flujo de generación de tests: analizar función, generar tests, incluir casos límite, ejecutar. + +> **Prueba esto primero:** `@samples/book-app-project/books.py Generate pytest tests for all functions including edge cases` + +### La "Explosión de tests" - 2 tests vs 15+ tests + +Al escribir tests manualmente, los desarrolladores normalmente crean 2-3 tests básicos: +- Probar entrada válida +- Probar entrada inválida +- Probar un caso límite + +¡Mira lo que ocurre cuando le pides a Copilot CLI que genere tests exhaustivos! Este prompt usa una lista de viñetas estructurada con una referencia de archivo `@` para guiar a Copilot CLI hacia una cobertura de tests completa: + +```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 +``` + +--- + +
+🎬 ¡Míralo en acción! + +![Demo de generación de tests](../../../03-development-workflows/images/test-gen-demo.gif) + +*La salida del demo varía. Tu modelo, herramientas y respuestas serán diferentes a lo mostrado aquí.* + +
+ +--- + +**Lo que obtienes**: 15+ tests exhaustivos incluyendo: + +```python +class TestBookCollection: + # Happy path + def test_add_book_creates_new_book(self): + ... + def test_list_books_returns_all_books(self): + ... + + # Find operations + 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): + ... + + # Edge cases + def test_add_book_with_empty_title(self): + ... + def test_remove_nonexistent_book(self): + ... + def test_mark_as_read_nonexistent_book(self): + ... + + # Data persistence + def test_save_books_persists_to_json(self): + ... + def test_load_books_handles_missing_file(self): + ... + def test_load_books_handles_corrupted_json(self): + ... + + # Special characters + def test_add_book_with_unicode_characters(self): + ... + def test_find_by_author_with_special_characters(self): + ... +``` + +**Resultado**: En 30 segundos, obtienes tests de casos límite que tomaría una hora pensar y escribir. + +--- + +### Tests unitarios + +Apunta a una sola función y enumera las categorías de entrada que quieres probar para que Copilot CLI genere tests unitarios enfocados y exhaustivos. + +```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 +``` + +### Ejecutar tests + +Hazle a Copilot CLI una pregunta en lenguaje natural sobre tu cadena de herramientas. Puede generar el comando de shell adecuado por ti. + +```bash +copilot + +> How do I run the tests? Show me the pytest command. + +# Copilot CLI responds: +# cd samples/book-app-project && python -m pytest tests/ +# Or for verbose output: python -m pytest tests/ -v +# To see print statements: python -m pytest tests/ -s +``` + +### Tests para escenarios específicos + +Lista escenarios avanzados o complicados que quieres cubrir para que Copilot CLI vaya más allá del happy path. + +```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 +``` + +### Añadir tests a un archivo existente + +Pide tests *adicionales* para una sola función para que Copilot CLI genere casos nuevos que complementen los que ya tienes. + +```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 +``` + +
+ +--- + + +
+Flujo 5: Integración con Git - Mensajes de commit, descripciones de PR, /pr, /delegate y /diff + +Flujo de integración con Git: pasar cambios a stage, generar mensaje, hacer commit, crear PR. + +> 💡 **Este flujo de trabajo asume familiaridad básica con git** (stage, commit, ramas). Si git es nuevo para ti, prueba primero los otros cuatro flujos. + +### Generar mensajes de commit + +> **Prueba esto primero:** `copilot -p "Generate a conventional commit message for: $(git diff --staged)"` — pasa algunos cambios a stage, luego ejecuta esto para ver a Copilot CLI escribir tu mensaje de commit. + +Este ejemplo usa la opción de prompt en línea `-p` con sustitución de comandos de shell para canalizar la salida de `git diff` directamente a Copilot CLI para un mensaje de commit de un solo disparo. La sintaxis `$(...)` ejecuta el comando dentro de los paréntesis e inserta su salida en el comando exterior. + +```bash + +# See what changed +git diff --staged + +# Generate commit message using [Conventional Commit](../../../GLOSSARY.md#conventional-commit) format +# (structured messages like "feat(books): add search" or "fix(data): handle empty input") +copilot -p "Generate a conventional commit message for: $(git diff --staged)" + +# Output: "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" +``` + +--- + +
+🎬 ¡Míralo en acción! + +![Demo de integración con Git](../../../03-development-workflows/images/git-integration-demo.gif) + +*La salida del demo varía. Tu modelo, herramientas y respuestas serán diferentes a lo mostrado aquí.* + +
+ +--- + +### Explicar cambios + +Canaliza la salida de `git show` a un prompt `-p` para obtener un resumen en lenguaje natural del último commit. + +```bash +# What did this commit change? +copilot -p "Explain what this commit does: $(git show HEAD --stat)" +``` + +### Descripción de PR + +Combina la salida de `git log` con una plantilla de prompt estructurado para autogenerar una descripción completa de pull request. + +```bash +# Generate PR description from branch changes +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)" +``` + +### Usando /pr en modo interactivo para la rama actual + +Si estás trabajando con una rama en el modo interactivo de Copilot CLI, puedes usar el comando `/pr` para trabajar con pull requests. Usa `/pr` para ver un PR, crear un nuevo PR, corregir un PR existente o dejar que Copilot CLI decida automáticamente según el estado de la rama. + +```bash +copilot + +> /pr [view|create|fix|auto] +``` + +### Revisar antes de hacer push + +Usa `git diff main..HEAD` dentro de un prompt `-p` para una rápida verificación antes del push entre todos los cambios de la rama. + +```bash +# Last check before pushing +copilot -p "Review these changes for issues before I push: +$(git diff main..HEAD)" +``` + +### Usando /delegate para tareas en segundo plano + +El comando `/delegate` delega trabajo al agente en la nube de GitHub Copilot. Usa el comando de barra `/delegate` (o el atajo `&`) para delegar una tarea bien definida a un agente en segundo plano. + +```bash +copilot + +> /delegate Add input validation to the login form + +# Or use the & prefix shortcut: +> & Fix the typo in the README header + +# Copilot CLI: +# 1. Commits your changes to a new branch +# 2. Opens a draft pull request +# 3. Works in the background on GitHub +# 4. Requests your review when done +``` + +Esto es excelente para tareas bien definidas que quieres completar mientras te enfocas en otro trabajo. + +### Usando /diff para revisar cambios de la sesión + +El comando `/diff` muestra todos los cambios realizados durante tu sesión actual. Usa este comando de barra para ver un diff visual de todo lo que Copilot CLI ha modificado antes de hacer commit. + +```bash +copilot + +# After making some changes... +> /diff + +# Shows a visual diff of all files modified in this session +# Great for reviewing before committing +``` + +
+ +--- + +## Consejo rápido: investiga antes de planificar o codificar + +Cuando necesitas investigar una librería, entender buenas prácticas o explorar un tema desconocido, usa `/research` para realizar una investigación profunda antes de escribir cualquier código: + +```bash +copilot + +> /research What are the best Python libraries for validating user input in CLI apps? +``` + +Copilot busca en repositorios de GitHub y fuentes web, luego devuelve un resumen con referencias. Esto es útil cuando estás a punto de empezar una nueva característica y quieres tomar decisiones informadas primero. Puedes compartir los resultados usando `/share`. + +> 💡 **Consejo**: `/research` funciona bien *antes* de `/plan`. Investiga el enfoque, luego planifica la implementación. + +--- + +## Poniéndolo todo junto: flujo de corrección de errores + +Aquí tienes un flujo completo para corregir un error reportado: + +```bash + +# 1. Understand the bug report +copilot + +> Users report: 'Finding books by author name doesn't work for partial names' +> @samples/book-app-project/books.py Analyze and identify the likely cause + +# 2. Debug the issue and fix (continuing in same session) +> Based on the analysis, show me the find_by_author function and explain the issue + +> Fix the find_by_author function to handle partial name matches + +# 3. Generate tests for the fix +> @samples/book-app-project/books.py Generate pytest tests specifically for: +> - Full author name match +> - Partial author name match +> - Case-insensitive matching +> - Author name not found + +# Exit the interactive session + +> /exit + +# 4. Run git add + +# Stage the changes so git diff --staged has something to work with +git add . + +# 5. Generate commit message +copilot -p "Generate commit message for: $(git diff --staged)" + +# Example Output: "fix(books): support partial author name search" + +# 6. Commit changes (optional) + +git commit -m "" +``` + +### Resumen del flujo de corrección de errores + +| Paso | Acción | Comando de Copilot | +|------|--------|-----------------| +| 1 | Entender el error | `> [describe bug] @relevant-file.py Analyze the likely cause` | +| 2 | Análisis y corrección | `> Show me the function and fix the issue` | +| 3 | Generar tests | `> Generate tests for [specific scenarios]` | +| 4 | Pasar cambios a stage | `git add .` | +| 5 | Generar mensaje de commit | `copilot -p "Generate commit message for: $(git diff --staged)"` | +| 6 | Hacer commit | `git commit -m ""` | + +--- + +# Práctica + +Configuración acogedora de escritorio con monitor mostrando código, lámpara, taza de café y auriculares listos para la práctica + +Ahora es tu turno de aplicar estos flujos de trabajo. + +--- + +## ▶️ Pruébalo tú mismo + +Tras completar los demos, prueba estas variaciones: + +1. **Reto del Detective de errores**: Pídele a Copilot CLI que depure la función `mark_as_read` en `samples/book-app-buggy/books_buggy.py`. ¿Explicó por qué la función marca TODOS los libros como leídos en lugar de solo uno? + +2. **Reto de tests**: Genera tests para la función `add_book` en la app de libros. Cuenta cuántos casos límite incluye Copilot CLI que no se te habrían ocurrido. + +3. **Reto de mensaje de commit**: Haz cualquier cambio pequeño en un archivo de la app de libros, pásalo a stage (`git add .`) y luego ejecuta: + ```bash + copilot -p "Generate a conventional commit message for: $(git diff --staged)" + ``` + ¿Es el mensaje mejor de lo que habrías escrito rápidamente? + +**Autocomprobación**: Entiendes los flujos de trabajo de desarrollo cuando puedes explicar por qué "depura este error" es más potente que "encuentra errores" (¡el contexto importa!). + +--- + +## 📝 Tarea + +### Reto principal: refactoriza, prueba y entrega + +Los ejemplos prácticos se centraron en `find_book_by_title` y revisiones de código. Ahora practica las mismas habilidades de flujo de trabajo en diferentes funciones en `book-app-project`: + +1. **Revisar**: Pídele a Copilot CLI que revise `remove_book()` en `books.py` para casos límite y problemas potenciales: + `@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. **Refactorizar**: Pídele a Copilot CLI que mejore `remove_book()` para manejar casos límite como coincidencia sin distinguir mayúsculas y minúsculas y devolver retroalimentación útil cuando no se encuentre un libro +3. **Probar**: Genera tests pytest específicamente para la función `remove_book()` mejorada, cubriendo: + - Eliminar un libro que existe + - Coincidencia de título sin distinguir mayúsculas y minúsculas + - Un libro que no existe devuelve retroalimentación apropiada + - Eliminar de una colección vacía +4. **Revisar**: Pasa tus cambios a stage y ejecuta `/review` para comprobar si quedan problemas +5. **Commit**: Genera un mensaje de commit convencional: + `copilot -p "Generate a conventional commit message for: $(git diff --staged)"` + +
+💡 Pistas (haz clic para expandir) + +**Prompts de muestra para cada paso:** + +```bash +copilot + +# Step 1: Review +> @samples/book-app-project/books.py Review the remove_book() function. What edge cases are not handled? + +# Step 2: Refactor +> 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. + +# Step 3: Test +> 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 + +# Step 4: Review +> /review + +# Step 5: Commit +> Generate a conventional commit message for this refactor +``` + +**Consejo:** Tras mejorar `remove_book()`, prueba a preguntarle a Copilot CLI: "¿Hay otras funciones en este archivo que podrían beneficiarse de las mismas mejoras?". Puede sugerir cambios similares para `find_book_by_title()` o `find_by_author()`. + +
+ +### Reto extra: crear una aplicación con Copilot CLI + +> 💡 **Nota**: Este ejercicio de GitHub Skills usa **Node.js** en lugar de Python. Las técnicas de GitHub Copilot CLI que practicarás (crear issues, generar código y colaborar desde la terminal) se aplican a cualquier lenguaje. + +El ejercicio muestra a los desarrolladores cómo usar GitHub Copilot CLI para crear issues, generar código y colaborar desde la terminal mientras construyen una app calculadora en Node.js. Instalarás la CLI, usarás plantillas y agentes, y practicarás desarrollo iterativo dirigido por línea de comandos. + +##### [Comienza el ejercicio de Skills "Create applications with the Copilot CLI"](https://github.com/skills/create-applications-with-the-copilot-cli) + +--- + +
+🔧 Errores comunes y solución de problemas (haz clic para expandir) + +### Errores comunes + +| Error | Qué ocurre | Solución | +|---------|--------------|-----| +| Usar prompts vagos como "Review this code" | Retroalimentación genérica que pasa por alto problemas específicos | Sé específico: "Review for SQL injection, XSS, and auth issues" | +| No usar `/review` para revisiones de código | Te pierdes el agente code-review optimizado | Usa `/review` que está afinado para una salida con alta relación señal-ruido | +| Pedir "encontrar errores" sin contexto | Copilot CLI no sabe qué error estás experimentando | Describe el síntoma: "Users report X happens when Y" | +| Generar tests sin especificar el framework | Los tests pueden usar la sintaxis o la librería de aserciones equivocada | Especifica: "Generate tests using Jest" o "using pytest" | + +### Solución de problemas + +**La revisión parece incompleta** - Sé más específico sobre qué buscar: + +```bash +copilot + +# Instead of: +> Review @samples/book-app-project/book_app.py + +# Try: +> Review @samples/book-app-project/book_app.py for input validation, error handling, and edge cases +``` + +**Los tests no coinciden con mi framework** - Especifica el framework: + +```bash +copilot + +> @samples/book-app-project/books.py Generate tests using pytest (not unittest) +``` + +**La refactorización cambia el comportamiento** - Pídele a Copilot CLI que preserve el comportamiento: + +```bash +copilot + +> @samples/book-app-project/book_app.py Refactor command handling to use dictionary dispatch. IMPORTANT: Maintain identical external behavior - no breaking changes +``` + +
+ +--- + +# Resumen + +## 🔑 Conclusiones clave + +Flujos de trabajo especializados para cada tarea: revisión de código, refactorización, depuración, pruebas e integración con Git + +1. **La revisión de código** se vuelve exhaustiva con prompts específicos +2. **La refactorización** es más segura cuando generas tests primero +3. **La depuración** se beneficia de mostrar a Copilot CLI el error Y el código +4. **La generación de tests** debe incluir casos límite y escenarios de error +5. **La integración con Git** automatiza mensajes de commit y descripciones de PR + +> 📋 **Referencia rápida**: Consulta la [referencia de comandos de GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para ver una lista completa de comandos y atajos. + +--- + +## ✅ Punto de control: has dominado lo esencial + +**¡Felicidades!** Ahora tienes todas las habilidades fundamentales para ser productivo con GitHub Copilot CLI: + +| Habilidad | Capítulo | Ahora puedes... | +|-------|---------|----------------| +| Comandos básicos | Cap 01 | Usar el modo interactivo, modo de planificación, modo programático (-p) y comandos de barra | +| Contexto | Cap 02 | Referenciar archivos con `@`, gestionar sesiones, entender ventanas de contexto | +| Flujos de trabajo | Cap 03 | Revisar código, refactorizar, depurar, generar tests, integrar con git | + +Los Capítulos 04-06 cubren características adicionales que añaden aún más potencia y vale la pena aprender. + +--- + +## 🛠️ Construyendo tu flujo de trabajo personal + +No hay una única manera "correcta" de usar GitHub Copilot CLI. Aquí tienes algunos consejos mientras desarrollas tus propios patrones: + +> 📚 **Documentación oficial**: [Copilot CLI best practices](https://docs.github.com/copilot/how-tos/copilot-cli/cli-best-practices) para flujos de trabajo y consejos recomendados de GitHub. + +- **Empieza con `/plan`** para cualquier cosa no trivial. Refina el plan antes de la ejecución: un buen plan lleva a mejores resultados. +- **Guarda los prompts que funcionan bien.** Cuando Copilot CLI cometa un error, anota qué salió mal. Con el tiempo, esto se convierte en tu manual personal. +- **Experimenta libremente.** Algunos desarrolladores prefieren prompts largos y detallados. Otros prefieren prompts cortos con seguimientos. Prueba diferentes enfoques y observa cuál se siente natural. + +> 💡 **Próximamente**: En los Capítulos 04 y 05, aprenderás cómo codificar tus mejores prácticas en instrucciones personalizadas y skills que Copilot CLI carga automáticamente. + +--- + +## ➡️ Qué sigue + +Los capítulos restantes cubren características adicionales que extienden las capacidades de Copilot CLI: + +| Capítulo | Qué cubre | Cuándo lo querrás | +|---------|----------------|---------------------| +| Cap 04: Agentes | Crear personas IA especializadas | Cuando quieras expertos de dominio (frontend, seguridad) | +| Cap 05: Skills | Cargar instrucciones automáticamente para tareas | Cuando repitas los mismos prompts a menudo | +| Cap 06: MCP | Conectar servicios externos | Cuando necesites datos en vivo de GitHub, bases de datos | + +**Recomendación**: Prueba los flujos de trabajo principales durante una semana, luego vuelve a los Capítulos 04-06 cuando tengas necesidades específicas. + +--- + +## Continúa con temas adicionales + +En el **[Capítulo 04: Agentes e instrucciones personalizadas](../04-agents-custom-instructions/README.md)** aprenderás: + +- Usar agentes integrados (`/plan`, `/review`) +- Crear agentes especializados (experto frontend, auditor de seguridad) con archivos `.agent.md` +- Patrones de colaboración multiagente +- Archivos de instrucciones personalizadas para estándares del proyecto + +--- + +**[← Volver al Capítulo 02](../02-context-conversations/README.md)** | **[Continuar al Capítulo 04 →](../04-agents-custom-instructions/README.md)** diff --git a/localization/es-es/04-agents-custom-instructions/README.md b/localization/es-es/04-agents-custom-instructions/README.md new file mode 100644 index 00000000..93080270 --- /dev/null +++ b/localization/es-es/04-agents-custom-instructions/README.md @@ -0,0 +1,783 @@ +![Capítulo 04: Agentes e instrucciones personalizadas](../../../04-agents-custom-instructions/images/chapter-header.png) + +> **¿Y si pudieras contratar a un revisor de código Python, a un experto en testing y a un revisor de seguridad… todos en una sola herramienta?** + +En el Capítulo 03 dominaste los flujos de trabajo esenciales: revisión de código, refactorización, depuración, generación de pruebas e integración con git. Eso te hace muy productivo con GitHub Copilot CLI. Ahora vamos a llevarlo más lejos. + +Hasta ahora has usado Copilot CLI como un asistente de propósito general. Los agentes te permiten asignarle una persona específica con estándares incorporados, como un revisor de código que aplica type hints y PEP 8, o un asistente de testing que escribe casos pytest. Verás cómo el mismo prompt obtiene resultados notablemente mejores cuando lo gestiona un agente con instrucciones dirigidas. + +## 🎯 Objetivos de aprendizaje + +Al final de este capítulo, serás capaz de: + +- Usar agentes integrados: Plan (`/plan`), Code-review (`/review`), y entender los agentes automáticos (Explore, Task) +- Crear agentes especializados usando archivos de agente (`.agent.md`) +- Usar agentes para tareas específicas de un dominio +- Cambiar entre agentes usando `/agent` y `--agent` +- Escribir archivos de instrucciones personalizadas para estándares específicos del proyecto + +> ⏱️ **Tiempo estimado**: ~55 minutos (20 min de lectura + 35 min práctica) + +--- + +## 🧩 Analogía del mundo real: contratar especialistas + +Cuando necesitas ayuda con tu casa, no llamas a un único "ayudante general". Llamas a especialistas: + +| Problema | Especialista | Por qué | +|---------|------------|-----| +| Tubería con fugas | Fontanero | Conoce las normativas de fontanería, dispone de herramientas especializadas | +| Reinstalación eléctrica | Electricista | Comprende los requisitos de seguridad, cumple la normativa | +| Tejado nuevo | Tejador | Conoce los materiales y el clima local | + +Los agentes funcionan igual. En lugar de una IA genérica, usa agentes que se centran en tareas concretas y conocen el proceso correcto a seguir. Configura las instrucciones una vez y reutilízalas siempre que necesites esa especialidad: revisión de código, testing, seguridad, documentación. + +Analogía de contratar especialistas - Igual que llamas a profesionales especializados para reparar tu casa, los agentes de IA están especializados en tareas concretas como revisión de código, testing, seguridad y documentación + +--- + +# Usar agentes + +Empieza ya con agentes integrados y personalizados. + +--- + +## *¿Nuevo en agentes?* ¡Empieza aquí! +¿Nunca has usado o creado un agente? Aquí tienes todo lo que necesitas saber para empezar este curso. + +1. **Prueba un agente *integrado* ahora mismo:** + ```bash + copilot + > /plan Add input validation for book year in the book app + ``` + Esto invoca al agente Plan para crear un plan de implementación paso a paso. + +2. **Mira uno de nuestros ejemplos de agente personalizado:** Es sencillo definir las instrucciones de un agente; revisa el archivo de ejemplo [python-reviewer.agent.md](../../../.github/agents/python-reviewer.agent.md) para ver el patrón. + +3. **Entiende el concepto clave:** Los agentes son como consultar a un especialista en lugar de a un generalista. Un "agente de frontend" se centrará automáticamente en accesibilidad y patrones de componentes; no tienes que recordárselo porque ya está especificado en las instrucciones del agente. + + +## Agentes integrados + +**¡Ya has usado algunos agentes integrados en el flujo de trabajo de desarrollo del Capítulo 03!** +
`/plan` y `/review` son en realidad agentes integrados. Ahora ya sabes lo que ocurre por debajo. Aquí tienes la lista completa: + +| Agente | Cómo invocarlo | Qué hace | +|-------|---------------|--------------| +| **Plan** | `/plan` o `Shift+Tab` (cambia entre modos) | Crea planes de implementación paso a paso antes de programar | +| **Code-review** | `/review` | Revisa los cambios en stage o sin stage con feedback enfocado y accionable | +| **Init** | `/init` | Genera archivos de configuración del proyecto (instrucciones, agentes) | +| **Explore** | *Automático* | Se usa internamente cuando le pides a Copilot que explore o analice el código | +| **Task** | *Automático* | Ejecuta comandos como pruebas, builds, lints e instalación de dependencias | + +
+ +**Agentes integrados en acción** - Ejemplos de invocación de Plan, Code-review, Explore y Task + +```bash +copilot + +# Invoke the Plan agent to create an implementation plan +> /plan Add input validation for book year in the book app + +# Invoke the Code-review agent on your changes +> /review + +# Explore and Task agents are invoked automatically when relevant: +> Run the test suite # Uses Task agent + +> Explore how book data is loaded # Uses Explore agent +``` + +¿Y el agente Task? Trabaja entre bastidores para gestionar y registrar lo que está pasando, y reportar de vuelta en un formato limpio y claro: + +| Resultado | Lo que ves | +|---------|--------------| +| ✅ **Éxito** | Resumen breve (por ejemplo, "All 247 tests passed", "Build succeeded") | +| ❌ **Fallo** | Salida completa con stack traces, errores del compilador y logs detallados | + + +> 📚 **Documentación oficial**: [Agentes de GitHub Copilot CLI](https://docs.github.com/copilot/how-tos/use-copilot-agents/use-copilot-cli#use-custom-agents) + +--- + +# Añadir agentes a Copilot CLI + +¡Puedes definir tus propios agentes para que formen parte de tu flujo de trabajo! Defínelos una vez y luego dirígelos. + +Cuatro robots de IA coloridos juntos, cada uno con herramientas distintas que representan capacidades de agentes especializados + +## 🗂️ Añade tus agentes + +Los archivos de agente son archivos Markdown con la extensión `.agent.md`. Tienen dos partes: el frontmatter YAML (metadatos) y las instrucciones en Markdown. + +> 💡 **¿Nuevo con el frontmatter YAML?** Es un pequeño bloque de configuración al principio del archivo, rodeado por marcadores `---`. YAML son simplemente pares `key: value`. El resto del archivo es Markdown normal. + +Aquí tienes un agente mínimo: + +```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 +``` + +> 💡 **Obligatorio vs opcional**: El campo `description` es obligatorio. Otros campos como `name`, `tools` y `model` son opcionales. + +## Dónde colocar los archivos de agente + +| Ubicación | Ámbito | Recomendado para | +|----------|-------|----------| +| `.github/agents/` | Específico del proyecto | Agentes compartidos por el equipo con las convenciones del proyecto | +| `~/.copilot/agents/` | Global (todos los proyectos) | Agentes personales que usas en todas partes | + +**Este proyecto incluye archivos de agente de ejemplo en la carpeta [.github/agents/](../../../.github/agents/)**. Puedes escribir los tuyos o personalizar los que ya se proporcionan. + +
+📂 Ver los agentes de ejemplo de este curso + +| Archivo | Descripción | +|------|-------------| +| `hello-world.agent.md` | Ejemplo mínimo: empieza por aquí | +| `python-reviewer.agent.md` | Revisor de calidad de código Python | +| `pytest-helper.agent.md` | Especialista en testing con pytest | + +```bash +# Or copy one to your personal agents folder (available in every project) +cp .github/agents/python-reviewer.agent.md ~/.copilot/agents/ +``` + +Para más agentes de la comunidad, consulta [github/awesome-copilot](https://github.com/github/awesome-copilot) + +
+ + +## 🚀 Dos formas de usar agentes personalizados + +### Modo interactivo +Dentro del modo interactivo, lista los agentes con `/agent` y selecciona el agente con el que quieras trabajar. +Selecciona un agente para continuar tu conversación con él. + +```bash +copilot +> /agent +``` + +Para cambiar a un agente diferente o volver al modo por defecto, vuelve a usar el comando `/agent`. + +### Modo programático + +Lanza directamente una nueva sesión con un agente. + +```bash +copilot --agent python-reviewer +> Review @samples/book-app-project/books.py +``` + +> 💡 **Cambiar de agente**: Puedes cambiar a un agente diferente en cualquier momento volviendo a usar `/agent` o `--agent`. Para volver a la experiencia estándar de Copilot CLI, usa `/agent` y selecciona **no agent**. + +--- + +# Profundizando en los agentes + +Robot siendo ensamblado en un banco de trabajo rodeado de componentes y herramientas que representan la creación de agentes personalizados + +> 💡 **Esta sección es opcional.** Los agentes integrados (`/plan`, `/review`) son lo bastante potentes para la mayoría de los flujos de trabajo. Crea agentes personalizados cuando necesites una experiencia especializada que se aplique de forma consistente a tu trabajo. + +Cada tema a continuación es independiente. **Elige lo que te interese: no necesitas leerlos todos a la vez.** + +| Quiero... | Ir a | +|---|---| +| Ver por qué los agentes superan a los prompts genéricos | [Especialista vs genérico](#specialist-vs-generic-see-the-difference) | +| Combinar agentes en una funcionalidad | [Trabajar con varios agentes](#working-with-multiple-agents) | +| Organizar, nombrar y compartir agentes | [Organizar y compartir agentes](#organizing--sharing-agents) | +| Configurar contexto de proyecto siempre activo | [Configurar tu proyecto para Copilot](#configuring-your-project-for-copilot) | +| Consultar propiedades YAML y herramientas | [Referencia del archivo de agente](#agent-file-reference) | + +Selecciona un escenario abajo para expandirlo. + +--- + + +
+Especialista vs genérico: nota la diferencia - Por qué los agentes producen mejores resultados que los prompts genéricos + +## Especialista vs genérico: nota la diferencia + +Aquí es donde los agentes demuestran su valor. Observa la diferencia: + +### Sin un agente (Copilot genérico) + +```bash +copilot + +> Add a function to search books by year range in the book app +``` + +**Salida genérica**: +```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 +``` + +Básico. Funciona. Pero le falta mucho. + +--- + +### Con el agente Python Reviewer + +```bash +copilot + +> /agent +# Select "python-reviewer" + +> Add a function to search books by year range in the book app +``` + +**Salida del especialista**: +```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 + ] +``` + +**Lo que el agente python-reviewer incluye automáticamente**: +- ✅ Type hints en todos los parámetros y valores de retorno +- ✅ Docstring completa con Args/Returns/Raises +- ✅ Validación de entrada con manejo de errores adecuado +- ✅ Comprensión de listas para mejor rendimiento +- ✅ Manejo de casos límite (valores de año ausentes o no válidos) +- ✅ Formato conforme a PEP 8 +- ✅ Prácticas de programación defensiva + +**La diferencia**: El mismo prompt, una salida muchísimo mejor. El agente aporta la experiencia que tú olvidarías pedir. + +
+ +--- + + +
+Trabajar con varios agentes - Combina especialistas, cambia a mitad de sesión, agentes como herramientas + +## Trabajar con varios agentes + +El verdadero poder llega cuando los especialistas trabajan juntos en una funcionalidad. + +### Ejemplo: construir una funcionalidad sencilla + +```bash +copilot + +> I want to add a "search by year range" feature to the book app + +# Use python-reviewer for design +> /agent +# Select "python-reviewer" + +> @samples/book-app-project/books.py Design a find_by_year_range method. What's the best approach? + +# Switch to pytest-helper for test design +> /agent +# Select "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? + +# Synthesize both designs +> Create an implementation plan that includes the method implementation and comprehensive tests. +``` + +**La idea clave**: tú eres el arquitecto que dirige a los especialistas. Ellos se encargan de los detalles, tú de la visión. + +
+🎬 ¡Mira la demo! + +![Demo del Python Reviewer](../../../04-agents-custom-instructions/images/python-reviewer-demo.gif) + +*La salida de la demo varía: tu modelo, herramientas y respuestas serán distintas a las que se muestran aquí.* + +
+ +### Agentes como herramientas + +Cuando hay agentes configurados, Copilot también puede llamarlos como herramientas durante tareas complejas. Si pides una funcionalidad full-stack, Copilot puede delegar automáticamente partes a los agentes especialistas adecuados. + +
+ +--- + + +
+Organizar y compartir agentes - Nombrado, ubicación de archivos, archivos de instrucciones y compartir con el equipo + +## Organizar y compartir agentes + +### Nombrar tus agentes + +Cuando creas archivos de agente, el nombre importa. Es lo que escribirás después de `/agent` o `--agent`, y lo que tus compañeros verán en la lista de agentes. + +| ✅ Buenos nombres | ❌ Evita | +|--------------|----------| +| `frontend` | `my-agent` | +| `backend-api` | `agent1` | +| `security-reviewer` | `helper` | +| `react-specialist` | `code` | +| `python-backend` | `assistant` | + +**Convenciones de nombrado:** +- Usa minúsculas con guiones: `my-agent-name.agent.md` +- Incluye el dominio: `frontend`, `backend`, `devops`, `security` +- Sé específico cuando sea necesario: `react-typescript` vs simplemente `frontend` + +--- + +### Compartir con tu equipo + +Coloca los archivos de agente en `.github/agents/` y quedarán bajo control de versiones. Súbelos a tu repositorio y cada miembro del equipo los obtiene automáticamente. Pero los agentes son solo un tipo de archivo que Copilot lee de tu proyecto. También admite **archivos de instrucciones** que se aplican automáticamente en cada sesión, sin que nadie tenga que ejecutar `/agent`. + +Piénsalo así: los agentes son especialistas a los que llamas, y los archivos de instrucciones son reglas del equipo que están siempre activas. + +### Dónde colocar tus archivos + +Ya conoces las dos ubicaciones principales (consulta [Dónde colocar los archivos de agente](#where-to-put-agent-files) más arriba). Usa este árbol de decisión para elegir: + +Árbol de decisión sobre dónde colocar los archivos de agente: experimentando → carpeta actual, uso por el equipo → .github/agents/, en todas partes → ~/.copilot/agents/ + +**Empieza simple:** Crea un único archivo `*.agent.md` en la carpeta de tu proyecto. Muévelo a una ubicación permanente cuando estés satisfecho con él. + +Más allá de los archivos de agente, Copilot también lee **archivos de instrucciones a nivel de proyecto** automáticamente, sin necesidad de `/agent`. Consulta [Configurar tu proyecto para Copilot](#configuring-your-project-for-copilot) más abajo para `AGENTS.md`, `.instructions.md` y `/init`. + +
+ +--- + + +
+Configurar tu proyecto para Copilot - AGENTS.md, archivos de instrucciones y configuración con /init + +## Configurar tu proyecto para Copilot + +Los agentes son especialistas que invocas a demanda. Los **archivos de configuración del proyecto** son distintos: Copilot los lee automáticamente en cada sesión para entender las convenciones, el stack tecnológico y las reglas de tu proyecto. Nadie tiene que ejecutar `/agent`; el contexto está siempre activo para todos los que trabajan en el repo. + +### Configuración rápida con /init + +La forma más rápida de empezar es dejar que Copilot genere los archivos de configuración por ti: + +```bash +copilot +> /init +``` + +Copilot escaneará tu proyecto y creará archivos de instrucciones a medida. Puedes editarlos después. + +### Formatos de archivo de instrucciones + +| Archivo | Ámbito | Notas | +|------|-------|-------| +| `AGENTS.md` | Raíz del proyecto o anidado | **Estándar multiplataforma** - funciona con Copilot y otros asistentes de IA | +| `.github/copilot-instructions.md` | Proyecto | Específico de GitHub Copilot | +| `.github/instructions/*.instructions.md` | Proyecto | Instrucciones granulares específicas por tema | +| `CLAUDE.md`, `GEMINI.md` | Raíz del proyecto | Soportados por compatibilidad | + +> 🎯 **¿Empezando ahora?** Usa `AGENTS.md` para las instrucciones del proyecto. Puedes explorar los demás formatos más adelante según los necesites. + +### AGENTS.md + +`AGENTS.md` es el formato recomendado. Es un [estándar abierto](https://agents.md/) que funciona con Copilot y otras herramientas de IA para programar. Colócalo en la raíz de tu repositorio y Copilot lo leerá automáticamente. El propio [AGENTS.md](../../../AGENTS.md) de este proyecto es un ejemplo funcional. + +Un `AGENTS.md` típico describe el contexto de tu proyecto, el estilo de código, los requisitos de seguridad y los estándares de testing. Escribe el tuyo siguiendo el patrón de nuestro archivo de ejemplo. + +### Archivos de instrucciones personalizadas (.instructions.md) + +Para equipos que quieren un control más granular, divide las instrucciones en archivos específicos por tema. Cada archivo cubre una preocupación y se aplica automáticamente: + +``` +.github/ +└── instructions/ + ├── python-standards.instructions.md + ├── security-checklist.instructions.md + └── api-design.instructions.md +``` + +> 💡 **Nota**: Los archivos de instrucciones funcionan con cualquier lenguaje. Este ejemplo usa Python para encajar con el proyecto del curso, pero puedes crear archivos similares para TypeScript, Go, Rust o cualquier tecnología que use tu equipo. + +**Encontrar archivos de instrucciones de la comunidad**: Explora [github/awesome-copilot](https://github.com/github/awesome-copilot) para encontrar archivos de instrucciones prefabricados que cubren .NET, Angular, Azure, Python, Docker y muchas otras tecnologías. + +### Desactivar las instrucciones personalizadas + +Si necesitas que Copilot ignore todas las configuraciones específicas del proyecto (útil para depurar o comparar comportamientos): + +```bash +copilot --no-custom-instructions +``` + +
+ +--- + + +
+Referencia del archivo de agente - Propiedades YAML, alias de herramientas y ejemplos completos + +## Referencia del archivo de agente + +### Un ejemplo más completo + +Has visto el [formato de agente mínimo](#-add-your-agents) más arriba. Aquí tienes un agente más completo que usa la propiedad `tools`. Crea `~/.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 +``` + +### Propiedades YAML + +| Propiedad | Obligatoria | Descripción | +|----------|----------|-------------| +| `name` | No | Nombre para mostrar (por defecto, el nombre del archivo) | +| `description` | **Sí** | Lo que hace el agente: ayuda a Copilot a entender cuándo sugerirlo | +| `tools` | No | Lista de herramientas permitidas (omitir = todas las herramientas disponibles). Consulta los alias de herramientas más abajo. | +| `target` | No | Limitar a `vscode` o `github-copilot` solamente | + +### Alias de herramientas + +Usa estos nombres en la lista `tools`: +- `read` - Leer el contenido de archivos +- `edit` - Editar archivos +- `search` - Buscar en archivos (grep/glob) +- `execute` - Ejecutar comandos de shell (también: `shell`, `Bash`) +- `agent` - Invocar otros agentes personalizados + +> 📖 **Documentación oficial**: [Configuración de agentes personalizados](https://docs.github.com/copilot/reference/custom-agents-configuration) +> +> ⚠️ **Solo en VS Code**: La propiedad `model` (para seleccionar modelos de IA) funciona en VS Code pero no es compatible con GitHub Copilot CLI. Puedes incluirla sin problema en archivos de agente multiplataforma. GitHub Copilot CLI la ignorará. + +### Más plantillas de agentes + +> 💡 **Nota para principiantes**: Los ejemplos de abajo son plantillas. **Reemplaza las tecnologías específicas por las que use tu proyecto.** Lo importante es la *estructura* del agente, no las tecnologías concretas mencionadas. + +Este proyecto incluye ejemplos funcionales en la carpeta [.github/agents/](../../../.github/agents/): +- [hello-world.agent.md](../../../.github/agents/hello-world.agent.md) - Ejemplo mínimo, empieza por aquí +- [python-reviewer.agent.md](../../../.github/agents/python-reviewer.agent.md) - Revisor de calidad de código Python +- [pytest-helper.agent.md](../../../.github/agents/pytest-helper.agent.md) - Especialista en testing con pytest + +Para agentes de la comunidad, consulta [github/awesome-copilot](https://github.com/github/awesome-copilot). + +
+ +--- + +# Práctica + +Escritorio acogedor con monitor mostrando código, lámpara, taza de café y auriculares listos para la práctica + +Crea tus propios agentes y míralos en acción. + +--- + +## ▶️ Inténtalo tú mismo + +```bash + +# Create the agents directory (if it doesn't exist) +mkdir -p .github/agents + +# Create a code reviewer agent +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 + +# Create a documentation agent +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 + +# Now use them +copilot --agent reviewer +> Review @samples/book-app-project/books.py + +# Or switch agents +copilot +> /agent +# Select "documentor" +> Document @samples/book-app-project/books.py +``` + +--- + +## 📝 Tarea + +### Reto principal: construye un equipo de agentes especializados + +El ejemplo práctico creó los agentes `reviewer` y `documentor`. Ahora practica creando y usando agentes para una tarea diferente: mejorar la validación de datos en la app de libros. + +1. Crea 3 archivos de agente (`.agent.md`) adaptados a la app de libros, uno por agente, colocados en `.github/agents/` +2. Tus agentes: + - **data-validator**: comprueba `data.json` en busca de datos faltantes o malformados (autores vacíos, year=0, campos faltantes) + - **error-handler**: revisa el código Python en busca de manejo de errores inconsistente y sugiere un enfoque unificado + - **doc-writer**: genera o actualiza docstrings y contenido del README +3. Usa cada agente en la app de libros: + - `data-validator` → audita `@samples/book-app-project/data.json` + - `error-handler` → revisa `@samples/book-app-project/books.py` y `@samples/book-app-project/utils.py` + - `doc-writer` → añade docstrings a `@samples/book-app-project/books.py` +4. Colabora: usa `error-handler` para identificar lagunas en el manejo de errores y luego `doc-writer` para documentar el enfoque mejorado + +**Criterio de éxito**: Tienes 3 agentes funcionales que producen una salida consistente y de alta calidad y puedes alternar entre ellos con `/agent`. + +
+💡 Pistas (haz clic para expandir) + +**Plantillas iniciales**: crea un archivo por agente en `.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 +``` + +**Probar tus agentes:** + +> 💡 **Nota:** Ya deberías tener `samples/book-app-project/data.json` en tu copia local de este repo. Si falta, descarga la versión original desde el repo origen: +> [data.json](https://github.com/github/copilot-cli-for-beginners/blob/main/samples/book-app-project/data.json) + +```bash +copilot +> /agent +# Select "data-validator" from the list +> @samples/book-app-project/data.json Check for books with empty author fields or invalid years +``` + +**Consejo:** El campo `description` en el frontmatter YAML es obligatorio para que los agentes funcionen. + +
+ +### Reto bonus: biblioteca de instrucciones + +Has construido agentes que invocas a demanda. Ahora prueba la otra cara: **archivos de instrucciones** que Copilot lee automáticamente en cada sesión, sin necesidad de `/agent`. + +Crea una carpeta `.github/instructions/` con al menos 3 archivos de instrucciones: +- `python-style.instructions.md` para aplicar PEP 8 y convenciones de type hints +- `test-standards.instructions.md` para aplicar las convenciones de pytest en archivos de test +- `data-quality.instructions.md` para validar entradas de datos JSON + +Prueba cada archivo de instrucciones con el código de la app de libros. + +--- + +
+🔧 Errores comunes y solución de problemas (haz clic para expandir) + +### Errores comunes + +| Error | Qué pasa | Solución | +|---------|--------------|-----| +| Falta `description` en el frontmatter del agente | El agente no se carga o no es detectable | Incluye siempre `description:` en el frontmatter YAML | +| Ubicación de archivo incorrecta para los agentes | Agente no encontrado al intentar usarlo | Colócalo en `~/.copilot/agents/` (personal) o `.github/agents/` (proyecto) | +| Usar `.md` en lugar de `.agent.md` | El archivo puede no reconocerse como agente | Nombra los archivos como `python-reviewer.agent.md` | +| Prompts de agente excesivamente largos | Puede alcanzar el límite de 30 000 caracteres | Mantén las definiciones de agente enfocadas; usa skills para instrucciones detalladas | + +### Solución de problemas + +**Agente no encontrado** - Comprueba que el archivo del agente exista en una de estas ubicaciones: +- `~/.copilot/agents/` +- `.github/agents/` + +Lista los agentes disponibles: + +```bash +copilot +> /agent +# Shows all available agents +``` + +**El agente no sigue las instrucciones** - Sé explícito en tus prompts y añade más detalle a las definiciones del agente: +- Frameworks/librerías concretas con versiones +- Convenciones del equipo +- Patrones de código de ejemplo + +**Las instrucciones personalizadas no se cargan** - Ejecuta `/init` en tu proyecto para configurar instrucciones específicas del proyecto: + +```bash +copilot +> /init +``` + +O comprueba si están desactivadas: +```bash +# Don't use --no-custom-instructions if you want them loaded +copilot # This loads custom instructions by default +``` + +
+ +--- + +# Resumen + +## 🔑 Conclusiones clave + +1. **Agentes integrados**: `/plan` y `/review` se invocan directamente; Explore y Task funcionan automáticamente +2. **Los agentes personalizados** son especialistas definidos en archivos `.agent.md` +3. **Los buenos agentes** tienen experiencia, estándares y formatos de salida claros +4. **La colaboración multiagente** resuelve problemas complejos combinando experiencia +5. **Los archivos de instrucciones** (`.instructions.md`) codifican estándares del equipo para aplicarse automáticamente +6. **La salida consistente** procede de instrucciones de agente bien definidas + +> 📋 **Referencia rápida**: Consulta la [referencia de comandos de GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para una lista completa de comandos y atajos. + +--- + +## ➡️ Qué sigue + +Los agentes cambian *cómo enfoca y ejecuta acciones dirigidas Copilot* en tu código. A continuación aprenderás sobre las **skills**, que cambian *qué pasos* sigue. ¿Te preguntas en qué se diferencian agentes y skills? El Capítulo 05 lo aborda directamente. + +En el **[Capítulo 05: Sistema de skills](../05-skills/README.md)**, aprenderás: + +- Cómo las skills se autodisparan a partir de tus prompts (sin necesidad de un slash command) +- Instalar skills de la comunidad +- Crear skills personalizadas con archivos SKILL.md +- La diferencia entre agentes, skills y MCP +- Cuándo usar cada uno + +--- + +**[← Volver al Capítulo 03](../03-development-workflows/README.md)** | **[Continuar al Capítulo 05 →](../05-skills/README.md)** diff --git a/localization/es-es/05-skills/README.md b/localization/es-es/05-skills/README.md new file mode 100644 index 00000000..f4a5404d --- /dev/null +++ b/localization/es-es/05-skills/README.md @@ -0,0 +1,886 @@ +![Capítulo 05: Sistema de Skills](../../../05-skills/images/chapter-header.png) + +> **¿Y si Copilot pudiera aplicar automáticamente las mejores prácticas de tu equipo sin que tengas que explicarlas cada vez?** + +En este capítulo aprenderás sobre las Agent Skills: carpetas de instrucciones que Copilot carga automáticamente cuando son relevantes para tu tarea. Mientras que los agentes cambian *cómo* piensa Copilot, las skills le enseñan *formas concretas de completar tareas*. Crearás una skill de auditoría de seguridad que Copilot aplicará siempre que preguntes sobre seguridad, construirás criterios de revisión estándar del equipo que aseguren una calidad de código consistente y aprenderás cómo funcionan las skills en Copilot CLI, VS Code y el agente en la nube de GitHub Copilot. + + +## 🎯 Objetivos de aprendizaje + +Al final de este capítulo, serás capaz de: + +- Entender cómo funcionan las Agent Skills y cuándo usarlas +- Crear skills personalizadas con archivos SKILL.md +- Usar skills de la comunidad desde repositorios compartidos +- Saber cuándo usar skills, agentes o MCP + +> ⏱️ **Tiempo estimado**: ~55 minutos (20 min de lectura + 35 min práctica) + +--- + +## 🧩 Analogía del mundo real: herramientas eléctricas + +Un taladro de propósito general es útil, pero los accesorios especializados lo hacen potente. +Herramientas eléctricas - Las skills amplían las capacidades de Copilot + + +Las skills funcionan igual. Igual que cambias las brocas del taladro para distintos trabajos, puedes añadir skills a Copilot para diferentes tareas: + +| Accesorio (Skill) | Propósito | +|------------|---------| +| `commit` | Generar mensajes de commit consistentes | +| `security-audit` | Comprobar vulnerabilidades OWASP | +| `generate-tests` | Crear pruebas pytest exhaustivas | +| `code-checklist` | Aplicar estándares de calidad de código del equipo | + + + +*Las skills son accesorios especializados que amplían lo que Copilot puede hacer* + +--- + +# Cómo funcionan las skills + +Iconos de skill estilo RPG brillantes conectados por estelas de luz sobre un fondo estelar que representan las skills de Copilot + +Aprende qué son las skills, por qué importan y en qué se diferencian de los agentes y MCP. + +--- + +## *¿Nuevo en skills?* ¡Empieza aquí! + +1. **Mira qué skills ya están disponibles:** + ```bash + copilot + > /skills list + ``` + Esto muestra todas las skills que Copilot puede encontrar, incluidas las **skills integradas** que vienen con la propia CLI, además de las skills de tu proyecto y de tus carpetas personales. + + > 💡 **Skills integradas**: Copilot CLI viene con skills preinstaladas listas para usar. Por ejemplo, la skill `customizing-copilot-cloud-agents-environment` proporciona una guía para personalizar el entorno del agente en la nube de Copilot. No necesitas crear ni instalar nada para usarlas. Ejecuta `/skills list` para ver lo que está disponible. + +2. **Mira un archivo de skill real:** Echa un vistazo a nuestro ejemplo [code-checklist SKILL.md](../../../.github/skills/code-checklist/SKILL.md) para ver el patrón. Es solo frontmatter YAML más instrucciones en Markdown. + +3. **Entiende el concepto clave:** Las skills son instrucciones específicas de tarea que Copilot carga *automáticamente* cuando tu prompt coincide con la descripción de la skill. No necesitas activarlas; basta con preguntar de forma natural. + + +## Entender las skills + +Las Agent Skills son carpetas que contienen instrucciones, scripts y recursos que Copilot **carga automáticamente cuando son relevantes** para tu tarea. Copilot lee tu prompt, comprueba si alguna skill coincide y aplica las instrucciones pertinentes automáticamente. + +```bash +copilot + +> Check books.py against our quality checklist +# Copilot detects this matches your "code-checklist" skill +# and automatically applies its Python quality checklist + +> Generate tests for the BookCollection class +# Copilot loads your "pytest-gen" skill +# and applies your preferred test structure + +> What are the code quality issues in this file? +# Copilot loads your "code-checklist" skill +# and checks against your team's standards +``` + +> 💡 **Idea clave**: Las skills se **disparan automáticamente** cuando tu prompt coincide con la descripción de la skill. Solo pregunta de forma natural y Copilot aplicará las skills relevantes en segundo plano. También puedes invocar skills directamente, como verás a continuación. + +> 🧰 **Plantillas listas para usar**: Echa un vistazo a la carpeta [.github/skills](../../../.github/skills/) para ver skills sencillas que puedes copiar, pegar y probar. + +### Invocación directa con slash command + +Aunque el autodisparo es la forma principal en que funcionan las skills, también puedes **invocar skills directamente** usando su nombre como un slash command: + +```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 +``` + +Esto te da control explícito cuando quieres asegurarte de que se use una skill concreta. + +#### Combinar varias skills en un mismo mensaje + +Puedes invocar **más de una skill en un solo mensaje**, y el slash command de la skill puede aparecer en cualquier parte de tu prompt, no solo al principio. Esto es práctico cuando quieres realizar dos comprobaciones distintas de una sola vez: + +```bash +> Check @samples/book-app-project/book_app.py with /code-checklist and also run /generate-tests for it + +> Review the auth module /security-audit then /code-checklist the result +``` + +Copilot aplicará cada skill nombrada en la misma respuesta, ahorrándote tener que enviar varios mensajes por separado. + +> 💡 **Consejo**: Coloca los slash commands de skill donde resulte más natural en tu frase. Puedes ponerlos al principio, en medio o al final de tu mensaje. + +> 📝 **Invocación de skills vs agentes**: No confundas la invocación de skills con la invocación de agentes: +> - **Skills**: `/skill-name `, por ejemplo, `/code-checklist Check this file` +> - **Agentes**: `/agent` (selecciona de la lista) o `copilot --agent ` (línea de comandos) +> +> Si tienes una skill y un agente con el mismo nombre (por ejemplo, "code-reviewer"), escribir `/code-reviewer` invoca la **skill**, no el agente. + +### ¿Cómo sé que se ha usado una skill? + +Puedes preguntárselo directamente a Copilot: + +```bash +> What skills did you use for that response? + +> What skills do you have available for security reviews? +``` + +### Skills vs agentes vs MCP + +Las skills son solo una pieza del modelo de extensibilidad de GitHub Copilot. Aquí tienes cómo se comparan con los agentes y los servidores MCP. + +> *No te preocupes por MCP todavía. Lo cubriremos en el [Capítulo 06](../06-mcp-servers/). Se incluye aquí para que veas cómo encajan las skills en el cuadro general.* + +Diagrama comparativo que muestra las diferencias entre Agentes, Skills y servidores MCP y cómo se combinan en tu flujo de trabajo + +| Característica | Qué hace | Cuándo usarla | +|---------|--------------|-------------| +| **Agentes** | Cambian cómo piensa la IA | Necesitas experiencia especializada en muchas tareas | +| **Skills** | Proporcionan instrucciones específicas de tarea | Tareas específicas y repetibles con pasos detallados | +| **MCP** | Conecta servicios externos | Necesitas datos en vivo desde APIs | + +Usa agentes para experiencia amplia, skills para instrucciones de tareas concretas, y MCP para datos externos. Un agente puede usar una o varias skills durante una conversación. Por ejemplo, cuando le pides a un agente que revise tu código, podría aplicar automáticamente tanto una skill `security-audit` como una skill `code-checklist`. + +> 📚 **Aprende más**: Consulta la documentación oficial [About Agent Skills](https://docs.github.com/copilot/concepts/agents/about-agent-skills) para la referencia completa sobre formatos de skills y mejores prácticas. + +--- + +## De los prompts manuales a la experiencia automática + +Antes de profundizar en cómo crear skills, veamos *por qué* merece la pena aprenderlas. Una vez que veas las ganancias en consistencia, el "cómo" tendrá más sentido. + +### Antes de las skills: revisiones inconsistentes + +En cada revisión de código, podrías olvidar algo: + +```bash +copilot + +> Review this code for issues +# Generic review - might miss your team's specific concerns +``` + +O escribes un prompt largo cada vez: + +```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... +``` + +Tiempo: **más de 30 segundos** para teclear. Consistencia: **depende de la memoria**. + +### Después de las skills: mejores prácticas automáticas + +Con una skill `code-checklist` instalada, basta con preguntar de forma natural: + +```bash +copilot + +> Check the book collection code for quality issues +``` + +**Lo que pasa entre bastidores**: +1. Copilot ve "code quality" e "issues" en tu prompt +2. Comprueba las descripciones de las skills, encuentra que tu skill `code-checklist` coincide +3. Carga automáticamente la checklist de calidad de tu equipo +4. Aplica todas las comprobaciones sin que tú las enumeres + +Cómo se autodisparan las skills - Flujo de 4 pasos que muestra cómo Copilot empareja automáticamente tu prompt con la skill adecuada + +*Solo pregunta de forma natural. Copilot empareja tu prompt con la skill adecuada y la aplica automáticamente.* + +**Salida**: +``` +## 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 +``` + +**La diferencia**: Los estándares de tu equipo se aplican automáticamente, cada vez, sin tener que escribirlos. + +--- + +
+🎬 ¡Mira la demo! + +![Demo de disparo de skill](../../../05-skills/images/skill-trigger-demo.gif) + +*La salida de la demo varía. Tu modelo, herramientas y respuestas serán distintas a las que se muestran aquí.* + +
+ +--- + +## Consistencia a escala: skill de revisión de PR del equipo + +Imagina que tu equipo tiene una checklist de PR de 10 puntos. Sin una skill, cada desarrollador debe recordar los 10 puntos, y siempre alguien olvida uno. Con una skill `pr-review`, todo el equipo recibe revisiones consistentes: + +```bash +copilot + +> Can you review this PR? +``` + +Copilot carga automáticamente la skill `pr-review` de tu equipo y comprueba los 10 puntos: + +``` +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 +``` + +**El poder**: Cada miembro del equipo aplica los mismos estándares automáticamente. Las nuevas incorporaciones no necesitan memorizar la checklist porque la skill se encarga. + +--- + +# Crear skills personalizadas + +Manos humanas y robóticas construyendo un muro de bloques tipo LEGO brillantes que representan la creación y gestión de skills + +Construye tus propias skills a partir de archivos SKILL.md. + +--- + +## Ubicaciones de las skills + +Las skills se almacenan en `.github/skills/` (específicas del proyecto) o `~/.copilot/skills/` (a nivel de usuario). + +### Cómo encuentra Copilot las skills + +Copilot escanea automáticamente estas ubicaciones en busca de skills: + +| Ubicación | Ámbito | +|----------|-------| +| `.github/skills/` | Específica del proyecto (compartida con el equipo vía git) | +| `~/.copilot/skills/` | Específica del usuario (tus skills personales) | + +### Estructura de una skill + +Cada skill vive en su propia carpeta con un archivo `SKILL.md`. Opcionalmente puedes incluir scripts, ejemplos u otros recursos: + +``` +.github/skills/ +└── my-skill/ + ├── SKILL.md # Required: Skill definition and instructions + ├── examples/ # Optional: Example files Copilot can reference + │ └── sample.py + └── scripts/ # Optional: Scripts the skill can use + └── validate.sh +``` + +> 💡 **Consejo**: El nombre del directorio debería coincidir con el `name` del frontmatter de tu SKILL.md (minúsculas con guiones). + +### Formato de SKILL.md + +Las skills usan un formato Markdown sencillo con frontmatter YAML: + +```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 +``` + +**Propiedades YAML:** + +| Propiedad | Obligatoria | Descripción | +|----------|----------|-------------| +| `name` | **Sí** | Identificador único (minúsculas, guiones para los espacios) | +| `description` | **Sí** | Lo que hace la skill y cuándo debería usarla Copilot | +| `license` | No | Licencia que se aplica a esta skill | + +> 📖 **Documentación oficial**: [About Agent Skills](https://docs.github.com/copilot/concepts/agents/about-agent-skills) + +### Crea tu primera skill + +Vamos a construir una skill de auditoría de seguridad que comprueba las vulnerabilidades del OWASP Top 10: + +```bash +# Create skill directory +mkdir -p .github/skills/security-audit + +# Create the SKILL.md file +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 + +# Test your skill (skills load automatically based on your prompt) +copilot + +> @samples/book-app-project/ Check this code for security vulnerabilities +# Copilot detects "security vulnerabilities" matches your skill +# and automatically applies its OWASP checklist +``` + +**Salida esperada** (tus resultados pueden variar): + +``` +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 +``` + +--- + +## Escribir buenas descripciones de skill + +¡El campo `description` en tu SKILL.md es crucial! Es como Copilot decide si cargar tu skill: + +```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 +--- +``` + +> 💡 **Consejo**: Incluye palabras clave que coincidan con cómo haces las preguntas de forma natural. Si dices "security review", incluye "security review" en la descripción. + +### Combinar skills con agentes + +Skills y agentes funcionan juntos. El agente aporta la experiencia, la skill aporta las instrucciones específicas: + +```bash +# Start with a code-reviewer agent +copilot --agent code-reviewer + +> Check the book app for quality issues +# code-reviewer agent's expertise combines +# with your code-checklist skill's checklist +``` + +--- + +# Gestionar y compartir skills + +Descubre las skills instaladas, encuentra skills de la comunidad y comparte las tuyas. + +Gestionar y compartir skills - mostrando el ciclo descubrir, usar, crear y compartir para skills de la CLI + +--- + +## Gestionar skills con el comando `/skills` + +Usa el comando `/skills` para gestionar tus skills instaladas: + +| Comando | Qué hace | +|---------|--------------| +| `/skills list` | Muestra todas las skills instaladas | +| `/skills info ` | Obtiene detalles sobre una skill concreta | +| `/skills add ` | Habilita una skill (desde un repositorio o marketplace) | +| `/skills remove ` | Desactiva o desinstala una skill | +| `/skills reload` | Recarga las skills tras editar archivos SKILL.md | + +> 💡 **Recuerda**: No necesitas "activar" las skills para cada prompt. Una vez instaladas, las skills se **disparan automáticamente** cuando tu prompt coincide con su descripción. Estos comandos sirven para gestionar qué skills están disponibles, no para usarlas. + +### Ejemplo: ver tus skills + +```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 +``` + +--- + +
+¡Mira la demo! + +![Demo de listar skills](../../../05-skills/images/list-skills-demo.gif) + +*La salida de la demo varía. Tu modelo, herramientas y respuestas serán distintas a las que se muestran aquí.* + +
+ +--- + +### Cuándo usar `/skills reload` + +Después de crear o editar el archivo SKILL.md de una skill, ejecuta `/skills reload` para incorporar los cambios sin reiniciar Copilot: + +```bash +# Edit your skill file +# Then in Copilot: +> /skills reload +Skills reloaded successfully. +``` + +> 💡 **Bueno saberlo**: Las skills siguen siendo efectivas incluso después de usar `/compact` para resumir tu historial de conversación. No es necesario recargar tras compactar. + +--- + +## Encontrar y usar skills de la comunidad + +### Usar plugins para instalar skills + +> 💡 **¿Qué son los plugins?** Los plugins son paquetes instalables que pueden agrupar skills, agentes y configuraciones de servidores MCP. Piénsalos como extensiones de "tienda de aplicaciones" para Copilot CLI. + +El comando `/plugin` te permite explorar e instalar estos paquetes: + +```bash +copilot + +> /plugin list +# Shows installed plugins + +> /plugin marketplace +# Browse available plugins + +> /plugin install +# Install a plugin from the marketplace +``` + +Para mantener al día tu catálogo local de plugins, actualízalo con: + +```bash +copilot plugin marketplace update +``` + +Los plugins pueden agrupar varias capacidades. Un único plugin puede incluir skills relacionadas, agentes y configuraciones de servidores MCP que funcionen juntos. + +### Repositorios de skills de la comunidad + +También hay skills prefabricadas disponibles en repositorios de la comunidad: + +- **[Awesome Copilot](https://github.com/github/awesome-copilot)** - Recursos oficiales de GitHub Copilot incluyendo documentación y ejemplos de skills + +### Instalar una skill de la comunidad con GitHub CLI + +La forma más sencilla de instalar una skill desde un repositorio de GitHub es usar el comando `gh skill install` (requiere [GitHub CLI v2.90.0+](https://github.blog/changelog/2026-04-16-manage-agent-skills-with-github-cli/)): + +```bash +# Browse and interactively select a skill from awesome-copilot +gh skill install github/awesome-copilot + +# Or install a specific skill directly +gh skill install github/awesome-copilot code-checklist + +# Install for personal use across all projects (user scope) +gh skill install github/awesome-copilot code-checklist --scope user +``` + +> ⚠️ **Revisa antes de instalar**: Lee siempre el `SKILL.md` de una skill antes de instalarla. Las skills controlan lo que hace Copilot, y una skill maliciosa podría indicarle que ejecute comandos dañinos o que modifique código de formas inesperadas. + +--- + +# Práctica + +Escritorio acogedor con monitor mostrando código, lámpara, taza de café y auriculares listos para la práctica + +Aplica lo que has aprendido construyendo y probando tus propias skills. + +--- + +## ▶️ Inténtalo tú mismo + +### Construye más skills + +Aquí tienes dos skills más que muestran patrones diferentes. Sigue el mismo flujo `mkdir` + `cat` de "Crea tu primera skill" más arriba o copia y pega las skills en la ubicación correcta. Hay más ejemplos disponibles en [.github/skills](../../../.github/skills). + +### Skill de generación de tests pytest + +Una skill que asegura una estructura pytest consistente en todo tu codebase: + +```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 +``` + +### Skill de revisión de PR del equipo + +Una skill que aplica estándares de revisión de PR consistentes en tu equipo: + +```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 +``` + +### Ve más allá + +1. **Reto de creación de skill**: Crea una skill `quick-review` que haga una checklist de 3 puntos: + - Cláusulas bare except + - Type hints faltantes + - Nombres de variables poco claros + + Pruébala preguntando: "Do a quick review of books.py" + +2. **Comparativa de skill**: Cronométrate escribiendo manualmente un prompt detallado de revisión de seguridad. Después, simplemente pregunta "Check for security issues in this file" y deja que tu skill `security-audit` se cargue automáticamente. ¿Cuánto tiempo te ha ahorrado la skill? + +3. **Reto de skill de equipo**: Piensa en la checklist de revisión de código de tu equipo. ¿Podrías codificarla como una skill? Anota 3 cosas que la skill debería comprobar siempre. + +**Autocomprobación**: Entiendes las skills cuando puedes explicar por qué importa el campo `description` (es como Copilot decide si cargar tu skill). + +--- + +## 📝 Tarea + +### Reto principal: construir una skill de resumen de libros + +Los ejemplos anteriores crearon las skills `pytest-gen` y `pr-review`. Ahora practica creando un tipo de skill completamente diferente: una para generar salida con formato a partir de datos. + +1. Lista tus skills actuales: ejecuta Copilot y pásale `/skills list`. También puedes usar `ls .github/skills/` para ver las skills del proyecto o `ls ~/.copilot/skills/` para las personales. +2. Crea una skill `book-summary` en `.github/skills/book-summary/SKILL.md` que genere un resumen Markdown formateado de la colección de libros +3. Tu skill debería tener: + - Un nombre y descripción claros (¡la descripción es crucial para el matching!) + - Reglas de formato concretas (por ejemplo, una tabla Markdown con título, autor, año, estado de lectura) + - Convenciones de salida (por ejemplo, usar ✅/❌ para el estado de lectura, ordenar por año) +4. Prueba la skill: `@samples/book-app-project/data.json Summarize the books in this collection` +5. Verifica que la skill se autodispara comprobando `/skills list` +6. Prueba a invocarla directamente con `/book-summary Summarize the books in this collection` + +**Criterio de éxito**: Tienes una skill `book-summary` funcional que Copilot aplica automáticamente cuando preguntas sobre la colección de libros. + +
+💡 Pistas (haz clic para expandir) + +**Plantilla inicial**: Crea `.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)** +``` + +**Pruébalo:** +```bash +copilot +> @samples/book-app-project/data.json Summarize the books in this collection +# The skill should auto-trigger based on the description match +``` + +**Si no se dispara:** Prueba `/skills reload` y vuelve a preguntar. + +
+ +### Reto bonus: skill de mensaje de commit + +1. Crea una skill `commit-message` que genere mensajes de commit convencionales con un formato consistente +2. Pruébala dejando un cambio en stage y preguntando: "Generate a commit message for my staged changes" +3. Documenta tu skill y compártela en GitHub con el topic `copilot-skill` + +--- + +
+🔧 Errores comunes y solución de problemas (haz clic para expandir) + +### Errores comunes + +| Error | Qué pasa | Solución | +|---------|--------------|-----| +| Nombrar el archivo de otra forma que no sea `SKILL.md` | La skill no se reconocerá | El archivo debe llamarse exactamente `SKILL.md` | +| Campo `description` vago | La skill nunca se cargará automáticamente | La descripción es el mecanismo PRIMARIO de descubrimiento. Usa palabras clave concretas | +| Falta `name` o `description` en el frontmatter | La skill no carga | Añade ambos campos en el frontmatter YAML | +| Ubicación de carpeta incorrecta | Skill no encontrada | Usa `.github/skills/skill-name/` (proyecto) o `~/.copilot/skills/skill-name/` (personal) | + +### Solución de problemas + +**La skill no se utiliza** - Si Copilot no usa tu skill cuando lo esperas: + +1. **Comprueba la descripción**: ¿Coincide con cómo lo estás preguntando? + ```markdown + # Bad: Too vague + description: Reviews code + + # Good: Includes trigger words + description: Use for code reviews, checking code quality, + finding bugs, security issues, and best practice violations + ``` + +2. **Verifica la ubicación del archivo**: + ```bash + # Project skills + ls .github/skills/ + + # User skills + ls ~/.copilot/skills/ + ``` + +3. **Comprueba el formato de SKILL.md**: El frontmatter es obligatorio: + ```markdown + --- + name: skill-name + description: What the skill does and when to use it + --- + + # Instructions here + ``` + +**La skill no aparece** - Verifica la estructura de carpetas: +``` +.github/skills/ +└── my-skill/ # Folder name + └── SKILL.md # Must be exactly SKILL.md (case-sensitive) +``` + +Ejecuta `/skills reload` después de crear o editar skills para asegurarte de que los cambios se incorporan. + +**Probar si una skill se carga** - Pregúntale directamente a Copilot: +```bash +> What skills do you have available for checking code quality? +# Copilot will describe relevant skills it found +``` + +**¿Cómo sé que mi skill realmente está funcionando?** + +1. **Comprueba el formato de salida**: Si tu skill especifica un formato de salida (como las etiquetas `[CRITICAL]`), búscalo en la respuesta +2. **Pregunta directamente**: Tras recibir una respuesta, pregunta "Did you use any skills for that?" +3. **Compara con/sin**: Prueba el mismo prompt con `--no-custom-instructions` para ver la diferencia: + ```bash + # With skills + copilot --allow-all -p "Review @file.py for security issues" + + # Without skills (baseline comparison) + copilot --allow-all -p "Review @file.py for security issues" --no-custom-instructions + ``` +4. **Busca comprobaciones específicas**: Si tu skill incluye comprobaciones específicas (como "functions over 50 lines"), comprueba si aparecen en la salida + +
+ +--- + +# Resumen + +## 🔑 Conclusiones clave + +1. **Las skills son automáticas**: Copilot las carga cuando tu prompt coincide con la descripción de la skill +2. **Invocación directa**: También puedes invocar skills directamente con `/skill-name` como un slash command +3. **Formato SKILL.md**: Frontmatter YAML (name, description, license opcional) más instrucciones en Markdown +4. **La ubicación importa**: `.github/skills/` para compartir en proyecto/equipo, `~/.copilot/skills/` para uso personal +5. **La descripción es clave**: Escribe descripciones que coincidan con cómo preguntas de forma natural + +> 📋 **Referencia rápida**: Consulta la [referencia de comandos de GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para una lista completa de comandos y atajos. + +--- + +## ➡️ Qué sigue + +Las skills amplían lo que Copilot puede hacer con instrucciones cargadas automáticamente. Pero, ¿qué pasa con conectarse a servicios externos? Ahí es donde entra MCP. + +En el **[Capítulo 06: Servidores MCP](../06-mcp-servers/README.md)**, aprenderás: + +- Qué es MCP (Model Context Protocol) +- Conectar a GitHub, sistema de archivos y servicios de documentación +- Configurar servidores MCP +- Flujos de trabajo con varios servidores + +--- + +**[← Volver al Capítulo 04](../04-agents-custom-instructions/README.md)** | **[Continuar al Capítulo 06 →](../06-mcp-servers/README.md)** diff --git a/localization/es-es/06-mcp-servers/README.md b/localization/es-es/06-mcp-servers/README.md new file mode 100644 index 00000000..6a4a5d85 --- /dev/null +++ b/localization/es-es/06-mcp-servers/README.md @@ -0,0 +1,974 @@ +![Capítulo 06: Servidores MCP](../../../06-mcp-servers/images/chapter-header.png) + +> **¿Y si Copilot pudiera leer tus issues de GitHub, consultar tu base de datos y crear PRs... todo desde la terminal?** + +Hasta ahora, Copilot solo puede trabajar con lo que le proporcionas directamente: archivos a los que haces referencia con `@`, el historial de conversación y sus propios datos de entrenamiento. Pero ¿y si pudiera consultar por sí mismo tu repositorio de GitHub, explorar los archivos de tu proyecto o buscar la documentación más reciente de una librería? + +Eso es lo que hace MCP (Model Context Protocol). Es una manera de conectar Copilot con servicios externos para que tenga acceso a datos reales y en vivo. A cada servicio al que Copilot se conecta se le llama "servidor MCP". En este capítulo configurarás algunas de estas conexiones y verás cómo hacen que Copilot sea muchísimo más útil. + +> 💡 **¿Ya conoces MCP?** [Salta al inicio rápido](#-use-the-built-in-github-mcp) para confirmar que funciona y empezar a configurar servidores. + +## 🎯 Objetivos de aprendizaje + +Al finalizar este capítulo, serás capaz de: + +- Entender qué es MCP y por qué importa +- Gestionar servidores MCP con los comandos `/mcp` +- Configurar servidores MCP para GitHub, sistema de archivos y documentación +- Usar flujos de trabajo potenciados por MCP con el proyecto book app +- Saber cuándo y cómo construir un servidor MCP personalizado (opcional) + +> ⏱️ **Tiempo estimado**: ~50 minutos (15 min de lectura + 35 min práctica) + +--- + +## 🧩 Analogía del mundo real: extensiones del navegador + +Los servidores MCP son como las extensiones del navegador + +Piensa en los servidores MCP como en las extensiones del navegador. Tu navegador, por sí solo, puede mostrar páginas web, pero las extensiones lo conectan con servicios adicionales: + +| Extensión del navegador | Con qué se conecta | Equivalente en MCP | +|-------------------|---------------------|----------------| +| Gestor de contraseñas | Tu bóveda de contraseñas | **GitHub MCP** → tus repos, issues, PRs | +| Grammarly | Servicio de análisis de escritura | **Context7 MCP** → documentación de librerías | +| Gestor de archivos | Almacenamiento en la nube | **Filesystem MCP** → archivos locales del proyecto | + +Sin extensiones, el navegador sigue siendo útil, pero con ellas se convierte en una herramienta muy potente. Los servidores MCP hacen lo mismo con Copilot. Lo conectan a fuentes de datos reales y en vivo para que pueda leer tus issues de GitHub, explorar tu sistema de archivos, traer documentación actualizada y mucho más. + +***Los servidores MCP conectan Copilot con el mundo exterior: GitHub, repositorios, documentación y más*** + +> 💡 **Idea clave**: Sin MCP, Copilot solo puede ver los archivos que compartes explícitamente con `@`. Con MCP, puede explorar tu proyecto de forma proactiva, consultar tu repositorio de GitHub y buscar documentación, todo de forma automática. + +--- + +Cable de alimentación conectándose con una chispa eléctrica brillante rodeado de iconos tecnológicos flotantes que representan las conexiones de los servidores MCP + +# Inicio rápido: MCP en 30 segundos + +## Empieza con el servidor MCP de GitHub integrado +Veamos MCP en acción ahora mismo, antes de configurar nada. +El servidor MCP de GitHub viene incluido por defecto. Prueba esto: + +```bash +copilot +> List the recent commits in this repository +``` + +Si Copilot devuelve datos reales de commits, acabas de ver MCP en acción. Eso es el servidor MCP de GitHub conectándose con GitHub en tu nombre. Pero GitHub es solo *un* servidor. Este capítulo te muestra cómo añadir más (acceso al sistema de archivos, documentación actualizada y otros) para que Copilot pueda hacer todavía más. + +--- + +## El comando `/mcp show` + +Usa `/mcp show` para ver qué servidores MCP están configurados y si están habilitados: + +```bash +copilot + +> /mcp show + +MCP Servers: +✓ github (enabled) - GitHub integration +✓ filesystem (enabled) - File system access +``` + +> 💡 **¿Solo ves el servidor de GitHub?** ¡Es lo esperado! Si todavía no has añadido ningún servidor MCP adicional, GitHub es el único que aparece. Añadirás más en la siguiente sección. + +> 📚 **¿Quieres ver todos los comandos de gestión de MCP?** Puedes gestionar los servidores con los comandos slash `/mcp` dentro del chat, o con `copilot mcp` directamente desde tu terminal. Consulta la [referencia completa de comandos](#-additional-mcp-commands) al final de este capítulo. + +
+🎬 ¡Míralo en acción! + +![Demo de estado de MCP](../../../06-mcp-servers/images/mcp-status-demo.gif) + +*La salida de la demo varía. Tu modelo, tus herramientas y las respuestas serán distintos a lo que se muestra aquí.* + +
+ +--- + +## ¿Qué cambia con MCP? + +Esta es la diferencia que MCP marca en la práctica: + +**Sin 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." +``` + +**Con 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 hace que Copilot sea consciente de tu entorno de desarrollo real. + +> 📚 **Documentación oficial**: [Sobre MCP](https://docs.github.com/copilot/concepts/context/mcp) para profundizar en cómo funciona MCP con GitHub Copilot. + +--- + +# Configurar servidores MCP + +Manos ajustando perillas y deslizadores en una mesa profesional de mezcla de audio que representa la configuración de servidores MCP + +Ahora que has visto MCP en acción, vamos a configurar servidores adicionales. Puedes añadir servidores de dos maneras: **desde el registro integrado** (lo más fácil — configuración guiada directamente en la CLI) o **editando manualmente el archivo de configuración** (más flexible). Empieza por la opción del registro si no estás seguro de cuál elegir. + +--- + +## Instalar servidores MCP desde el registro + +La CLI tiene un registro integrado de servidores MCP que te permite descubrir e instalar los más populares con una configuración guiada — sin necesidad de editar JSON. + +```bash +copilot + +> /mcp search +``` + +Copilot abre un selector interactivo que muestra los servidores disponibles. Elige uno y la CLI te guiará por la configuración necesaria (claves de API, rutas, etc.) y lo añadirá a tu configuración automáticamente. + +> 💡 **¿Por qué usar el registro?** Es la forma más fácil de empezar — no necesitas conocer el nombre del paquete npm, los argumentos del comando ni la estructura JSON. La CLI se encarga de todo eso por ti. + +--- + +## Archivo de configuración de MCP + +Los servidores MCP se configuran en `~/.copilot/mcp-config.json` (a nivel de usuario, aplica a todos los proyectos) o `.mcp.json` (a nivel de proyecto, situado en la raíz de tu proyecto). Si has usado `/mcp search` arriba, la CLI ya ha creado o actualizado este archivo por ti, pero es útil entender el formato para poder personalizarlo. + +> ⚠️ **Nota**: `.vscode/mcp.json` ya no se admite como fuente de configuración MCP. Si tienes un `.vscode/mcp.json` existente, migra su contenido a `.mcp.json` en la raíz de tu proyecto. La CLI mostrará una sugerencia de migración si detecta un archivo de configuración antiguo. + +```json +{ + "mcpServers": { + "server-name": { + "type": "local", + "command": "npx", + "args": ["@package/server-name"], + "tools": ["*"] + } + } +} +``` + +*La mayoría de servidores MCP se distribuyen como paquetes de npm y se ejecutan con el comando `npx`.* + +
+💡 ¿Eres nuevo en JSON? Haz clic aquí para ver qué significa cada campo + +| Campo | Qué significa | +|-------|---------------| +| `"mcpServers"` | Contenedor de todas tus configuraciones de servidores MCP | +| `"server-name"` | Un nombre que tú eliges (p. ej., "github", "filesystem") | +| `"type": "local"` | El servidor se ejecuta en tu máquina | +| `"command": "npx"` | El programa a ejecutar (npx ejecuta paquetes de npm) | +| `"args": [...]` | Argumentos pasados al comando | +| `"tools": ["*"]` | Permite todas las herramientas de este servidor | + +**Reglas importantes de JSON:** +- Usa comillas dobles `"` para las cadenas (no comillas simples) +- Sin comas finales tras el último elemento +- El archivo debe ser JSON válido (usa un [validador de JSON](https://jsonlint.com/) si tienes dudas) + +
+ +--- + +## Añadir servidores MCP + +El servidor MCP de GitHub viene integrado y no requiere configuración. A continuación tienes servidores adicionales que puedes añadir. **Elige el que te interese o ve recorriéndolos en orden.** + +| Quiero... | Ir a | +|---|---| +| Dejar que Copilot navegue por los archivos de mi proyecto | [Servidor Filesystem](#filesystem-server) | +| Obtener documentación de librerías actualizada | [Servidor Context7](#context7-server-documentation) | +| Explorar extras opcionales (servidores personalizados, web_fetch) | [Más allá de lo básico](#beyond-the-basics) | + +
+Servidor Filesystem - Deja que Copilot explore los archivos de tu proyecto + + +### Servidor Filesystem + +```json +{ + "mcpServers": { + "filesystem": { + "type": "local", + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], + "tools": ["*"] + } + } +} +``` + +> 💡 **La ruta `.`**: El `.` significa "directorio actual". Copilot puede acceder a archivos relativos al lugar donde lo has lanzado. En un Codespace, esto es la raíz de tu workspace. También puedes usar una ruta absoluta como `/workspaces/copilot-cli-for-beginners` si lo prefieres. + +Añade esto a tu `~/.copilot/mcp-config.json` y reinicia Copilot. + +
+ +
+Servidor Context7 - Obtén documentación actualizada de librerías + + +### Servidor Context7 (documentación) + +Context7 da a Copilot acceso a documentación actualizada de frameworks y librerías populares. En lugar de depender de datos de entrenamiento que pueden estar obsoletos, Copilot trae la documentación actual real. + +```json +{ + "mcpServers": { + "context7": { + "type": "local", + "command": "npx", + "args": ["-y", "@upstash/context7-mcp"], + "tools": ["*"] + } + } +} +``` + +- ✅ **No requiere clave de API** +- ✅ **No necesita cuenta** +- ✅ **Tu código se queda en local** + +Añade esto a tu `~/.copilot/mcp-config.json` y reinicia Copilot. + +
+ +
+Más allá de lo básico - Servidores personalizados y acceso web (opcional) + + +Estos son extras opcionales para cuando ya te sientas cómodo con los servidores básicos anteriores. + +### Servidor MCP de Microsoft Learn + +Cada servidor MCP que has visto hasta ahora (filesystem, Context7) se ejecuta localmente en tu máquina. Pero los servidores MCP también pueden ejecutarse de forma remota, lo que significa que tú simplemente apuntas Copilot CLI a una URL y él se encarga del resto. Sin `npx` ni `python`, sin proceso local, sin dependencias que instalar. + +El [servidor MCP de Microsoft Learn](https://github.com/microsoftdocs/mcp) es un buen ejemplo. Da a Copilot CLI acceso directo a la documentación oficial de Microsoft (Azure, Microsoft Foundry y otros temas de IA, .NET, Microsoft 365 y mucho más) para que pueda buscar en la documentación, traer páginas completas y encontrar ejemplos de código oficiales en lugar de depender de los datos de entrenamiento de un modelo. + +- ✅ **No requiere clave de API** +- ✅ **No necesita cuenta** +- ✅ **No requiere instalación local** + +**Instalación rápida con `/plugin install`:** + +En lugar de editar manualmente tu archivo de configuración JSON, puedes instalarlo con un solo comando: + +```bash +copilot + +> /plugin install microsoftdocs/mcp +``` + +Esto añade el servidor y sus skills de agente asociados automáticamente. Los skills instalados incluyen: + +- **microsoft-docs**: Conceptos, tutoriales y consultas de información +- **microsoft-code-reference**: Consultas de API, ejemplos de código y solución de problemas +- **microsoft-skill-creator**: Un meta-skill para generar skills personalizados sobre tecnologías de Microsoft + +**Uso:** +```bash +copilot + +> What's the recommended way to deploy a Python app to Azure App Service? Search Microsoft Learn. +``` + +📚 Más información: [Información general del servidor MCP de Microsoft Learn](https://learn.microsoft.com/training/support/mcp-get-started) + +### Acceso web con `web_fetch` + +Copilot CLI incluye una herramienta integrada `web_fetch` que puede traer contenido de cualquier URL. Es útil para obtener READMEs, documentación de APIs o notas de versión sin salir de tu terminal. No hace falta ningún servidor MCP. + +Puedes controlar a qué URLs se puede acceder mediante `~/.copilot/config.json` (ajustes generales de Copilot), que es distinto a `~/.copilot/mcp-config.json` (definiciones de servidores MCP). + +```json +{ + "permissions": { + "allowedUrls": [ + "https://api.github.com/**", + "https://docs.github.com/**", + "https://*.npmjs.org/**" + ], + "blockedUrls": [ + "http://**" + ] + } +} +``` + +**Uso:** +```bash +copilot + +> Fetch and summarize the README from https://github.com/facebook/react +``` + +### Construir un servidor MCP personalizado + +¿Quieres conectar Copilot con tus propias APIs, bases de datos o herramientas internas? Puedes construir un servidor MCP personalizado en Python. Esto es totalmente opcional, ya que los servidores preconstruidos (GitHub, filesystem, Context7) cubren la mayoría de casos de uso. + +📖 Consulta la [Guía del servidor MCP personalizado](mcp-custom-server.md) para ver un recorrido completo usando el book app como ejemplo. + +📚 Para más contexto, consulta el [curso MCP for Beginners](https://github.com/microsoft/mcp-for-beginners). + +
+ + + +### Archivo de configuración completo + +Aquí tienes un `mcp-config.json` completo con los servidores filesystem y Context7: + +> 💡 **Nota:** El MCP de GitHub viene integrado. No necesitas añadirlo a tu archivo de configuración. + +```json +{ + "mcpServers": { + "filesystem": { + "type": "local", + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], + "tools": ["*"] + }, + "context7": { + "type": "local", + "command": "npx", + "args": ["-y", "@upstash/context7-mcp"], + "tools": ["*"] + } + } +} +``` + +Guárdalo como `~/.copilot/mcp-config.json` para acceso global o como `.mcp.json` en la raíz del proyecto para una configuración específica de proyecto. + +--- + +# Usar servidores MCP + +Ahora que tienes servidores MCP configurados, veamos lo que pueden hacer. + +Uso de servidores MCP - Diagrama radial que muestra una CLI de desarrollador conectada a los servidores GitHub, Filesystem, Context7 y Personalizado/Web Fetch + +--- + +## Ejemplos de uso de servidores + +**Elige un servidor a explorar o ve recorriéndolos en orden.** + +| Quiero probar... | Ir a | +|---|---| +| Repos, issues y PRs de GitHub | [Servidor GitHub](#github-server-built-in) | +| Navegar por archivos del proyecto | [Uso del servidor Filesystem](#filesystem-server-usage) | +| Búsqueda de documentación de librerías | [Uso del servidor Context7](#context7-server-usage) | +| Servidor personalizado, MCP de Microsoft Learn y uso de web_fetch | [Uso de Más allá de lo básico](#beyond-the-basics-usage) | + +
+Servidor GitHub (integrado) - Accede a repos, issues, PRs y más + + +### Servidor GitHub (integrado) + +El servidor MCP de GitHub viene **integrado**. Si has iniciado sesión en Copilot (lo hiciste durante la configuración inicial), ya funciona. ¡No hace falta configuración! + +> 💡 **¿No funciona?** Ejecuta `/login` para reautenticarte con GitHub. + +
+Autenticación en dev containers + +- **GitHub Codespaces** (recomendado): La autenticación es automática. La CLI `gh` hereda el token de tu Codespace. No hay que hacer nada. +- **Dev container local (Docker)**: Ejecuta `gh auth login` después de que arranque el contenedor y reinicia Copilot. + +**Solución de problemas de autenticación:** +```bash +# Check if you're authenticated +gh auth status + +# If not, log in +gh auth login + +# Verify GitHub MCP is connected +copilot +> /mcp show +``` + +
+ +| Característica | Ejemplo | +|---------|----------| +| **Información del repositorio** | Ver commits, ramas, contribuidores | +| **Issues** | Listar, crear, buscar y comentar issues | +| **Pull requests** | Ver PRs, diffs, crear PRs, comprobar estado | +| **Búsqueda de código** | Buscar código entre repositorios | +| **Actions** | Consultar ejecuciones y estado de workflows | + +```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 +``` + +> 💡 **¿Trabajas en tu propio fork?** Si has hecho fork de este repositorio del curso, también puedes probar operaciones de escritura como crear issues y pull requests. Lo practicaremos en los ejercicios de abajo. + +> ⚠️ **¿No ves resultados?** El MCP de GitHub opera sobre el remoto del repositorio (en github.com), no solo sobre archivos locales. Asegúrate de que tu repo tiene un remoto: ejecuta `git remote -v` para comprobarlo. + +
+ +
+Servidor Filesystem - Navega y analiza archivos del proyecto + + +### Servidor Filesystem + +Una vez configurado, el MCP de filesystem proporciona herramientas que Copilot puede usar automáticamente: + +```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() +``` + +
+ +
+Servidor Context7 - Consulta documentación de librerías + + +### Servidor 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 +``` + +
+ +
+Más allá de lo básico - Uso del servidor personalizado y de web_fetch + + +### Más allá de lo básico + +**Servidor MCP personalizado**: Si has construido el servidor book-lookup de la [Guía del servidor MCP personalizado](mcp-custom-server.md), puedes consultar tu colección de libros directamente: + +```bash +copilot + +> Look up information about "1984" using the book lookup server. Search for books by George Orwell +``` + +**MCP de Microsoft Learn**: Si has instalado el [servidor MCP de Microsoft Learn](#microsoft-learn-mcp-server), puedes consultar la documentación oficial de Microsoft directamente: + +```bash +copilot + +> How do I configure managed identity for an Azure Function? Search Microsoft Learn. +``` + +**Web Fetch**: Usa la herramienta integrada `web_fetch` para traer contenido de cualquier URL: + +```bash +copilot + +> Fetch and summarize the README from https://github.com/facebook/react +``` + +
+ +--- + +## Flujos de trabajo multiservidor + +Estos flujos de trabajo muestran por qué hay quien dice "no quiero volver a trabajar sin esto". Cada ejemplo combina varios servidores MCP en una única sesión. + +Flujo de trabajo de issue a PR usando MCP - Muestra el flujo completo desde obtener un issue de GitHub hasta crear un pull request + +*Flujo completo de MCP: el MCP de GitHub recupera datos del repo, el MCP de Filesystem encuentra el código, el MCP de Context7 aporta buenas prácticas y Copilot se encarga del análisis* + +Cada ejemplo de abajo es autónomo. **Elige el que te interese o léelos todos.** + +| Quiero ver... | Ir a | +|---|---| +| Varios servidores funcionando juntos | [Exploración multiservidor](#multi-server-exploration) | +| Pasar de issue a PR en una sola sesión | [Flujo de trabajo de issue a PR](#issue-to-pr-workflow) | +| Una rápida revisión de salud del proyecto | [Panel de salud](#health-dashboard) | + +
+Exploración multiservidor - Combina filesystem, GitHub y Context7 en una sesión + + +#### Explorar el book app con varios servidores 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) +``` + +
+🎬 ¡Ve el flujo de trabajo de MCP en acción! + +![Demo del flujo de trabajo de MCP](../../../06-mcp-servers/images/mcp-workflow-demo.gif) + +*La salida de la demo varía. Tu modelo, tus herramientas y las respuestas serán distintos a lo que se muestra aquí.* + +
+ +**El resultado**: Exploración del código → revisión del historial → consulta de buenas prácticas → plan de mejora. **Todo desde una sola sesión de terminal, usando tres servidores MCP juntos.** + +
+ +
+Flujo de trabajo de issue a PR - Pasa de un issue de GitHub a un pull request sin salir de la terminal + + +#### El flujo de trabajo de issue a PR (en tu propio repo) + +Esto funciona mejor en tu propio fork o repositorio donde tengas permisos de escritura: + +> 💡 **No te preocupes si no puedes probarlo ahora mismo.** Si estás en un clon de solo lectura, lo practicarás en la tarea. Por ahora, basta con leer para entender el flujo. + +```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 implements year validation in 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 +``` + +**Cero copiar y pegar. Cero cambio de contexto. Una sola sesión de terminal.** + +
+ +
+Panel de salud - Obtén una rápida revisión de salud del proyecto usando varios servidores + + +#### Panel de salud del 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! +``` + +**El resultado**: Múltiples fuentes de datos agregadas en segundos. De forma manual, esto significaría ejecutar grep, contar líneas, revisar git log y navegar por archivos de pruebas. Fácilmente más de 15 minutos de trabajo. + +
+ +--- + +# Práctica + +Espacio de escritorio acogedor con monitor mostrando código, lámpara, taza de café y auriculares listos para la práctica + +**🎉 ¡Ya conoces lo esencial!** Entiendes MCP, has visto cómo configurar servidores y has visto flujos de trabajo reales en acción. Ahora es momento de probarlo tú. + +--- + +## ▶️ Inténtalo tú mismo + +¡Te toca! Completa estos ejercicios para practicar el uso de servidores MCP con el proyecto book app. + +### Ejercicio 1: Comprueba el estado de tu MCP + +Empieza viendo qué servidores MCP están disponibles: + +```bash +copilot + +> /mcp show +``` + +Deberías ver el servidor de GitHub listado como habilitado. Si no, ejecuta `/login` para autenticarte. + +--- + +### Ejercicio 2: Explora el book app con el MCP de Filesystem + +Si has configurado el servidor de filesystem, úsalo para explorar el book app: + +```bash +copilot + +> How many Python files are in samples/book-app-project/? +> What functions are defined in each file? +``` + +**Resultado esperado**: Copilot lista `book_app.py`, `books.py` y `utils.py` con sus funciones. + +> 💡 **¿Aún no has configurado el MCP de filesystem?** Crea el archivo de configuración a partir de la sección [Configuración completa](#complete-configuration-file) de arriba. Después reinicia Copilot. + +--- + +### Ejercicio 3: Consulta el historial del repositorio con el MCP de GitHub + +Usa el MCP integrado de GitHub para explorar este repositorio del curso: + +```bash +copilot + +> List the last 5 commits in this repository + +> What branches exist in this repository? +``` + +**Resultado esperado**: Copilot muestra los mensajes recientes de commit y los nombres de las ramas desde el remoto de GitHub. + +> ⚠️ **¿Estás en un Codespace?** Esto funciona automáticamente. La autenticación se hereda. Si estás en un clon local, asegúrate de que `gh auth status` muestra que has iniciado sesión. + +--- + +### Ejercicio 4: Combina varios servidores MCP + +Ahora combina los MCP de filesystem y GitHub en una sola sesión: + +```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. +``` + +**Resultado esperado**: Copilot lee el archivo JSON (MCP de filesystem), lista los 5 libros incluidos "The Hobbit", "1984", "Dune", "To Kill a Mockingbird" y "Mysterious Book", y luego consulta GitHub para el historial de commits. + +**Autoevaluación**: Entiendes MCP cuando puedes explicar por qué "Comprueba el historial de commits de mi repo" es mejor que ejecutar manualmente `git log` y pegar la salida en tu prompt. + +--- + +## 📝 Tarea + +### Reto principal: Exploración del book app con MCP + +Practica el uso de servidores MCP juntos en el proyecto book app. Completa estos pasos en una sola sesión de Copilot: + +1. **Verifica que MCP funciona**: Ejecuta `/mcp show` y confirma que al menos el servidor de GitHub está habilitado +2. **Configura el MCP de filesystem** (si aún no lo has hecho): Crea `~/.copilot/mcp-config.json` con la configuración del servidor de filesystem +3. **Explora el código**: Pide a Copilot que use el servidor de filesystem para: + - Listar todas las funciones en `samples/book-app-project/books.py` + - Comprobar qué funciones de `samples/book-app-project/utils.py` no tienen type hints + - Leer `samples/book-app-project/data.json` e identificar problemas de calidad de datos (pista: fíjate en la última entrada) +4. **Comprueba la actividad del repositorio**: Pide a Copilot que use el MCP de GitHub para: + - Listar los commits recientes que tocaron archivos en `samples/book-app-project/` + - Comprobar si hay issues o pull requests abiertos +5. **Combina servidores**: En un único prompt, pide a Copilot que: + - Lea el archivo de pruebas en `samples/book-app-project/tests/test_books.py` + - Compare las funciones probadas con todas las funciones de `books.py` + - Resuma qué cobertura de pruebas falta + +**Criterios de éxito**: Puedes combinar sin fricciones datos de los MCP de filesystem y GitHub en una sola sesión de Copilot, y puedes explicar qué aportó cada servidor MCP a la respuesta. + +
+💡 Pistas (haz clic para expandir) + +**Paso 1: Verifica MCP** +```bash +copilot +> /mcp show +# Should show "github" as enabled +# If not, run: /login +``` + +**Paso 2: Crea el archivo de configuración** + +Usa el JSON de la sección [Configuración completa](#complete-configuration-file) de arriba y guárdalo como `~/.copilot/mcp-config.json`. + +**Paso 3: Problema de calidad de datos a buscar** + +El último libro de `data.json` es: +```json +{ + "title": "Mysterious Book", + "author": "", + "year": 0, + "read": false +} +``` +Un autor vacío y año 0. ¡Ese es el problema de calidad de datos! + +**Paso 5: Comparación de cobertura de pruebas** + +Las pruebas en `test_books.py` cubren: `add_book`, `mark_as_read`, `remove_book`, `get_unread_books` y `find_book_by_title`. Funciones como `load_books`, `save_books` y `list_books` no tienen pruebas directas. Las funciones CLI en `book_app.py` y los helpers en `utils.py` no tienen ninguna prueba. + +**Si MCP no funciona:** Reinicia Copilot después de editar el archivo de configuración. + +
+ +### Reto extra: Construye un servidor MCP personalizado + +¿Listo para profundizar más? Sigue la [Guía del servidor MCP personalizado](mcp-custom-server.md) para construir tu propio servidor MCP en Python que se conecte a cualquier API. + +--- + +
+🔧 Errores comunes y solución de problemas (haz clic para expandir) + +### Errores comunes + +| Error | Qué pasa | Solución | +|---------|--------------|-----| +| No saber que el MCP de GitHub viene integrado | Intentar instalarlo o configurarlo manualmente | El MCP de GitHub viene incluido por defecto. Solo prueba: "List the recent commits in this repo" | +| Buscar la configuración en el lugar equivocado | No encontrar o editar los ajustes de MCP | La configuración a nivel de usuario está en `~/.copilot/mcp-config.json`, la de nivel de proyecto es `.mcp.json` en la raíz del proyecto | +| JSON inválido en el archivo de configuración | Los servidores MCP no se cargan | Usa `/mcp show` para revisar la configuración; valida la sintaxis JSON | +| Olvidar autenticar los servidores MCP | Errores de "Authentication failed" | Algunos MCPs necesitan autenticación aparte. Revisa los requisitos de cada servidor | + +### Solución de problemas + +**"MCP server not found"** - Comprueba que: +1. El paquete de npm existe: `npm view @modelcontextprotocol/server-github` +2. Tu configuración es JSON válido +3. El nombre del servidor coincide con el de tu configuración + +Usa `/mcp show` para ver la configuración actual. + +**"GitHub authentication failed"** - El MCP integrado de GitHub usa tus credenciales de `/login`. Prueba: + +```bash +copilot +> /login +``` + +Esto te reautenticará con GitHub. Si los problemas persisten, comprueba que tu cuenta de GitHub tiene los permisos necesarios para el repositorio al que estás accediendo. + +**"MCP server failed to start"** - Revisa los logs del servidor: +```bash +# Run the server command manually to see errors +npx -y @modelcontextprotocol/server-github +``` + +**Las herramientas de MCP no están disponibles** - Asegúrate de que el servidor está habilitado: +```bash +copilot + +> /mcp show +# Check if server is listed and enabled +``` + +Si un servidor está deshabilitado, consulta los [comandos `/mcp` adicionales](#-additional-mcp-commands) de abajo para saber cómo reactivarlo. + +
+ +--- + +
+📚 Comandos MCP adicionales (haz clic para expandir) + + +Puedes gestionar los servidores MCP de dos formas: usando **comandos slash dentro de una sesión de chat**, o usando el comando **`copilot mcp` directamente en tu terminal** (sin necesidad de sesión de chat). + +### Opción 1: Comandos slash (dentro de una sesión de chat) + +Funcionan cuando ya estás dentro de `copilot`: + +| Comando | Qué hace | +|---------|--------------| +| `/mcp show` | Muestra todos los servidores MCP configurados y su estado | +| `/mcp add` | Configuración interactiva para añadir un nuevo servidor | +| `/mcp edit ` | Edita la configuración de un servidor existente | +| `/mcp enable ` | Habilita un servidor deshabilitado (persiste entre sesiones) | +| `/mcp disable ` | Deshabilita un servidor (persiste entre sesiones) | +| `/mcp delete ` | Elimina un servidor permanentemente | +| `/mcp auth ` | Reautentica con un servidor MCP que use OAuth (p. ej., tras cambiar de cuenta) | + +### Opción 2: Comando `copilot mcp` (desde tu terminal) + +También puedes gestionar los servidores MCP directamente desde tu terminal sin iniciar antes una sesión de chat: + +```bash +# List all configured MCP servers +copilot mcp list + +# Enable a server +copilot mcp enable filesystem + +# Disable a server +copilot mcp disable context7 +``` + +> 💡 **¿Cuándo usar cada uno?** Usa los comandos slash `/mcp` cuando ya estés en una sesión de chat. Usa `copilot mcp` desde la terminal cuando quieras revisar o cambiar rápidamente los ajustes de tus servidores antes de iniciar una sesión. + +Para la mayor parte de este curso, `/mcp show` es todo lo que necesitas. Los demás comandos te resultarán útiles a medida que gestiones más servidores con el tiempo. + +
+ +--- + +# Resumen + +## 🔑 Conclusiones clave + +1. **MCP** conecta Copilot con servicios externos (GitHub, sistema de archivos, documentación) +2. **El MCP de GitHub viene integrado** - sin configuración necesaria, basta con `/login` +3. **Filesystem y Context7** se configuran mediante `~/.copilot/mcp-config.json` +4. **Los flujos de trabajo multiservidor** combinan datos de múltiples fuentes en una sola sesión +5. **Gestiona los servidores de dos formas**: usa los comandos slash `/mcp` dentro del chat, o `copilot mcp` desde la terminal +6. **Los servidores personalizados** te permiten conectar cualquier API (opcional, cubierto en la guía del apéndice) + +> 📋 **Referencia rápida**: Consulta la [referencia de comandos de GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para ver una lista completa de comandos y atajos. + +--- + +## ➡️ Qué sigue + +Ya tienes todos los bloques: modos, contexto, flujos de trabajo, agentes, skills y MCP. Es hora de combinarlos. + +En el **[Capítulo 07: Combinando todo](../07-putting-it-together/README.md)** aprenderás: + +- Combinar agentes, skills y MCP en flujos de trabajo unificados +- Desarrollo completo de funcionalidades de la idea al PR fusionado +- Automatización con hooks +- Buenas prácticas para entornos de equipo + +--- + +**[← Volver al Capítulo 05](../05-skills/README.md)** | **[Continuar al Capítulo 07 →](../07-putting-it-together/README.md)** diff --git a/localization/es-es/06-mcp-servers/mcp-custom-server.md b/localization/es-es/06-mcp-servers/mcp-custom-server.md new file mode 100644 index 00000000..37fe226b --- /dev/null +++ b/localization/es-es/06-mcp-servers/mcp-custom-server.md @@ -0,0 +1,176 @@ +# Construir un servidor MCP personalizado + +> ⚠️ **Este contenido es totalmente opcional.** Puedes ser muy productivo con Copilot CLI usando únicamente los servidores MCP preconstruidos (GitHub, filesystem, Context7). Esta guía es para personas desarrolladoras que quieran conectar Copilot con APIs internas personalizadas. Consulta el [curso MCP for Beginners](https://github.com/microsoft/mcp-for-beginners) para más detalles. +> +> **Requisitos previos:** +> - Sentirte cómodo con Python +> - Comprender los patrones `async`/`await` +> - Tener `pip` disponible en tu sistema (incluido en este dev container) +> +> **[← Volver al Capítulo 06: Servidores MCP](README.md)** + +--- + +¿Quieres conectar Copilot con tus propias APIs? Aquí tienes cómo construir un servidor MCP sencillo en Python que busca información de libros, vinculándolo con el proyecto book app que has estado usando a lo largo de este curso. + +## Configuración del proyecto + +```bash +mkdir book-lookup-mcp-server +cd book-lookup-mcp-server +pip install mcp +``` + +> 💡 **¿Qué es el paquete `mcp`?** Es el SDK oficial de Python para construir servidores MCP. Se encarga de los detalles del protocolo para que tú puedas centrarte en tus herramientas. + +## Implementación del servidor + +Crea un archivo llamado `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() +``` + +**Qué está pasando aquí:** + +| Parte | Qué hace | +|------|-------------| +| `FastMCP("book-lookup")` | Crea un servidor llamado "book-lookup" | +| `@mcp.tool()` | Registra una función como herramienta que Copilot puede invocar | +| Type hints + docstrings | Indican a Copilot lo que hace cada herramienta y los parámetros que necesita | +| `mcp.run()` | Inicia el servidor y se queda escuchando peticiones | + +> 💡 **¿Por qué decoradores?** El decorador `@mcp.tool()` es todo lo que necesitas. El SDK de MCP lee automáticamente el nombre de tu función, sus type hints y su docstring para generar el esquema de la herramienta. ¡No hace falta escribir un esquema JSON a mano! + +## Configuración + +Añade esto a tu `~/.copilot/mcp-config.json`: + +```json +{ + "mcpServers": { + "book-lookup": { + "type": "local", + "command": "python3", + "args": ["./book-lookup-mcp-server/server.py"], + "tools": ["*"] + } + } +} +``` + +## Uso + +```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] +``` + +## Próximos pasos + +Una vez que hayas construido un servidor básico, puedes: + +1. **Añadir más herramientas** - Cada función `@mcp.tool()` se convierte en una herramienta que Copilot puede invocar +2. **Conectar APIs reales** - Sustituye el `BOOKS_DB` simulado por llamadas reales a una API o consultas a una base de datos +3. **Añadir autenticación** - Maneja claves de API y tokens de forma segura +4. **Compartir tu servidor** - Publícalo en PyPI para que otras personas puedan instalarlo con `pip` + +## Recursos + +- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) +- [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) +- [Servidores MCP de ejemplo](https://github.com/modelcontextprotocol/servers) +- [Curso MCP for Beginners](https://github.com/microsoft/mcp-for-beginners) + +--- + +**[← Volver al Capítulo 06: Servidores MCP](README.md)** diff --git a/localization/es-es/07-putting-it-together/README.md b/localization/es-es/07-putting-it-together/README.md new file mode 100644 index 00000000..10a6bb8d --- /dev/null +++ b/localization/es-es/07-putting-it-together/README.md @@ -0,0 +1,512 @@ +![Capítulo 07: Combinando todo](../../../07-putting-it-together/images/chapter-header.png) + +> **Todo lo que has aprendido se combina aquí. Pasa de la idea al PR fusionado en una sola sesión.** + +En este capítulo unirás todo lo que has aprendido en flujos de trabajo completos. Construirás funcionalidades usando colaboración multiagente, configurarás hooks de pre-commit que detectan problemas de seguridad antes de que se confirmen, integrarás Copilot en pipelines de CI/CD, e irás de la idea de una funcionalidad al PR fusionado en una sola sesión de terminal. Aquí es donde GitHub Copilot CLI se convierte en un auténtico multiplicador de fuerza. + +> 💡 **Nota**: Este capítulo muestra cómo combinar todo lo que has aprendido. **No necesitas agentes, skills ni MCP para ser productivo (aunque pueden resultar muy útiles).** El flujo de trabajo central — describir, planificar, implementar, probar, revisar, enviar — funciona solo con las funcionalidades integradas de los Capítulos 00-03. + +## 🎯 Objetivos de aprendizaje + +Al finalizar este capítulo, serás capaz de: + +- Combinar agentes, skills y MCP (Model Context Protocol) en flujos de trabajo unificados +- Construir funcionalidades completas usando enfoques multi-herramienta +- Configurar automatización básica con hooks +- Aplicar buenas prácticas para el desarrollo profesional + +> ⏱️ **Tiempo estimado**: ~75 minutos (15 min de lectura + 60 min práctica) + +--- + +## 🧩 Analogía del mundo real: la orquesta + +Analogía de la orquesta - Flujo de trabajo unificado + +Una orquesta sinfónica tiene muchas secciones: +- **Las cuerdas** aportan la base (como tus flujos de trabajo principales) +- **Los metales** añaden potencia (como los agentes con experiencia especializada) +- **Las maderas** añaden color (como los skills que amplían capacidades) +- **La percusión** marca el ritmo (como MCP conectando con sistemas externos) + +Por separado, cada sección suena limitada. Juntas y bien dirigidas, crean algo magnífico. + +**¡Eso es lo que enseña este capítulo!**
+*Como un director con su orquesta, tú orquestas agentes, skills y MCP en flujos de trabajo unificados* + +Empecemos recorriendo un escenario que modifica código, genera pruebas, lo revisa y crea un PR - todo en una sola sesión. + +--- + +## De la idea al PR fusionado en una sola sesión + +En lugar de cambiar entre tu editor, la terminal, el ejecutor de pruebas y la interfaz de GitHub, perdiendo contexto cada vez, puedes combinar todas tus herramientas en una sola sesión de terminal. Desglosaremos este patrón en la sección [Patrón de integración](#the-integration-pattern-for-power-users) más abajo. + +```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, use /pr to operate on the pull request for the current branch +> /pr [view|create|fix|auto] + +# Or ask naturally if you want Copilot to draft it from the terminal +> Create a pull request titled "Feature: Add list unread books command" +``` + +**Enfoque tradicional**: Cambiar entre editor, terminal, ejecutor de pruebas, documentación y la interfaz de GitHub. Cada cambio provoca pérdida de contexto y fricción. + +**La idea clave**: Diriges a especialistas como un arquitecto. Ellos se encargan de los detalles. Tú te encargas de la visión. + +> 💡 **Yendo más allá**: Para planes grandes y multi-paso como este, prueba `/fleet` para que Copilot ejecute subtareas independientes en paralelo. Consulta la [documentación oficial](https://docs.github.com/copilot/concepts/agents/copilot-cli/fleet) para más detalles. + +--- + +# Flujos de trabajo adicionales + +Personas montando un puzzle gigante de colores con engranajes, que representa cómo agentes, skills y MCP se combinan en flujos de trabajo unificados + +Para usuarios avanzados que han completado los Capítulos 04-06, estos flujos de trabajo muestran cómo agentes, skills y MCP multiplican tu eficacia. + +## El patrón de integración + +Aquí tienes el modelo mental para combinarlo todo: + +El patrón de integración - Un flujo de trabajo de 4 fases: Reunir contexto (MCP), Analizar y planificar (Agentes), Ejecutar (Skills + Manual), Completar (MCP) + +--- + +## Flujo de trabajo 1: Investigación y corrección de bugs + +Corrección de bugs reales con integración completa de herramientas: + +```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 +``` + +--- + +## Flujo de trabajo 2: Automatización de revisión de código (opcional) + +> 💡 **Esta sección es opcional.** Los hooks de pre-commit son útiles para equipos pero no son imprescindibles para ser productivo. Sáltatela si estás empezando. +> +> ⚠️ **Nota de rendimiento**: Este hook llama a `copilot -p` por cada archivo en staged, lo que tarda varios segundos por archivo. Para commits grandes, considera limitarlo a archivos críticos o ejecutar las revisiones manualmente con `/review`. + +Un **git hook** es un script que Git ejecuta automáticamente en determinados puntos, por ejemplo, justo antes de un commit. Puedes usarlo para ejecutar comprobaciones automatizadas sobre tu código. Aquí tienes cómo configurar una revisión automatizada de Copilot en tus commits: + +```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 +``` + +> ⚠️ **Usuarios de macOS**: El comando `timeout` no viene incluido por defecto en macOS. Instálalo con `brew install coreutils` o sustituye `timeout 60` por una invocación simple sin protección de tiempo. + +> 📚 **Documentación oficial**: [Usar hooks](https://docs.github.com/copilot/how-tos/copilot-cli/use-hooks) y [Referencia de configuración de hooks](https://docs.github.com/copilot/reference/hooks-configuration) para la API completa de hooks. +> +> 💡 **Alternativa integrada**: Copilot CLI también tiene un sistema de hooks integrado (`copilot hooks`) que puede ejecutarse automáticamente en eventos como pre-commit. El git hook manual de arriba te da control total, mientras que el sistema integrado es más sencillo de configurar. Consulta la documentación de arriba para decidir qué enfoque encaja con tu flujo de trabajo. + +Ahora cada commit recibe una rápida revisión de seguridad: + +```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. +``` + +--- + +## Flujo de trabajo 3: Onboarding en una nueva base de código + +Al incorporarte a un nuevo proyecto, combina contexto, agentes y MCP para ponerte al día rápido: + +```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 +``` + +Este flujo de trabajo combina contexto con `@`, agentes y MCP en una sola sesión de onboarding, exactamente el patrón de integración de antes en este capítulo. + +--- + +# Buenas prácticas y automatización + +Patrones y hábitos que hacen que tus flujos de trabajo sean más eficaces. + +--- + +## Buenas prácticas + +### 1. Empieza con contexto antes del análisis + +Reúne siempre contexto antes de pedir un análisis: + +```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. Conoce la diferencia: agentes, skills e instrucciones personalizadas + +Cada herramienta tiene su punto fuerte: + +```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 +``` + +> 💡 **Punto clave**: Los agentes y los skills pueden tanto analizar como generar código. La diferencia real es **cómo se activan** — los agentes son explícitos (`/agent`), los skills son automáticos (se activan según el prompt) y las instrucciones personalizadas están siempre activas. + +### 3. Mantén las sesiones enfocadas + +Usa `/rename` para etiquetar tu sesión (facilita encontrarla en el historial) y `/exit` para terminarla limpiamente: + +```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. Haz que los flujos de trabajo sean reutilizables con Copilot + +En lugar de simplemente documentar los flujos de trabajo en una wiki, codifícalos directamente en tu repo donde Copilot pueda usarlos: + +- **Instrucciones personalizadas** (`.github/copilot-instructions.md`): Guía siempre activa para estándares de codificación, reglas de arquitectura y pasos de build/test/deploy. Cada sesión las sigue automáticamente. +- **Archivos de prompts** (`.github/prompts/`): Prompts reutilizables y parametrizables que tu equipo puede compartir — como plantillas para revisiones de código, generación de componentes o descripciones de PR. +- **Agentes personalizados** (`.github/agents/`): Codifica personas especializadas (p. ej., un revisor de seguridad o un redactor de documentación) que cualquiera del equipo pueda activar con `/agent`. +- **Skills personalizados** (`.github/skills/`): Empaqueta instrucciones de flujo de trabajo paso a paso que se activan automáticamente cuando son relevantes. + +> 💡 **El beneficio**: Las nuevas personas del equipo obtienen tus flujos de trabajo gratis — están integrados en el repo, no encerrados en la cabeza de alguien. + +--- + +## Extra: Patrones de producción + +Estos patrones son opcionales pero valiosos para entornos profesionales. + +### Generador de descripciones de 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" +``` + +### Integración CI/CD + +Para equipos con pipelines de CI/CD existentes, puedes automatizar las revisiones de Copilot en cada pull request usando GitHub Actions. Esto incluye publicar comentarios de revisión automáticamente y filtrar problemas críticos. + +> 📖 **Más información**: Consulta [Integración CI/CD](../appendices/ci-cd-integration.md) para flujos de trabajo de GitHub Actions completos, opciones de configuración y consejos de solución de problemas. + +--- + +# Práctica + +Espacio de escritorio acogedor con monitor mostrando código, lámpara, taza de café y auriculares listos para la práctica + +Pon en práctica el flujo de trabajo completo. + +--- + +## ▶️ Inténtalo tú mismo + +Después de completar las demos, prueba estas variantes: + +1. **Reto end-to-end**: Elige una pequeña funcionalidad (p. ej., "list unread books" o "export to CSV"). Usa el flujo de trabajo completo: + - Planifica con `/plan` + - Diseña con agentes (python-reviewer, pytest-helper) + - Implementa + - Genera pruebas + - Crea un PR + +2. **Reto de automatización**: Configura el hook de pre-commit del flujo de Automatización de revisión de código. Haz un commit con una vulnerabilidad intencionada de ruta de archivo. ¿Se bloquea? + +3. **Tu flujo de trabajo de producción**: Diseña tu propio flujo de trabajo para una tarea común que hagas. Escríbelo como una checklist. ¿Qué partes podrían automatizarse con skills, agentes o hooks? + +**Autoevaluación**: Has completado el curso cuando puedes explicarle a un compañero cómo funcionan juntos agentes, skills y MCP - y cuándo usar cada uno. + +--- + +## 📝 Tarea + +### Reto principal: Funcionalidad end-to-end + +Los ejemplos prácticos recorrieron la construcción de una funcionalidad "list unread books". Ahora practica el flujo de trabajo completo en una funcionalidad distinta: **buscar libros por rango de años**: + +1. Inicia Copilot y reúne contexto: `@samples/book-app-project/books.py` +2. Planifica con `/plan Add a "search by year" command that lets users find books published between two years` +3. Implementa un método `find_by_year_range(start_year, end_year)` en `BookCollection` +4. Añade una función `handle_search_year()` en `book_app.py` que pregunte al usuario por los años de inicio y fin +5. Genera pruebas: `@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. Revisa con `/review` +7. Actualiza el README: `@samples/book-app-project/README.md Add documentation for the new "search by year" command.` +8. Genera un mensaje de commit + +Documenta tu flujo de trabajo a medida que avances. + +**Criterios de éxito**: Has completado la funcionalidad de la idea al commit usando Copilot CLI, incluyendo planificación, implementación, pruebas, documentación y revisión. + +> 💡 **Extra**: Si tienes agentes configurados desde el Capítulo 04, prueba a crear y usar agentes personalizados. Por ejemplo, un agente error-handler para revisión de la implementación y un agente doc-writer para la actualización del README. + +
+💡 Pistas (haz clic para expandir) + +**Sigue el patrón del ejemplo ["De la idea al PR fusionado"](#idea-to-merged-pr-in-one-session)** del inicio de este capítulo. Los pasos clave son: + +1. Reúne contexto con `@samples/book-app-project/books.py` +2. Planifica con `/plan Add a "search by year" command` +3. Implementa el método y el manejador del comando +4. Genera pruebas con casos límite (entrada inválida, resultados vacíos, rango invertido) +5. Revisa con `/review` +6. Actualiza el README con `@samples/book-app-project/README.md` +7. Genera un mensaje de commit con `-p` + +**Casos límite a tener en cuenta:** +- ¿Qué pasa si el usuario introduce "2000" y "1990" (rango invertido)? +- ¿Qué pasa si ningún libro coincide con el rango? +- ¿Qué pasa si el usuario introduce datos no numéricos? + +**La clave es practicar el flujo de trabajo completo** desde idea → contexto → plan → implementar → probar → documentar → commit. + +
+ +--- + +
+🔧 Errores comunes (haz clic para expandir) + +| Error | Qué pasa | Solución | +|---------|--------------|-----| +| Saltar directamente a la implementación | Te pierdes problemas de diseño que cuesta corregir más tarde | Usa primero `/plan` para reflexionar sobre el enfoque | +| Usar una sola herramienta cuando varias ayudarían | Resultados más lentos y menos completos | Combina: agente para análisis → skill para ejecución → MCP para integración | +| No revisar antes de hacer commit | Se cuelan problemas de seguridad o bugs | Ejecuta siempre `/review` o usa un [hook de pre-commit](#workflow-2-code-review-automation-optional) | +| Olvidar compartir flujos de trabajo con el equipo | Cada persona reinventa la rueda | Documenta los patrones en agentes, skills e instrucciones compartidas | + +
+ +--- + +# Resumen + +## 🔑 Conclusiones clave + +1. **Integración > Aislamiento**: Combina herramientas para un máximo impacto +2. **Contexto primero**: Reúne siempre el contexto necesario antes del análisis +3. **Los agentes analizan, los skills ejecutan**: Usa la herramienta adecuada para cada tarea +4. **Automatiza la repetición**: Los hooks y scripts multiplican tu eficacia +5. **Documenta los flujos de trabajo**: Los patrones compartibles benefician a todo el equipo + +> 📋 **Referencia rápida**: Consulta la [referencia de comandos de GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para ver una lista completa de comandos y atajos. + +--- + +## 🎓 ¡Curso completado! + +¡Enhorabuena! Has aprendido: + +| Capítulo | Lo que has aprendido | +|---------|-------------------| +| 00 | Instalación de Copilot CLI e inicio rápido | +| 01 | Tres modos de interacción | +| 02 | Gestión de contexto con la sintaxis @ | +| 03 | Flujos de trabajo de desarrollo | +| 04 | Agentes especializados | +| 05 | Skills extensibles | +| 06 | Conexiones externas con MCP | +| 07 | Flujos de trabajo unificados de producción | + +Ahora estás equipado para usar GitHub Copilot CLI como un auténtico multiplicador de fuerza en tu flujo de trabajo de desarrollo. + +## ➡️ Qué sigue + +Tu aprendizaje no termina aquí: + +1. **Practica a diario**: Usa Copilot CLI para trabajo real +2. **Construye herramientas personalizadas**: Crea agentes y skills para tus necesidades específicas +3. **Comparte conocimiento**: Ayuda a tu equipo a adoptar estos flujos de trabajo +4. **Mantente al día**: Sigue las novedades de GitHub Copilot para nuevas funcionalidades + +### Recursos + +- [Documentación de GitHub Copilot CLI](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) +- [Registro de servidores MCP](https://github.com/modelcontextprotocol/servers) +- [Skills de la comunidad](https://github.com/topics/copilot-skill) + +--- + +**¡Buen trabajo! Ahora ve a construir algo increíble.** + +**[← Volver al Capítulo 06](../06-mcp-servers/README.md)** | **[Volver al inicio del curso →](../README.md)** diff --git a/localization/es-es/README.md b/localization/es-es/README.md new file mode 100644 index 00000000..147d1f3c --- /dev/null +++ b/localization/es-es/README.md @@ -0,0 +1,110 @@ +![GitHub Copilot CLI para principiantes](../../images/copilot-banner.png) + +[![Licencia: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](../../LICENSE)  +[![Abrir proyecto en 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)  +[![Documentación oficial de 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)  +[![Únete a Discord de AI Foundry](https://img.shields.io/badge/Discord-AI_Community-blue?style=flat-square&logo=discord&color=5865f2&logoColor=fff)](https://aka.ms/foundry/discord) + +🎯 [Qué aprenderás](#qué-aprenderás)   ✅ [Requisitos previos](#requisitos-previos)   🤖 [Familia Copilot](#entendiendo-la-familia-de-github-copilot)   📚 [Estructura del curso](#estructura-del-curso)   📋 [Referencia de comandos](#-referencia-de-comandos-de-github-copilot-cli) + +# GitHub Copilot CLI para principiantes + +> **✨ Aprende a potenciar tu flujo de trabajo de desarrollo con asistencia de línea de comandos impulsada por IA.** + +GitHub Copilot CLI lleva la asistencia de IA directamente a tu terminal. En lugar de cambiar a un navegador o editor de código, puedes hacer preguntas, generar aplicaciones completas, revisar código, generar pruebas y depurar problemas sin salir de tu línea de comandos. + +¡Imagínalo como tener un compañero experimentado disponible 24/7 que puede leer tu código, explicar patrones confusos y ayudarte a trabajar más rápido! + +> 📘 **¿Prefieres una experiencia web?** Puedes seguir este curso aquí mismo en GitHub, o verlo en [Awesome Copilot](https://awesome-copilot.github.com/learning-hub/cli-for-beginners/) para una experiencia de navegación más tradicional. + +Este curso está diseñado para: + +- **Desarrolladores de software** que quieren usar IA desde la línea de comandos +- **Usuarios de terminal** que prefieren flujos de trabajo basados en teclado sobre las integraciones con IDE +- **Equipos que buscan estandarizar** las prácticas de revisión de código y desarrollo asistido por IA + + + + GitHub Copilot Dev Days - Encuentra u organiza un evento + + + +## 🎯 Qué aprenderás + +Este curso práctico te lleva de cero a productivo con GitHub Copilot CLI. Trabajarás con una única aplicación Python de colección de libros en todos los capítulos, mejorándola progresivamente mediante flujos de trabajo asistidos por IA. Al final, utilizarás con confianza la IA para revisar código, generar pruebas, depurar problemas y automatizar flujos de trabajo: todo desde tu terminal. + +**No se requiere experiencia con IA.** Si puedes usar una terminal, puedes aprender esto. + +**Perfecto para:** Desarrolladores, estudiantes y cualquier persona con experiencia en desarrollo de software. + +## ✅ Requisitos previos + +Antes de comenzar, asegúrate de tener: + +- **Cuenta de GitHub**: [Crea una gratis](https://github.com/signup)
+- **Acceso a GitHub Copilot**: [Oferta gratuita](https://github.com/features/copilot/plans), [Suscripción mensual](https://github.com/features/copilot/plans) o [Gratis para estudiantes/profesores](https://education.github.com/pack)
+- **Conocimientos básicos de terminal**: Cómodo con `cd`, `ls`, ejecutar comandos + +## 🤖 Entendiendo la familia de GitHub Copilot + +GitHub Copilot ha evolucionado hasta convertirse en una familia de herramientas impulsadas por IA. Aquí es donde vive cada una: + +| Producto | Dónde se ejecuta | Descripción | +|---------|---------------|----------| +| [**GitHub Copilot CLI**](https://docs.github.com/copilot/how-tos/copilot-cli/cli-getting-started)
(este curso) | Tu terminal | Asistente de programación con IA nativo de la terminal | +| [**GitHub Copilot**](https://docs.github.com/copilot) | VS Code, Visual Studio, JetBrains, etc. | Modo agente, chat, sugerencias en línea | +| [**Copilot en GitHub.com**](https://github.com/copilot) | GitHub | Chat inmersivo sobre tus repositorios, crear agentes y más | +| [**Agente cloud de GitHub Copilot**](https://docs.github.com/copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks) | GitHub | Asigna issues a agentes, recibe PRs de vuelta | + +Este curso se centra en **GitHub Copilot CLI**, llevando la asistencia de IA directamente a tu terminal. + +## 📚 Estructura del curso + +![Ruta de aprendizaje de GitHub Copilot CLI](../../images/learning-path.png) + +| Capítulo | Título | Qué construirás | +|:-------:|-------|-------------------| +| 00 | 🚀 [Inicio rápido](./00-quick-start/README.md) | Instalación y verificación | +| 01 | 👋 [Primeros pasos](./01-setup-and-first-steps/README.md) | Demostraciones en vivo + tres modos de interacción | +| 02 | 🔍 [Contexto y conversaciones](./02-context-conversations/README.md) | Análisis de proyectos con múltiples archivos | +| 03 | ⚡ [Flujos de trabajo de desarrollo](./03-development-workflows/README.md) | Revisión de código, depuración, generación de pruebas | +| 04 | 🤖 [Crear asistentes de IA especializados](./04-agents-custom-instructions/README.md) | Agentes personalizados para tu flujo de trabajo | +| 05 | 🛠️ [Automatizar tareas repetitivas](./05-skills/README.md) | Skills que se cargan automáticamente | +| 06 | 🔌 [Conectar a GitHub, bases de datos y APIs](./06-mcp-servers/README.md) | Integración con servidores MCP | +| 07 | 🎯 [Poniéndolo todo junto](./07-putting-it-together/README.md) | Flujos de trabajo completos de funcionalidades | + +## 📖 Cómo funciona este curso + +Cada capítulo sigue el mismo patrón: + +1. **Analogía del mundo real**: Comprende el concepto a través de comparaciones familiares +2. **Conceptos clave**: Aprende el conocimiento esencial +3. **Ejemplos prácticos**: Ejecuta comandos reales y observa los resultados +4. **Tarea**: Practica lo que has aprendido +5. **Qué sigue**: Vista previa del capítulo siguiente + +**Los ejemplos de código son ejecutables.** Cada bloque de texto de copilot en este curso puede copiarse y ejecutarse en tu terminal. + +## 📋 Referencia de comandos de GitHub Copilot CLI + +La **[referencia de comandos de GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference)** te ayuda a encontrar comandos y atajos de teclado para usar Copilot CLI de forma eficaz. + +## 🙋 Obtener ayuda + +- 🐛 **¿Encontraste un error?** [Abre un Issue](https://github.com/github/copilot-cli-for-beginners/issues) +- 📚 **Documentación oficial:** [Documentación de GitHub Copilot CLI](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) + +## Contribuir + +> **Nota**: El código utilizado en el curso está diseñado para generar tipos específicos de resultados durante las revisiones, explicaciones y depuraciones, por lo que no podemos aceptar PRs que cambien el código existente. + +**Cómo contribuir:** + +1. Haz un fork de este repositorio y clónalo en tu máquina +2. Crea una rama de funcionalidad (`git checkout -b my-improvement`) +3. Realiza tus cambios +4. Envía un pull request + +## Licencia + +Este proyecto está licenciado bajo los términos de la licencia de código abierto MIT. Consulta el archivo [LICENSE](../../LICENSE) para conocer los términos completos. diff --git a/localization/es-es/appendices/README.md b/localization/es-es/appendices/README.md new file mode 100644 index 00000000..a4592325 --- /dev/null +++ b/localization/es-es/appendices/README.md @@ -0,0 +1,12 @@ +# Apéndices + +Estos apéndices cubren temas adicionales que amplían el contenido principal del curso. Son de lectura opcional, para cuando necesites estas capacidades específicas. + +| Apéndice | Descripción | Requisito previo | +|----------|-------------|------------------| +| [Características adicionales de contexto](additional-context.md) | Trabajar con imágenes y permisos de múltiples directorios | Capítulo 02 | +| [Integración con CI/CD](ci-cd-integration.md) | Flujos de trabajo de GitHub Actions para revisiones automatizadas | Capítulo 07 | + +--- + +**[← Volver al inicio del curso](../README.md)** diff --git a/localization/es-es/appendices/additional-context.md b/localization/es-es/appendices/additional-context.md new file mode 100644 index 00000000..9097f790 --- /dev/null +++ b/localization/es-es/appendices/additional-context.md @@ -0,0 +1,140 @@ +# Características adicionales de contexto + +> 📖 **Requisito previo**: Completa el [Capítulo 02: Contexto y conversaciones](../02-context-conversations/README.md) antes de leer este apéndice. + +Este apéndice cubre dos características adicionales de contexto: trabajar con imágenes y gestionar permisos en múltiples directorios. + +--- + +## Trabajar con imágenes + +Puedes incluir imágenes en tus conversaciones usando la sintaxis `@`. Copilot puede analizar capturas de pantalla, maquetas, diagramas y otro contenido visual. + +### Referencia básica de imagen + +```bash +copilot + +> @screenshot.png What's happening in this UI? + +# Copilot analyzes the image and responds + +> @mockup.png @current-design.png Compare these two designs + +# You can also drag and drop images or paste from clipboard +``` + +### Formatos de imagen compatibles + +| Formato | Ideal para | +|---------|-----------| +| PNG | Capturas de pantalla, maquetas de UI, diagramas | +| JPG/JPEG | Fotos, imágenes complejas | +| GIF | Diagramas simples (solo el primer fotograma) | +| WebP | Capturas de pantalla web | + +### Casos de uso prácticos para imágenes + +**1. Depuración de UI** +```bash +> @bug-screenshot.png The button doesn't align properly. What CSS might cause this? +``` + +**2. Implementación de diseño** +```bash +> @figma-export.png Write the HTML and Tailwind CSS to match this design +``` + +**3. Análisis de errores** +```bash +> @error-screenshot.png What does this error mean and how do I fix it? +``` + +**4. Revisión de arquitectura** +```bash +> @whiteboard-diagram.png Convert this architecture diagram to a Mermaid diagram I can put in docs +``` + +**5. Comparación antes/después** +```bash +> @before.png @after.png What changed between these two versions of the UI? +``` + +### Combinar imágenes con código + +Las imágenes se vuelven aún más poderosas cuando se combinan con contexto de código: + +```bash +copilot + +> @screenshot-of-bug.png @src/components/Header.jsx +> The header looks wrong in the screenshot. What's causing it in the code? +``` + +### Consejos para imágenes + +- **Recorta las capturas de pantalla** para mostrar solo las partes relevantes (ahorra tokens de contexto) +- **Usa alto contraste** para los elementos de UI que quieres analizar +- **Anota si es necesario**: rodea con un círculo o resalta las áreas problemáticas antes de subir +- **Una imagen por concepto**: múltiples imágenes funcionan, pero sé específico + +--- + +## Patrones de permisos + +Por defecto, Copilot puede acceder a los archivos del directorio actual. Para archivos en otras ubicaciones, necesitas conceder acceso. + +### Añadir directorios + +```bash +# Add a directory to the allowed list +copilot --add-dir /path/to/other/project + +# Add multiple directories +copilot --add-dir ~/workspace --add-dir /tmp +``` + +### Permitir todas las rutas + +```bash +# Disable path restrictions entirely (use with caution) +copilot --allow-all-paths +``` + +### Dentro de una sesión + +```bash +copilot + +> /add-dir /path/to/other/project +# Now you can reference files from that directory + +> /list-dirs +# See all allowed directories + +> /yolo +# Quick alias for /allow-all on — auto-approves all permission prompts +``` + +### Para automatización + +```bash +# Allow all permissions for non-interactive scripts +copilot -p "Review @src/" --allow-all + +# Or use the memorable alias +copilot -p "Review @src/" --yolo +``` + +### Cuándo necesitas acceso a múltiples directorios + +Escenarios comunes donde necesitarás estos permisos: + +1. **Trabajo en monorepo**: Comparar código entre paquetes +2. **Refactorización entre proyectos**: Actualizar bibliotecas compartidas +3. **Proyectos de documentación**: Referenciar múltiples bases de código +4. **Trabajo de migración**: Comparar implementaciones antiguas y nuevas + +--- + +**[← Volver al Capítulo 02](../02-context-conversations/README.md)** | **[Volver a los apéndices](README.md)** diff --git a/localization/es-es/appendices/ci-cd-integration.md b/localization/es-es/appendices/ci-cd-integration.md new file mode 100644 index 00000000..cb26037e --- /dev/null +++ b/localization/es-es/appendices/ci-cd-integration.md @@ -0,0 +1,199 @@ +# Integración con CI/CD + +> 📖 **Requisito previo**: Completa el [Capítulo 07: Poniéndolo todo junto](../07-putting-it-together/README.md) antes de leer este apéndice. +> +> ⚠️ **Este apéndice es para equipos con pipelines de CI/CD existentes.** Si eres nuevo en GitHub Actions o en los conceptos de CI/CD, comienza con el enfoque más simple de pre-commit hooks en la sección [Automatización de revisión de código](../07-putting-it-together/README.md#workflow-3-code-review-automation-optional) del Capítulo 07. + +Este apéndice muestra cómo integrar GitHub Copilot CLI en tus pipelines de CI/CD para la revisión automatizada de código en pull requests. + +--- + +## Flujo de trabajo de GitHub Actions + +Este flujo de trabajo revisa automáticamente los archivos modificados cuando se abre o actualiza un 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 # Needed to compare with main branch + + - name: Install Copilot CLI + run: npm install -g @github/copilot + + - name: Review Changed Files + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Get list of changed JS/TS files + 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 + + # Use --silent to suppress progress output + 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'); + + // Only post if there's meaningful content + 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'); + } +``` + +--- + +## Opciones de configuración + +### Limitar el alcance de la revisión + +Puedes enfocar la revisión en tipos específicos de problemas: + +```yaml +# Security-only review +copilot --allow-all -p "Security review of @$file. Check for: SQL injection, XSS, hardcoded secrets, authentication issues." --silent + +# Performance-only review +copilot --allow-all -p "Performance review of @$file. Check for: N+1 queries, memory leaks, blocking operations." --silent +``` + +### Gestionar PRs grandes + +Para PRs con muchos archivos, considera agruparlos o limitarlos: + +```yaml +# Limit to first 10 files +FILES=$(git diff --name-only origin/main...HEAD | grep -E '\.(js|ts)$' | head -10) + +# Or set a timeout per file +timeout 60 copilot --allow-all -p "Review @$file" --silent || echo "Review timed out" +``` + +### Configuración de equipo + +Para revisiones consistentes en todo tu equipo, crea una configuración compartida: + +```json +// .copilot/config.json (committed to repo) +{ + "model": "claude-sonnet-4.5", + "permissions": { + "allowedPaths": ["src/**/*", "tests/**/*"], + "deniedPaths": [".env*", "secrets/**/*", "*.min.js"] + } +} +``` + +--- + +## Alternativa: Bot de revisión de PRs + +Para flujos de trabajo de revisión más sofisticados, considera usar el agente cloud de GitHub Copilot: + +```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]'] + }); +``` + +--- + +## Buenas prácticas para la integración CI/CD + +1. **Usa el flag `--silent`**: Suprime la salida de progreso para logs más limpios +2. **Establece tiempos de espera (timeouts)**: Evita que revisiones colgadas bloqueen tu pipeline +3. **Filtra tipos de archivos**: Revisa solo los archivos relevantes (omite código generado y dependencias) +4. **Ten en cuenta los límites de velocidad (rate limits)**: Espacia las revisiones para PRs grandes +5. **Falla de forma elegante**: No bloquees las fusiones por fallos en la revisión; registra y continúa + +--- + +## Solución de problemas + +### "Authentication failed" en CI + +Asegúrate de que tu flujo de trabajo tiene los permisos correctos: + +```yaml +permissions: + contents: read + pull-requests: write + issues: write +``` + +### Las revisiones se agota el tiempo de espera + +Aumenta el timeout o reduce el alcance: + +```bash +timeout 120 copilot --allow-all -p "Quick review of @$file - critical issues only" --silent +``` + +### Límites de tokens en archivos grandes + +Omite los archivos muy grandes: + +```bash +if [ $(wc -l < "$file") -lt 500 ]; then + copilot --allow-all -p "Review @$file" --silent +else + echo "Skipping $file (too large)" +fi +``` + +--- + +**[← Volver al Capítulo 07](../07-putting-it-together/README.md)** | **[Volver a los apéndices](README.md)** diff --git a/localization/ja-jp/05-skills/README.md b/localization/ja-jp/05-skills/README.md index 507316d4..c6ebefcb 100644 --- a/localization/ja-jp/05-skills/README.md +++ b/localization/ja-jp/05-skills/README.md @@ -1,4 +1,4 @@ -![第 05 章: スキルシステム](../../../images/chapter-header.png) +![第 05 章: スキルシステム](../../../05-skills/images/chapter-header.png) > **チームのベストプラクティスを毎回説明しなくても Copilot が自動的に適用してくれたら?** @@ -21,7 +21,7 @@ ## 🧩 現実世界のたとえ話: 電動工具 汎用ドリルは便利ですが、特化したアタッチメントで強力になります。 -電動工具 - スキルが Copilot の機能を拡張する +電動工具 - スキルが Copilot の機能を拡張する スキルも同様に機能します。ドリルビットを異なる作業に交換するように、異なるタスクのために Copilot にスキルを追加できます。 @@ -41,7 +41,7 @@ # スキルの仕組み -Copilot スキルを表す星空を背景に光のトレイルで繋がれた輝く RPG スタイルのスキルアイコン +Copilot スキルを表す星空を背景に光のトレイルで繋がれた輝く RPG スタイルのスキルアイコン スキルとは何か、なぜ重要か、エージェントや MCP とどう違うかを学びましょう。 @@ -137,7 +137,7 @@ Copilot に直接聞くことができます。 > *MCP についてはまだ心配しないでください。[第 06 章](../06-mcp-servers/README.md)でカバーします。スキルが全体像にどう合うかがわかるようにここに含まれています。* -エージェント、スキル、MCP サーバーの違いとワークフローへの組み合わせ方を示す比較図 +エージェント、スキル、MCP サーバーの違いとワークフローへの組み合わせ方を示す比較図 | 機能 | 何をするか | いつ使うか | |---------|--------------|-------------| @@ -192,7 +192,7 @@ copilot 3. チームの品質チェックリストを自動的に読み込む 4. リストアップしなくてもすべてのチェックを適用する -スキルの自動トリガー方法 - Copilot がプロンプトを正しいスキルと自動的に一致させる 4 ステップのフロー +スキルの自動トリガー方法 - Copilot がプロンプトを正しいスキルと自動的に一致させる 4 ステップのフロー *自然に聞くだけ。Copilot がプロンプトを正しいスキルと一致させ、自動的に適用します。* @@ -227,7 +227,7 @@ copilot
🎬 実際の動作を見てみましょう! -![スキルトリガーデモ](../../../images/skill-trigger-demo.gif) +![スキルトリガーデモ](../../../05-skills/images/skill-trigger-demo.gif) *デモの出力は異なります。モデル、ツール、レスポンスはここに表示されているものと異なります。* @@ -275,7 +275,7 @@ PR Review: feature/user-auth # カスタムスキルを作成する -スキルの作成と管理を表す輝く LEGO のようなブロックの壁を構築する人間とロボットの手 +スキルの作成と管理を表す輝く LEGO のようなブロックの壁を構築する人間とロボットの手 SKILL.md ファイルから独自のスキルを構築しましょう。 @@ -472,7 +472,7 @@ copilot --agent code-reviewer インストール済みスキルを見つけ、コミュニティスキルを探し、自分のスキルを共有しましょう。 -CLI スキルの発見、使用、作成、共有サイクルを示すスキルの管理と共有 +CLI スキルの発見、使用、作成、共有サイクルを示すスキルの管理と共有 --- @@ -516,7 +516,7 @@ Description: Security-focused code review checking OWASP Top 10 vulnerabilities
実際の動作を見てみましょう! -![スキルリストデモ](../../../images/list-skills-demo.gif) +![スキルリストデモ](../../../05-skills/images/list-skills-demo.gif) *デモの出力は異なります。モデル、ツール、レスポンスはここに表示されているものと異なります。* diff --git a/localization/ja-jp/06-mcp-servers/README.md b/localization/ja-jp/06-mcp-servers/README.md index c3174cfb..35a364e0 100644 --- a/localization/ja-jp/06-mcp-servers/README.md +++ b/localization/ja-jp/06-mcp-servers/README.md @@ -1,4 +1,4 @@ -![第 06 章: MCP サーバー](../../../images/chapter-header.png) +![第 06 章: MCP サーバー](../../../06-mcp-servers/images/chapter-header.png) > **Copilot がターミナルから GitHub のイシューを読んで、データベースをチェックして、PR を作成できたら?** @@ -24,7 +24,7 @@ ## 🧩 現実世界のたとえ話: ブラウザの拡張機能 -MCP サーバーはブラウザの拡張機能のようなもの +MCP サーバーはブラウザの拡張機能のようなもの MCP サーバーをブラウザの拡張機能と考えてください。ブラウザ単体でも Web ページを表示できますが、拡張機能で追加サービスに接続できます。 @@ -42,7 +42,7 @@ MCP サーバーをブラウザの拡張機能と考えてください。ブラ --- -浮かぶテックアイコンに囲まれた明るい電気スパークとともに接続する電源ケーブル、MCP サーバー接続を表す +浮かぶテックアイコンに囲まれた明るい電気スパークとともに接続する電源ケーブル、MCP サーバー接続を表す # クイックスタート: 30 秒で MCP を使う @@ -80,7 +80,7 @@ MCP Servers:
🎬 実際の動作を見てみましょう! -![MCP ステータスデモ](../../../images/mcp-status-demo.gif) +![MCP ステータスデモ](../../../06-mcp-servers/images/mcp-status-demo.gif) *デモの出力は異なります。モデル、ツール、レスポンスはここに表示されているものと異なります。* @@ -117,7 +117,7 @@ MCP により Copilot が実際の開発環境を把握できます。 # MCP サーバーの設定 -MCP サーバーの設定を表すプロフェッショナルなオーディオミキシングボードのノブとスライダーを調整する手 +MCP サーバーの設定を表すプロフェッショナルなオーディオミキシングボードのノブとスライダーを調整する手 MCP の動作を確認したので、追加のサーバーを設定しましょう。サーバーを追加する方法は 2 つあります: **組み込みレジストリから**(最も簡単 — CLI 内でガイドされたセットアップ)または**設定ファイルを手動で編集**(より柔軟)。どちらを選ぶか確信がない場合はレジストリオプションから始めましょう。 @@ -359,7 +359,7 @@ filesystem と Context7 サーバーを含む完全な `mcp-config.json` です MCP サーバーを設定したので、何ができるかを見てみましょう。 -MCP サーバーを使う - GitHub、Filesystem、Context7、カスタム/Web Fetch サーバーに接続された開発者 CLI を示すハブアンドスポーク図 +MCP サーバーを使う - GitHub、Filesystem、Context7、カスタム/Web Fetch サーバーに接続された開発者 CLI を示すハブアンドスポーク図 --- @@ -557,7 +557,7 @@ copilot これらのワークフローは、開発者が「もうこれなしでは働きたくない」と言う理由を示しています。各例は 1 つのセッションで複数の MCP サーバーを組み合わせています。 -MCP を使った issue から PR へのワークフロー - GitHub イシューの取得からプルリクエスト作成までの完全なフローを示す +MCP を使った issue から PR へのワークフロー - GitHub イシューの取得からプルリクエスト作成までの完全なフローを示す *完全な MCP ワークフロー: GitHub MCP がリポジトリデータを取得し、Filesystem MCP がコードを見つけ、Context7 MCP がベストプラクティスを提供し、Copilot が分析を処理する* @@ -617,7 +617,7 @@ Suggestions:
🎬 MCP ワークフローを実際に見てみましょう! -![MCP ワークフローデモ](../../../images/mcp-workflow-demo.gif) +![MCP ワークフローデモ](../../../06-mcp-servers/images/mcp-workflow-demo.gif) *デモの出力は異なります。モデル、ツール、レスポンスはここに表示されているものと異なります。* diff --git a/localization/ja-jp/07-putting-it-together/README.md b/localization/ja-jp/07-putting-it-together/README.md index f585deee..97a2e1fb 100644 --- a/localization/ja-jp/07-putting-it-together/README.md +++ b/localization/ja-jp/07-putting-it-together/README.md @@ -1,4 +1,4 @@ -![第 07 章: すべてをまとめる](../../../images/chapter-header.png) +![第 07 章: すべてをまとめる](../../../07-putting-it-together/images/chapter-header.png) > **学んだすべてがここで融合します。1 つのセッションでアイデアからマージされた PR へ。** @@ -21,7 +21,7 @@ ## 🧩 現実世界のたとえ話: オーケストラ -オーケストラのたとえ話 - 統合ワークフロー +オーケストラのたとえ話 - 統合ワークフロー 交響楽団には多くのセクションがあります: - **弦楽器**が基礎を提供する(コアワークフローのように) @@ -109,7 +109,7 @@ copilot # 追加ワークフロー -エージェント、スキル、MCP が統合ワークフローにどのように組み合わさるかを表すカラフルな巨大ジグソーパズルのピースとギアを組み立てる人々 +エージェント、スキル、MCP が統合ワークフローにどのように組み合わさるかを表すカラフルな巨大ジグソーパズルのピースとギアを組み立てる人々 第 04〜06 章を完了したパワーユーザー向けに、これらのワークフローはエージェント、スキル、MCP が効果をどのように乗数倍するかを示します。 @@ -117,7 +117,7 @@ copilot すべてを組み合わせるためのメンタルモデルです。 -統合パターン - 4 フェーズのワークフロー: コンテキストの収集(MCP)、分析と計画(エージェント)、実行(スキル + 手動)、完了(MCP) +統合パターン - 4 フェーズのワークフロー: コンテキストの収集(MCP)、分析と計画(エージェント)、実行(スキル + 手動)、完了(MCP) --- diff --git a/localization/ko-kr/00-quick-start/README.md b/localization/ko-kr/00-quick-start/README.md new file mode 100644 index 00000000..0a82cffd --- /dev/null +++ b/localization/ko-kr/00-quick-start/README.md @@ -0,0 +1,290 @@ +![챕터 00: 빠른 시작](../../../00-quick-start/images/chapter-header.png) + +환영합니다! 이 챕터에서는 GitHub Copilot CLI(Command Line Interface)를 설치하고 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"이 표시된다면 무료 옵션을 사용하거나, 플랜을 구독하거나, 액세스를 제공하는 조직에 참여해야 합니다. + +--- + +## 설치 + +> ⏱️ **시간 예상**: 설치는 2~5분이 걸립니다. 인증에는 1~2분이 추가됩니다. + +### GitHub Codespaces (설정 없이 바로 시작) + +사전 요건을 설치하고 싶지 않다면 GitHub Codespaces를 사용할 수 있습니다. GitHub Copilot CLI가 바로 사용 가능하며(로그인 필요), Python과 pytest도 미리 설치되어 있습니다. + +1. 이 저장소를 GitHub 계정으로 [포크합니다](https://github.com/github/copilot-cli-for-beginners/fork) +2. **Code** > **Codespaces** > **Create codespace on main** 선택 +3. 컨테이너가 빌드될 때까지 몇 분 기다립니다 +4. 준비 완료! 터미널이 Codespace 환경에서 자동으로 열립니다. + +> 💡 **Codespace에서 확인**: `cd samples/book-app-project && python book_app.py help`를 실행하여 Python과 샘플 앱이 작동하는지 확인하세요. + +### 로컬 설치 + +로컬 머신에서 강의 샘플과 함께 Copilot CLI를 실행하려면 아래 단계를 따르세요. + +1. 저장소를 클론하여 강의 샘플을 가져옵니다: + + ```bash + git clone https://github.com/github/copilot-cli-for-beginners + cd copilot-cli-for-beginners + ``` + +2. 다음 옵션 중 하나를 사용하여 Copilot CLI를 설치합니다. + + > 💡 **어떤 방법을 선택할지 모르겠다면?** Node.js가 설치되어 있다면 `npm`을 사용하세요. 그렇지 않다면 시스템에 맞는 옵션을 선택하세요. + + ### 모든 플랫폼 (npm) + + ```bash + # Node.js가 설치되어 있다면 빠르게 CLI를 가져오는 방법입니다 + npm install -g @github/copilot + ``` + + ### macOS/Linux (Homebrew) + + ```bash + brew install copilot-cli + ``` + + ### Windows (WinGet) + + ```bash + winget install GitHub.Copilot + ``` + + ### macOS/Linux (설치 스크립트) + + ```bash + curl -fsSL https://gh.io/copilot-install | bash + ``` + +
+선택 사항: 쉘 탭 완성 활성화 + +쉘 탭 완성을 사용하면 **Tab** 키를 눌러 `copilot` 서브커맨드, 옵션, 일부 옵션 값을 자동 완성할 수 있습니다. 선택 사항이지만 CLI에 익숙해지면 유용합니다. + +Copilot CLI는 현재 Bash, Zsh, Fish의 완성 스크립트를 지원합니다: + +```shell +# Bash, 현재 세션만 +source <(copilot completion bash) + +# Bash, Linux에서 영구 설정 +copilot completion bash | sudo tee /etc/bash_completion.d/copilot + +# Zsh +copilot completion zsh > "${fpath[1]}/_copilot" + +# Fish +copilot completion fish > ~/.config/fish/completions/copilot.fish +``` + +영구 완성을 추가한 후 쉘을 재시작하세요. Windows에서 PowerShell로 Copilot CLI를 실행할 수 있지만, `copilot completion`은 현재 Bash, Zsh, Fish만 지원합니다. + +
+ +--- + +## 인증 + +`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 인증이 완료됩니다.* + +**팁**: 로그인은 세션 간에 유지됩니다. 토큰이 만료되거나 명시적으로 로그아웃하지 않는 한 한 번만 하면 됩니다. + +--- + +## 동작 확인 + +### 1단계: Copilot CLI 테스트 + +로그인이 완료되었으면 Copilot CLI가 올바르게 작동하는지 확인해 봅시다. 아직 CLI를 시작하지 않았다면 터미널에서 시작하세요: + +```bash +> Say hello and tell me what you can help with +``` + +응답을 받은 후 CLI를 종료할 수 있습니다: + +```bash +> /exit +``` + +--- + +
+🎬 실제 동작 보기! + +![Hello Demo](../../../00-quick-start/images/hello-demo.gif) + +*데모 출력은 다를 수 있습니다. 모델, 도구, 응답은 여기 표시된 것과 다를 수 있습니다.* + +
+ +--- + +**예상 출력**: Copilot CLI의 기능을 나열하는 친절한 응답. + +### 2단계: 샘플 도서 앱 실행 + +강의에는 CLI를 사용하여 전체 강의 과정에서 탐색하고 개선할 샘플 앱이 제공됩니다 *(코드는 /samples/book-app-project에서 확인할 수 있습니다)*. 시작 전에 *Python 도서 컬렉션 터미널 앱*이 올바르게 작동하는지 확인하세요. 시스템에 따라 `python` 또는 `python3`을 실행합니다. + +> **참고:** 강의 전반에 걸쳐 Python(`samples/book-app-project`)을 기반으로 주요 예제를 보여 주므로, 로컬 설치를 선택한 경우 [Python 3.10+](https://www.python.org/downloads/)가 있어야 합니다(Codespace에는 이미 설치되어 있습니다). 원하는 언어가 다르다면 JavaScript(`samples/book-app-project-js`) 및 C#(`samples/book-app-project-cs`) 버전도 제공됩니다. 각 샘플에는 해당 언어로 앱을 실행하는 방법이 담긴 README가 있습니다. + +```bash +cd samples/book-app-project +python book_app.py list +``` + +**예상 출력**: "The Hobbit", "1984", "Dune" 등 5권의 도서 목록. + +### 3단계: 도서 앱으로 Copilot CLI 사용해 보기 + +2단계를 실행했다면 먼저 저장소 루트로 돌아오세요: + +```bash +cd ../.. # 필요한 경우 저장소 루트로 돌아오기 +copilot +> What does @samples/book-app-project/book_app.py do? +``` + +**예상 출력**: 도서 앱의 주요 기능과 명령어 요약. + +오류가 발생하면 아래 [문제 해결 섹션](#troubleshooting)을 확인하세요. + +완료되면 Copilot CLI를 종료할 수 있습니다: + +```bash +> /exit +``` + +--- + +## ✅ 준비 완료! + +설치가 끝났습니다. 챕터 01에서 본격적인 내용이 시작됩니다: + +- AI가 도서 앱을 검토하며 코드 품질 문제를 즉시 발견하는 과정 확인 +- Copilot CLI를 사용하는 세 가지 방식 학습 +- 일반 영어 설명으로 동작하는 코드 생성 + +**[챕터 01로 계속: 첫걸음 →](../01-setup-and-first-steps/README.md)** + +--- + +## 문제 해결 + +### "copilot: command not found" + +CLI가 설치되지 않았습니다. 다른 설치 방법을 시도해 보세요: + +```bash +# brew가 실패했다면 npm을 시도하세요: +npm install -g @github/copilot + +# 또는 설치 스크립트: +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)를 수동으로 방문하고 터미널에 표시된 코드를 입력하세요. + +### 토큰이 만료된 경우 + +`/login`을 다시 실행하면 됩니다: + +```bash +copilot +> /login +``` + +### 여전히 막혔나요? + +- [GitHub Copilot CLI 공식 문서](https://docs.github.com/copilot/concepts/agents/about-copilot-cli)를 확인하세요 +- [GitHub Issues](https://github.com/github/copilot-cli/issues)에서 검색해 보세요 + +--- + +## 🔑 핵심 요점 + +1. **GitHub Codespace는 빠르게 시작하는 방법입니다** - Python, pytest, GitHub Copilot CLI가 모두 미리 설치되어 바로 데모를 시작할 수 있습니다 +2. **다양한 설치 방법** - 시스템에 맞는 방법을 선택하세요 (Homebrew, WinGet, npm, 또는 설치 스크립트) +3. **일회성 인증** - 토큰이 만료될 때까지 로그인이 유지됩니다 +4. **도서 앱이 작동합니다** - 전체 강의 과정에서 `samples/book-app-project`를 사용합니다 + +> 📚 **공식 문서**: 설치 옵션 및 요구 사항은 [Copilot CLI 설치](https://docs.github.com/copilot/how-tos/copilot-cli/cli-getting-started)를 참조하세요. + +> 📋 **빠른 참조**: 전체 명령어 및 단축키 목록은 [GitHub Copilot CLI 명령어 참조](https://docs.github.com/en/copilot/reference/cli-command-reference)를 확인하세요. + +--- + +**[챕터 01로 계속: 첫걸음 →](../01-setup-and-first-steps/README.md)** diff --git a/localization/ko-kr/01-setup-and-first-steps/README.md b/localization/ko-kr/01-setup-and-first-steps/README.md new file mode 100644 index 00000000..1901927e --- /dev/null +++ b/localization/ko-kr/01-setup-and-first-steps/README.md @@ -0,0 +1,690 @@ +![챕터 01: 첫걸음](../../../01-setup-and-first-steps/images/chapter-header.png) + +> **AI가 버그를 즉시 발견하고, 혼란스러운 코드를 설명하고, 동작하는 스크립트를 생성하는 모습을 보세요. 그런 다음 GitHub Copilot CLI를 사용하는 세 가지 방식을 배워 보세요.** + +이 챕터에서 진정한 마법이 시작됩니다! 개발자들이 GitHub Copilot CLI를 "빠른 통화 한 통으로 시니어 엔지니어를 부르는 것"이라고 표현하는 이유를 직접 경험하게 됩니다. AI가 초 단위로 보안 버그를 발견하고, 복잡한 코드를 쉬운 영어로 설명하고, 즉시 동작하는 스크립트를 생성하는 모습을 보게 됩니다. 그런 다음 세 가지 상호작용 모드(Interactive, Plan, Programmatic)를 마스터하여 어떤 작업에 어떤 모드를 사용해야 하는지 정확히 알게 됩니다. + +> ⚠️ **사전 요건**: 아직 **[챕터 00: 빠른 시작](../00-quick-start/README.md)**을 완료하지 않았다면 먼저 완료하세요. 아래 데모를 실행하기 전에 GitHub Copilot CLI가 설치되고 인증되어 있어야 합니다. + +## 🎯 학습 목표 + +이 챕터를 마치면: + +- 직접 해보는 데모를 통해 GitHub Copilot CLI가 제공하는 생산성 향상을 경험합니다 +- 어떤 작업에 어떤 모드(Interactive, Plan, Programmatic)를 사용해야 하는지 선택할 수 있습니다 +- 슬래시 명령어로 세션을 제어할 수 있습니다 + +> ⏱️ **예상 시간**: 약 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 세션 안에서 입력하는 프롬프트입니다. `>` 접두사가 없는 줄은 터미널에서 실행하는 쉘 명령어입니다. + +> 💡 **예제 출력에 대하여**: 강의 전반에 걸쳐 표시되는 샘플 출력은 예시입니다. Copilot CLI의 응답은 매번 다르므로 단어, 형식, 세부 사항이 다를 수 있습니다. 정확한 텍스트보다는 반환되는 *정보의 유형*에 집중하세요. + +### 데모 1: 초 단위 코드 리뷰 + +강의에는 의도적인 코드 품질 문제가 있는 샘플 파일이 포함되어 있습니다. 로컬 머신에서 작업 중이며 아직 저장소를 클론하지 않았다면 아래 `git clone` 명령어를 실행하고 `copilot-cli-for-beginners` 폴더로 이동한 다음 `copilot` 명령어를 실행하세요. + +```bash +# 로컬에서 작업 중이며 아직 클론하지 않았다면 저장소를 클론하세요 +git clone https://github.com/github/copilot-cli-for-beginners +cd copilot-cli-for-beginners + +# Copilot 시작 +copilot +``` + +대화형 Copilot CLI 세션 안에서 다음을 실행하세요: + +``` +> Review @samples/book-app-project/book_app.py for code quality issues and suggest improvements +``` + +> 💡 **`@` 기호는 무엇에 사용되나요?** `@` 기호는 Copilot CLI에게 파일을 읽으라고 지시합니다. 챕터 02에서 자세히 배울 예정입니다. 지금은 명령어를 그대로 복사하세요. + +--- + +
+🎬 실제 동작 보기! + +![코드 리뷰 데모](../../../01-setup-and-first-steps/images/code-review-demo.gif) + +*데모 출력은 다를 수 있습니다. 모델, 도구, 응답은 여기 표시된 것과 다를 수 있습니다.* + +
+ +--- + +**핵심**: 몇 초 만에 전문적인 코드 리뷰가 완성됩니다. 수동 리뷰는... 그보다 훨씬 더 오래 걸립니다! + +--- + +### 데모 2: 혼란스러운 코드 설명 + +코드를 보면서 이게 무엇을 하는지 의아해한 적이 있나요? Copilot CLI 세션에서 이것을 시도해 보세요: + +``` +> Explain what @samples/book-app-project/books.py does in simple terms +``` + +--- + +
+🎬 실제 동작 보기! + +![코드 설명 데모](../../../01-setup-and-first-steps/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분을 구글링에 쓸 함수가 필요하신가요? 세션에서 계속: + +``` +> Write a Python function that takes a list of books and returns statistics: + total count, number read, number unread, oldest and newest book +``` + +--- + +
+🎬 실제 동작 보기! + +![코드 생성 데모](../../../01-setup-and-first-steps/images/generate-code-demo.gif) + +*데모 출력은 다를 수 있습니다. 모델, 도구, 응답은 여기 표시된 것과 다를 수 있습니다.* + +
+ +--- + +**결과**: 복사해서 즉시 실행할 수 있는 완전한 함수가 몇 초 만에 생성됩니다. + +완료되면 세션을 종료하세요: + +``` +> /exit +``` + +**핵심**: 즉각적인 결과, 그리고 전체 과정을 하나의 연속된 세션에서 진행했습니다. + +--- + +# 모드와 명령어 + +Copilot CLI 모드와 명령어를 나타내는 빛나는 화면, 다이얼, 이퀄라이저가 있는 미래적인 제어판 + +Copilot CLI가 무엇을 할 수 있는지 보았습니다. 이제 이러한 기능을 *효과적으로 사용하는 방법*을 이해해 봅시다. 핵심은 서로 다른 상황에 세 가지 상호작용 모드 중 어느 것을 사용할지 아는 것입니다. + +> 💡 **참고**: Copilot CLI에는 여러분의 입력을 기다리지 않고 작업을 수행하는 **Autopilot** 모드도 있습니다. 강력하지만 전체 권한 부여가 필요하고 프리미엄 요청을 자율적으로 사용합니다. 이 강의는 아래 세 가지 모드에 집중합니다. 기본에 익숙해지면 Autopilot을 안내해 드리겠습니다. + +--- + +## 🧩 실생활 비유: 외식하기 + +GitHub Copilot CLI를 사용하는 것을 외식하는 것에 비유해 보세요. 식당 계획부터 주문까지, 상황마다 다른 접근이 필요합니다: + +| 모드 | 외식 비유 | 사용 시기 | +|------|----------------|-------------| +| **Plan** | 식당까지 GPS 경로 | 복잡한 작업 - 경로를 파악하고, 경유지를 검토하고, 계획에 동의한 다음 출발 | +| **Interactive** | 웨이터와 대화 | 탐색 및 반복 - 질문하고, 조정하고, 실시간 피드백 받기 | +| **Programmatic** | 드라이브스루 주문 | 빠르고 구체적인 작업 - 환경에 머물면서 빠르게 결과 얻기 | + +외식과 마찬가지로 각 접근 방식이 언제 적합한지 자연스럽게 배우게 됩니다. + +GitHub Copilot CLI를 사용하는 세 가지 방법 - Plan 모드(식당까지 GPS 경로), Interactive 모드(웨이터와 대화), Programmatic 모드(드라이브스루) + +*작업에 따라 모드를 선택하세요: 계획이 먼저 필요할 때는 Plan, 대화형 협업에는 Interactive, 빠른 단발성 결과에는 Programmatic* + +### 어떤 모드로 시작해야 할까요? + +**Interactive 모드로 시작하세요.** +- 실험하고 후속 질문을 할 수 있습니다 +- 대화를 통해 컨텍스트가 자연스럽게 쌓입니다 +- 실수를 `/clear`로 쉽게 수정할 수 있습니다 + +익숙해지면 다음을 시도해 보세요: +- **Programmatic 모드** (`copilot -p "<프롬프트>"`) - 빠른 일회성 질문에 +- **Plan 모드** (`/plan`) - 코딩 전에 더 자세히 계획해야 할 때 + +--- + +## 세 가지 모드 + +### 모드 1: Interactive 모드 (여기서 시작하세요) + +Interactive 모드 - 질문에 답하고 주문을 조정할 수 있는 웨이터와 대화하는 것처럼 + +**최적 용도**: 탐색, 반복, 다중 회전 대화. 질문에 답하고, 피드백을 받고, 즉석에서 주문을 조정할 수 있는 웨이터와 대화하는 것과 같습니다. + +대화형 세션을 시작합니다: + +```bash +copilot +``` + +지금까지 보신 것처럼 자연스럽게 타이핑할 수 있는 프롬프트가 표시됩니다. 사용 가능한 명령어에 대한 도움말을 보려면 다음을 입력하세요: + +``` +> /help +``` + +**핵심 통찰**: Interactive 모드는 컨텍스트를 유지합니다. 실제 대화처럼 각 메시지가 이전 메시지를 기반으로 합니다. + +#### Interactive 모드 예제 + +```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: Plan 모드 + +Plan 모드 - GPS를 사용하여 여행 전에 경로를 계획하는 것처럼 + +**최적 용도**: 실행 전에 접근 방식을 검토하고 싶은 복잡한 작업. GPS를 사용하여 여행 전에 경로를 계획하는 것과 유사합니다. + +Plan 모드는 코드를 작성하기 전에 단계별 계획을 세우는 데 도움을 줍니다. `/plan` 명령어를 사용하거나 **Shift+Tab**을 눌러 Plan 모드로 전환하세요: + +```bash +copilot + +> /plan Add a "mark as read" command to the book app +``` + +> 💡 **팁**: **Shift+Tab**으로 Interactive → Plan → Autopilot 모드를 순환합니다. 대화형 세션 중 언제든지 눌러 명령어를 입력하지 않고도 모드를 전환할 수 있습니다. + +`--plan` 플래그를 사용하여 Copilot CLI를 plan 모드로 직접 시작할 수도 있습니다: + +```bash +copilot --plan +``` + +**Plan 모드 출력:** (여러분의 출력은 다를 수 있습니다) + +``` +📋 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] +``` + +**핵심 통찰**: Plan 모드를 사용하면 코드가 작성되기 전에 접근 방식을 검토하고 수정할 수 있습니다. 계획이 완료되면 나중을 위해 파일에 저장하도록 Copilot CLI에 지시할 수도 있습니다. 예를 들어 "Save this plan to `mark_as_read_plan.md`"라고 하면 계획 세부 사항이 담긴 마크다운 파일이 생성됩니다. + +> 💡 **더 복잡한 것을 원하시나요?** 이것을 시도해 보세요: `/plan Add search and filter capabilities to the book app`. Plan 모드는 간단한 기능부터 전체 애플리케이션까지 확장됩니다. + +> 📚 **Autopilot 모드**: Shift+Tab이 **Autopilot**이라는 세 번째 모드를 순환한다는 것을 눈치채셨을 수 있습니다. Autopilot 모드에서 Copilot은 각 단계마다 여러분의 입력을 기다리지 않고 전체 계획을 실행합니다 — 동료에게 작업을 넘기고 "완료되면 알려줘"라고 말하는 것과 같습니다. 일반적인 워크플로우는 plan → accept → autopilot이며, 먼저 계획을 잘 작성하는 능력이 필요합니다. `copilot --autopilot`으로 직접 autopilot으로 시작할 수도 있습니다. Interactive와 Plan 모드에 먼저 익숙해진 다음 준비가 되면 [공식 문서](https://docs.github.com/copilot/concepts/agents/copilot-cli/autopilot)를 참조하세요. + +--- + +### 모드 3: Programmatic 모드 + +Programmatic 모드 - 웨이터 없이 빠르게 주문하는 드라이브스루처럼 + +**최적 용도**: 자동화, 스크립트, 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?" +``` + +**핵심 통찰**: Programmatic 모드는 빠른 답변을 제공하고 종료합니다. 대화 없이 입력 → 출력만 있습니다. + +
+📚 더 나아가기: 스크립트에서 Programmatic 모드 사용 (클릭하여 펼치기) + +익숙해지면 쉘 스크립트에서 `-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 접근을 먼저 묻지 않고 수행하게 합니다. 대화형 세션이 없어 작업을 승인할 수 없는 programmatic 모드(`-p`)에서는 필요합니다. 직접 작성한 프롬프트와 신뢰할 수 있는 디렉터리에서만 `--allow-all`을 사용하세요. 신뢰할 수 없는 입력이나 민감한 디렉터리에서는 절대 사용하지 마세요. + +
+ +--- + +## 필수 슬래시 명령어 + +Copilot CLI를 시작할 때 처음 배우면 좋은 명령어들입니다: + +| 명령어 | 기능 | 사용 시기 | +|---------|--------------|-------------| +| `/ask` | 대화 기록에 영향을 주지 않고 빠른 질문 | 현재 작업을 방해하지 않고 빠른 답변이 필요할 때 | +| `/clear` | 대화를 지우고 새로 시작 | 주제를 전환할 때 | +| `/help` | 사용 가능한 모든 명령어 표시 | 명령어가 기억나지 않을 때 | +| `/model` | AI 모델 표시 또는 전환 | AI 모델을 변경하고 싶을 때 | +| `/plan` | 코딩 전에 작업 계획 수립 | 더 복잡한 기능에 | +| `/research` | GitHub 및 웹 소스를 사용한 심층 조사 | 코딩 전에 주제를 조사해야 할 때 | +| `/exit` | 세션 종료 | 완료되었을 때 | + +> 💡 **`/ask` vs 일반 채팅**: 일반적으로 보내는 모든 메시지는 진행 중인 대화의 일부가 되어 향후 응답에 영향을 줍니다. `/ask`는 "비공개" 단축키입니다 — 세션 컨텍스트를 오염시키지 않고 `/ask What does YAML mean?`처럼 빠른 일회성 질문에 적합합니다. + +> 💡 **탭 완성**: 슬래시 명령어를 입력할 때 **Tab** 키를 눌러 명령어 이름을 자동 완성하거나 사용 가능한 서브커맨드와 인수를 순환할 수 있습니다. 명령어의 정확한 이름이 기억나지 않을 때 특히 유용합니다. + +시작을 위해서는 이것으로 충분합니다! 익숙해지면 추가 명령어를 탐색할 수 있습니다. + +> 📚 **공식 문서**: 전체 명령어 및 플래그 목록은 [CLI 명령어 참조](https://docs.github.com/copilot/reference/cli-command-reference)를 참조하세요. + +
+📚 추가 명령어 (클릭하여 펼치기) + +> 💡 위의 필수 명령어로 일상적인 사용의 많은 부분을 커버할 수 있습니다. 이 참조는 더 탐색하고 싶을 때를 위한 것입니다. + +### 에이전트 환경 + +| 명령어 | 기능 | +|---------|--------------| +| `/agent` | 사용 가능한 에이전트 탐색 및 선택 | +| `/env` | 로드된 환경 세부 정보 표시 — 활성화된 지침, MCP 서버, 스킬, 에이전트, 플러그인 | +| `/init` | 저장소에 Copilot 지침 초기화 | +| `/mcp` | MCP 서버 구성 관리 | +| `/skills` | 향상된 기능을 위한 스킬 관리 | + +> 💡 에이전트는 [챕터 04](../04-agents-custom-instructions/README.md)에서, 스킬은 [챕터 05](../05-skills/README.md)에서, MCP 서버는 [챕터 06](../06-mcp-servers/README.md)에서 다룹니다. + +### 모델 및 서브에이전트 + +| 명령어 | 기능 | +|---------|--------------| +| `/delegate` | GitHub Copilot 클라우드 에이전트에 작업 위임 | +| `/fleet` | 복잡한 작업을 병렬 서브태스크로 분할하여 빠르게 완료 | +| `/model` | AI 모델 표시 또는 전환 | +| `/tasks` | 백그라운드 서브에이전트 및 분리된 쉘 세션 보기 | + +### 코드 + +| 명령어 | 기능 | +|---------|--------------| +| `/diff` | 현재 디렉터리의 변경 사항 검토 | +| `/pr` | 현재 브랜치의 풀 리퀘스트 작업 | +| `/research` | GitHub 및 웹 소스를 사용한 심층 조사 실행 | +| `/review` | 코드 리뷰 에이전트를 실행하여 변경 사항 분석 | +| `/terminal-setup` | 멀티라인 입력 지원 활성화 (shift+enter 및 ctrl+enter) | + +### 권한 + +| 명령어 | 기능 | +|---------|--------------| +| `/add-dir ` | 허용 목록에 디렉터리 추가 | +| `/allow-all [on\|off\|show]` | 모든 권한 프롬프트 자동 승인; `on`으로 활성화, `off`로 비활성화, `show`로 현재 상태 확인 | +| `/yolo` | `/allow-all on`의 단축키 — 모든 권한 프롬프트 자동 승인 | +| `/cwd`, `/cd [directory]` | 작업 디렉터리 보기 또는 변경 | +| `/list-dirs` | 허용된 모든 디렉터리 표시 | + +> ⚠️ **주의해서 사용하세요**: `/allow-all`과 `/yolo`는 확인 프롬프트를 건너뜁니다. 신뢰할 수 있는 프로젝트에는 좋지만 신뢰할 수 없는 코드에는 주의하세요. + +### 세션 + +| 명령어 | 기능 | +|---------|--------------| +| `/clear` | 현재 세션을 포기하고(기록 저장 없음) 새 대화 시작 | +| `/compact` | 컨텍스트 사용량 줄이기 위해 대화 요약 | +| `/context` | 컨텍스트 창 토큰 사용량 및 시각화 표시 | +| `/keep-alive` | Copilot CLI가 활성화되는 동안 시스템 절전 방지 — 노트북에서 장시간 작업 시 유용 | +| `/new` | 현재 세션을 종료하고(검색/재개를 위해 기록에 저장) 새 대화 시작 | +| `/resume` | 다른 세션으로 전환 (선택적으로 세션 ID 또는 이름 지정) | +| `/rename` | 현재 세션 이름 변경 (이름을 생략하면 자동 생성) | +| `/rewind` | 타임라인 선택기를 열어 대화의 이전 지점으로 되돌리기 | +| `/usage` | 세션 사용량 지표 및 통계 표시 | +| `/session` | 세션 정보 및 워크스페이스 요약 표시; `/session delete`, `/session delete `, `/session delete-all`로 세션 삭제 | +| `/share` | 세션을 마크다운 파일, GitHub gist, 또는 독립형 HTML 파일로 내보내기 | + +### 표시 + +| 명령어 | 기능 | +|---------|--------------| +| `/statusline` (또는 `/footer`) | 세션 하단 상태 표시줄에 표시할 항목 사용자 정의 (디렉터리, 브랜치, 노력, 컨텍스트 창, 할당량) | +| `/theme` | 터미널 테마 보기 또는 설정 | + +### 도움말 및 피드백 + +| 명령어 | 기능 | +|---------|--------------| +| `/changelog` | CLI 버전의 변경 로그 표시 | +| `/feedback` | GitHub에 피드백 제출 | +| `/help` | 사용 가능한 모든 명령어 표시 | + +### 빠른 쉘 명령어 + +`!` 접두사를 사용하여 AI를 거치지 않고 쉘 명령어를 직접 실행합니다: + +```bash +copilot + +> !git status +# AI를 거치지 않고 git status를 직접 실행 + +> !python -m pytest tests/ +# pytest를 직접 실행 +``` + +### 모델 전환 + +Copilot CLI는 OpenAI, Anthropic, Google 등의 여러 AI 모델을 지원합니다. 사용 가능한 모델은 구독 수준과 지역에 따라 다릅니다. `/model`을 사용하여 옵션을 확인하고 전환하세요: + +```bash +copilot +> /model + +# 사용 가능한 모델을 표시하고 선택할 수 있습니다. Sonnet 4.5를 선택하세요. +``` + +> 💡 **팁**: 일부 모델은 다른 것보다 더 많은 "프리미엄 요청"을 소비합니다. **1x**로 표시된 모델(Claude Sonnet 4.5 등)은 훌륭한 기본값입니다. 유능하고 효율적입니다. 배수가 높은 모델은 프리미엄 요청 할당량을 더 빠르게 사용하므로 정말 필요할 때를 위해 아껴 두세요. + +> 💡 **어떤 모델을 선택해야 할지 모르겠나요?** 모델 선택기에서 **`Auto`**를 선택하면 Copilot이 각 세션에 가장 적합한 모델을 자동으로 선택합니다. 시작 단계이고 모델 선택에 대해 고민하고 싶지 않다면 훌륭한 기본값입니다. + +
+ +--- + +# 실습 + +코드가 표시된 모니터, 램프, 커피잔, 헤드폰이 있는 아늑한 책상 설정 + +배운 내용을 실제로 적용할 시간입니다. + +--- + +## ▶️ 직접 해보기 + +### Interactive 탐색 + +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 + +# 계획 검토 +# 승인 또는 수정 +# 단계별 구현 지켜보기 +``` + +### Programmatic 모드로 자동화 + +`-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. **Interactive 챌린지**: `copilot`을 시작하고 도서 앱을 탐색하세요. `@samples/book-app-project/books.py`에 대해 묻고 연속으로 3번 개선을 요청하세요. + +2. **Plan 모드 챌린지**: `/plan Add rating and review features to the book app`을 실행하세요. 계획을 꼼꼼히 읽어 보세요. 이해가 되나요? + +3. **Programmatic 챌린지**: `copilot --allow-all -p "List all functions in @samples/book-app-project/book_app.py and describe what each does"`를 실행하세요. 처음 시도에 잘 됐나요? + +--- + +## 💡 팁: 웹이나 모바일에서 CLI 세션 제어하기 + +GitHub Copilot CLI는 **원격 세션**을 지원합니다. 터미널에 물리적으로 있지 않아도 웹 브라우저(데스크톱 또는 모바일)나 GitHub Mobile 앱에서 실행 중인 CLI 세션을 모니터링하고 상호작용할 수 있습니다. + +`--remote` 플래그로 원격 세션을 시작합니다: + +```bash +copilot --remote +``` + +Copilot CLI가 링크를 표시하고 QR 코드에 접근할 수 있게 합니다. 휴대폰이나 데스크톱 브라우저 탭에서 링크를 열어 실시간으로 세션을 확인하고, 후속 프롬프트를 전송하고, 계획을 검토하고, 원격으로 에이전트를 조종하세요. 세션은 사용자별이므로 자신의 Copilot CLI 세션에만 접근할 수 있습니다. + +활성 세션 안에서 언제든지 원격 액세스를 활성화할 수도 있습니다: + +``` +> /remote +``` + +원격 세션에 대한 추가 세부 정보는 [Copilot CLI 공식 문서](https://docs.github.com/copilot/how-tos/copilot-cli/steer-remotely)에서 찾을 수 있습니다. + +--- + +## 📝 과제 + +### 메인 챌린지: 도서 앱 유틸리티 개선 + +실습 예제는 `book_app.py` 검토 및 리팩토링에 집중했습니다. 이제 다른 파일인 `utils.py`에서 동일한 기술을 연습해 보세요: + +1. 대화형 세션 시작: `copilot` +2. 파일 요약 요청: "Summarize @samples/book-app-project/utils.py and explain what each function in this file does" +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. 독스트링 요청: "Add a comprehensive docstring to `get_book_details()` with parameter descriptions and return values" +6. 컨텍스트가 프롬프트 간에 유지되는 방식을 관찰하세요. 각 개선이 이전 것을 기반으로 합니다 +7. `/exit`로 종료 + +**성공 기준**: 여러 단계의 대화를 통해 입력 유효성 검사, 오류 처리, 독스트링이 포함된 개선된 `utils.py`가 완성됩니다. + +
+💡 힌트 (클릭하여 펼치기) + +**시도할 샘플 프롬프트:** +```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. **Interactive**: `copilot` → 단계별로 메서드를 설계하고 구축하도록 요청 +2. **Plan**: `/plan Add a list_by_year(start, end) method to BookCollection that filters books by publication year range` +3. **Programmatic**: `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` 호출은 이전 호출의 기억이 없는 독립적인 것 | 컨텍스트를 쌓는 대화에는 interactive 모드(`copilot`) 사용 | +| `$`나 `!`가 포함된 프롬프트에 따옴표 없이 사용 | 쉘이 Copilot CLI가 보기 전에 특수 문자를 해석 | 프롬프트를 따옴표로 감싸세요: `copilot -p "What does $HOME mean?"` | +| Esc를 한 번 눌러 실행 중인 작업 취소 | 단일 Esc는 더 이상 진행 중인 작업을 취소하지 않음(실수 방지) | Copilot CLI가 처리 중일 때 취소하려면 **Esc를 두 번** 누르세요 | + +### 문제 해결 + +**"Model not available"** - 구독에 모든 모델이 포함되지 않을 수 있습니다. `/model`을 사용하여 사용 가능한 것을 확인하세요. + +**"Context too long"** - 대화가 전체 컨텍스트 창을 사용했습니다. `/clear`를 사용하여 리셋하거나 새 세션을 시작하세요. + +**"Rate limit exceeded"** - 몇 분 기다렸다가 다시 시도하세요. 딜레이를 포함한 배치 작업에는 programmatic 모드를 사용하는 것을 고려하세요. + +
+ +--- + +# 요약 + +## 🔑 핵심 요점 + +1. **Interactive 모드**는 탐색 및 반복에 적합합니다 - 컨텍스트가 이어집니다. 지금까지 한 말을 기억하는 사람과 대화하는 것과 같습니다. +2. **Plan 모드**는 일반적으로 더 복잡한 작업에 사용됩니다. 구현 전에 검토하세요. +3. **Programmatic 모드**는 자동화에 사용됩니다. 상호작용이 필요 없습니다. +4. **필수 명령어** (`/ask`, `/help`, `/clear`, `/plan`, `/research`, `/model`, `/exit`)로 대부분의 일상 사용이 가능합니다. + +> 📋 **빠른 참조**: 전체 명령어 및 단축키 목록은 [GitHub Copilot CLI 명령어 참조](https://docs.github.com/en/copilot/reference/cli-command-reference)를 확인하세요. + +--- + +## ➡️ 다음 단계 + +세 가지 모드를 이해했으니 이제 Copilot CLI에 코드에 대한 컨텍스트를 제공하는 방법을 배워 봅시다. + +**[챕터 02: 컨텍스트와 대화](../02-context-conversations/README.md)**에서 배울 내용: + +- 파일과 디렉터리를 참조하는 `@` 문법 +- `--resume`과 `--continue`를 사용한 세션 관리 +- 컨텍스트 관리가 Copilot CLI를 진정으로 강력하게 만드는 방법 + +--- + +**[← 강의 홈으로](../README.md)** | **[챕터 02로 계속 →](../02-context-conversations/README.md)** diff --git a/localization/ko-kr/02-context-conversations/README.md b/localization/ko-kr/02-context-conversations/README.md new file mode 100644 index 00000000..a3f432f6 --- /dev/null +++ b/localization/ko-kr/02-context-conversations/README.md @@ -0,0 +1,909 @@ +![2장: 컨텍스트와 대화](../../../02-context-conversations/images/chapter-header.png) + +> **AI가 한 번에 한 파일이 아니라 코드베이스 전체를 볼 수 있다면 어떨까요?** + +이번 장에서는 GitHub Copilot CLI의 진짜 힘인 **컨텍스트**를 이끌어 냅니다. `@` 구문을 사용해 파일과 디렉터리를 참조하고, Copilot CLI가 여러분의 코드베이스를 깊이 이해하도록 만드는 방법을 배웁니다. 또한 세션 간 대화를 유지하는 방법, 며칠 뒤에도 정확히 멈췄던 지점에서 다시 작업을 이어 가는 방법, 그리고 단일 파일 리뷰로는 절대 잡아낼 수 없는 버그를 교차 파일 분석으로 발견하는 모습을 함께 살펴봅니다. + +## 🎯 학습 목표 + +이번 장을 마치면 다음을 할 수 있습니다. + +- `@` 구문을 사용해 파일, 디렉터리, 이미지를 참조합니다. +- `--resume`과 `--continue`로 이전 세션을 다시 이어 갑니다. +- [컨텍스트 윈도우](../../../GLOSSARY.md#context-window)가 어떻게 동작하는지 이해합니다. +- 효과적인 멀티턴 대화를 작성합니다. +- 멀티 프로젝트 워크플로를 위한 디렉터리 권한을 관리합니다. + +> ⏱️ **예상 소요 시간**: 약 50분 (읽기 20분 + 실습 30분) + +--- + +## 🧩 실생활 비유: 동료와 함께 일하기 + +컨텍스트가 만드는 차이 - 컨텍스트가 없을 때와 있을 때 + +*동료와 마찬가지로 Copilot CLI도 마음을 읽지는 못합니다. 더 많은 정보를 제공하면 사람도, Copilot도 더 정확한 도움을 줄 수 있습니다!* + +버그를 동료에게 설명한다고 상상해 보세요. + +> **컨텍스트 없이**: "북 앱이 동작하지 않아요." + +> **컨텍스트와 함께**: "`books.py`, 특히 `find_book_by_title` 함수를 봐 주세요. 대소문자 구분 없는 매칭이 안 되고 있어요." + +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 +``` + +--- + +
+🎬 실제로 동작하는 모습 보기! + +![파일 컨텍스트 데모](../../../02-context-conversations/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 +``` + +--- + +## 교차 파일 인텔리전스 + +여기서부터 컨텍스트는 진짜 슈퍼파워가 됩니다. 단일 파일 분석도 유용하지만, 교차 파일 분석은 차원이 다릅니다. + +교차 파일 인텔리전스 - 단일 파일 분석과 교차 파일 분석을 비교하여, 파일을 함께 분석할 때 단일 파일에서는 보이지 않던 버그, 데이터 흐름, 패턴이 드러나는 모습 + +### 데모: 여러 파일에 걸친 버그 찾기 + +```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 +> ``` + +--- + +
+🎬 실제로 동작하는 모습 보기! + +![멀티 파일 데모](../../../02-context-conversations/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가 이미 본 코드를 통해 흐름을 추적할 수 있습니다 +``` + +
+🎬 멀티턴 대화가 실제로 동작하는 모습 보기! + +![멀티턴 데모](../../../02-context-conversations/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 + +# 또는 세션에 부여한 이름으로 이어 가기 +copilot --resume="my book app review" +``` + +> 💡 **세션 ID는 어떻게 찾나요?** 외울 필요 없습니다. ID 없이 `copilot --resume`을 실행하면 이전 세션의 이름, ID, 마지막 활동 시점이 대화형 목록으로 표시됩니다. 원하는 항목을 고르기만 하면 됩니다. +> +> **여러 터미널은 어떻게 처리되나요?** 각 터미널 창은 자체 컨텍스트를 가진 별도의 세션입니다. Copilot CLI를 세 개의 터미널에서 열어 두었다면, 그것은 세 개의 별도 세션입니다. 어느 터미널에서든 `--resume`을 실행하면 모두 둘러볼 수 있습니다. `--continue` 플래그는 현재 작업 디렉터리의 세션을 우선 가져오고, 거기에 세션이 없으면 가장 최근에 활동한 세션을 선택합니다. +> +> **재시작하지 않고 세션을 전환할 수 있나요?** 네. 활성 세션 안에서 `/resume` 슬래시 명령을 사용하세요. +> ``` +> > /resume +> # 전환할 세션 목록을 보여 줍니다 +> ``` + +### 세션 정리하기 + +나중에 찾을 수 있도록 세션에 의미 있는 이름을 부여하세요. 세션을 시작할 때 이름을 지정할 수도 있고, 세션 안에서 언제든 이름을 바꿀 수도 있습니다. + +```bash +# 세션을 시작할 때 바로 이름 지정 +copilot --name book-app-review + +# 또는 세션 안에서 현재 세션 이름 변경 +copilot + +> /rename book-app-review +# 식별이 쉽도록 세션 이름이 변경되었습니다 +``` + +세션에 이름이 부여되면 목록을 뒤지지 않고 이름으로 바로 이어 갈 수 있습니다. + +```bash +copilot --resume=book-app-review +``` + +더 이상 필요하지 않은 세션은 세션 안에서 `/session delete`로 정리할 수 있습니다. + +```bash +copilot + +> /session delete # 현재 세션 삭제 +> /session delete abc123 # 특정 ID의 세션 삭제 +> /session delete-all # 모든 세션 삭제 (신중하게 사용하세요!) +``` + +### 컨텍스트 확인 및 관리 + +파일과 대화를 계속 추가하다 보면 Copilot CLI의 [컨텍스트 윈도우](../../../GLOSSARY.md#context-window)가 점점 채워집니다. 이를 통제할 수 있도록 다음과 같은 명령들이 제공됩니다. + +```bash +copilot + +> /context +Context usage: 62k/200k tokens (31%) + +> /clear +# 현재 세션을 폐기(히스토리 저장 안 함)하고 새 대화를 시작합니다 + +> /new +# 현재 세션을 종료(검색/이어가기를 위해 히스토리에 저장)하고 새 대화를 시작합니다 + +> /rewind +# 타임라인 선택기를 열어 대화의 이전 시점으로 되돌릴 수 있게 합니다 +``` + +> 💡 **`/clear` 또는 `/new`를 언제 사용해야 하나요?** books.py를 리뷰하다가 utils.py로 주제를 옮기고 싶다면 먼저 `/new`를 실행하세요(세션 히스토리가 필요 없다면 `/clear`). 그렇지 않으면 이전 주제의 오래된 컨텍스트가 응답을 혼란스럽게 만들 수 있습니다. + +> 💡 **실수했거나 다른 접근 방식을 시도하고 싶나요?** `/rewind`를 사용하거나 Esc를 두 번 누르면 **타임라인 선택기**가 열려, 가장 최근 시점뿐 아니라 대화의 어느 지점으로든 되돌아갈 수 있습니다. 잘못된 길로 들어섰을 때 처음부터 다시 시작하지 않고 되돌아가고 싶을 때 유용합니다. + +--- + +### 멈췄던 지점에서 이어 가기 + +GitHub Copilot CLI 세션이 며칠에 걸쳐 어떻게 유지되는지 보여 주는 타임라인 - 월요일에 시작해 수요일에 전체 컨텍스트를 복원하며 다시 이어 가는 모습 + +*세션은 종료할 때 자동으로 저장됩니다. 며칠 뒤에 다시 열어도 파일, 이슈, 진행 상황까지 전체 컨텍스트가 그대로 복원됩니다.* + +여러 날에 걸친 다음 워크플로를 상상해 보세요. + +```bash +# 월요일: 처음부터 이름을 부여해 북 앱 리뷰 시작 +copilot --name 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 --resume=book-app-review + +> 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는 다음을 기억합니다. +- 작업 중이던 정확한 파일 +- 번호가 매겨진 이슈 목록 +- 이미 처리한 항목 +- 대화의 맥락 + +다시 설명할 필요도, 파일을 다시 읽을 필요도 없습니다. 그냥 이어서 작업하면 됩니다. + +--- + +**🎉 이제 핵심을 모두 익혔습니다!** `@` 구문, 세션 관리(`--name`/`--continue`/`--resume`/`/rename`), 컨텍스트 명령(`/context`/`/clear`)만으로도 매우 생산적으로 일할 수 있습니다. 아래 내용은 모두 선택 사항입니다. 준비가 되었을 때 다시 돌아오세요. + +--- + +# 선택: 더 깊이 들어가기 + +컨텍스트 개념을 더 깊이 탐험하는 모습을 표현한, 푸른빛과 보랏빛이 도는 추상적인 크리스털 동굴 + +이 주제들은 위의 핵심 내용을 토대로 합니다. **관심 가는 것을 선택하거나, [실습](#practice)으로 바로 건너뛰어도 됩니다.** + +| 알고 싶은 주제... | 이동 | +|---|---| +| 와일드카드 패턴과 고급 세션 명령 | [추가 @ 패턴 및 세션 명령](#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 +# 세션을 마크다운 파일로 내보냅니다 + +> /share gist +# 세션으로 GitHub gist를 생성합니다 + +> /share html +# 세션을 단독 실행 가능한 인터랙티브 HTML 파일로 내보냅니다 +# 동료와 다듬어진 세션 리포트를 공유하거나 참고용으로 저장할 때 유용합니다 +``` + +
+ +
+컨텍스트 인지 대화 + + +### 컨텍스트 인지 대화 + +진짜 마법은 서로의 결과 위에 쌓이는 멀티턴 대화에서 일어납니다. + +#### 예제: 점진적 개선 + +```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` | 관련 없는 컨텍스트 제거 | +| 잘못된 방향으로 진행 | `/rewind` | 어느 시점으로든 되돌리기 | +| 긴 대화 | `/compact` | 히스토리 요약, 토큰 확보 | +| 특정 파일이 필요할 때 | `@folder/`가 아니라 `@file.py` | 필요한 것만 로드 | +| 한계에 부딪힐 때 | `/new` 또는 `/clear` | 새로운 컨텍스트 | +| 여러 주제 다룰 때 | 주제별로 `/rename` 사용 | 올바른 세션을 쉽게 이어 가기 | + +#### 대규모 코드베이스를 위한 모범 사례 + +1. **구체적으로**: `@samples/book-app-project/` 대신 `@samples/book-app-project/books.py` +2. **주제 사이에 컨텍스트 정리**: 초점이 바뀔 때 `/new` 또는 `/clear` 사용 +3. **`/compact` 사용**: 대화를 요약해 컨텍스트 확보 +4. **여러 세션 활용**: 기능이나 주제별로 세션을 하나씩 + +
+ +
+참조할 대상 고르기 + + +### 참조할 대상 고르기 + +컨텍스트 측면에서 모든 파일이 동등하지는 않습니다. 현명하게 고르는 방법을 알아봅시다. + +#### 파일 크기 고려 사항 + +| 파일 크기 | 대략적인 [토큰](../../../GLOSSARY.md#token) | 전략 | +|-----------|-------------------|----------| +| 작음 (<100줄) | 약 500~1,500 토큰 | 자유롭게 참조 | +| 중간 (100~500줄) | 약 1,500~7,500 토큰 | 특정 파일 위주로 참조 | +| 큼 (500줄 이상) | 7,500+ 토큰 | 선별적으로, 특정 파일 위주 | +| 매우 큼 (1000줄 이상) | 15,000+ 토큰 | 분할하거나 섹션을 노려 참조 고려 | + +**구체적인 예시:** +- 북 앱의 Python 파일 4개를 합치면 약 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 디렉터리 +- 큰 데이터 파일이나 픽스처 +- 질문과 무관한 파일 + +#### 구체성 스펙트럼 + +``` +Less specific ────────────────────────► More specific +@samples/book-app-project/ @samples/book-app-project/books.py:47-52 + │ │ + └─ Scans everything └─ Just what you need + (uses more context) (preserves context) +``` + +**넓게 갈 때** (`@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.md#working-with-images)을 참고하세요. + +
+ +--- + +# 실습 + +모니터에 코드가 떠 있고, 램프, 커피 잔, 헤드폰이 놓인 따뜻한 분위기의 데스크 셋업 - 실습 준비가 된 모습 + +배운 컨텍스트와 세션 관리 기술을 적용해 볼 시간입니다. + +--- + +## ▶️ 직접 해 보기 + +### 전체 프로젝트 리뷰 + +이 코스에는 바로 리뷰해 볼 수 있는 샘플 파일이 포함되어 있습니다. copilot을 시작한 뒤 다음 프롬프트를 실행해 보세요. + +```bash +copilot + +> @samples/book-app-project/ Give me a code quality review of this project + +# Copilot CLI가 다음과 같은 이슈를 식별합니다: +# - 중복된 표시(display) 함수 +# - 누락된 입력 검증 +# - 일관성 없는 오류 처리 +``` + +> 💡 **자신의 파일로 시도해 보고 싶나요?** 작은 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. **세션은 자동 저장**됩니다: 시작 시 `--name`으로 이름을 부여하고, `--resume=`으로 이름으로 이어 가거나, `--continue`로 가장 최근 세션을 이어 갑니다. +4. **컨텍스트 윈도우**에는 한계가 있습니다: `/clear`, `/compact`, `/context`, `/new`, `/rewind`로 관리하세요. +5. **권한 플래그**(`--add-dir`, `--allow-all`)로 멀티 디렉터리 접근을 통제합니다. 신중하게 사용하세요! +6. **이미지 참조**(`@screenshot.png`)는 UI 이슈를 시각적으로 디버깅하는 데 도움이 됩니다. + +> 📚 **공식 문서**: 컨텍스트, 세션, 파일 작업에 대한 전체 레퍼런스는 [Use 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에 컨텍스트를 제공할 수 있게 되었으니, 실제 개발 작업에 활용해 봅시다. 방금 배운 컨텍스트 기술(파일 참조, 교차 파일 분석, 세션 관리)은 다음 장의 강력한 워크플로의 토대가 됩니다. + +**[3장: 개발 워크플로](../03-development-workflows/README.md)** 에서는 다음을 배웁니다. + +- 코드 리뷰 워크플로 +- 리팩터링 패턴 +- 디버깅 지원 +- 테스트 생성 +- Git 통합 + +--- + +**[← 1장으로 돌아가기](../01-setup-and-first-steps/README.md)** | **[3장으로 계속하기 →](../03-development-workflows/README.md)** diff --git a/localization/ko-kr/03-development-workflows/README.md b/localization/ko-kr/03-development-workflows/README.md new file mode 100644 index 00000000..c4885ded --- /dev/null +++ b/localization/ko-kr/03-development-workflows/README.md @@ -0,0 +1,972 @@ +![Chapter 03: 개발 워크플로](../../../03-development-workflows/images/chapter-header.png) + +> **AI가 여러분이 미처 묻지도 않은 버그를 찾아낼 수 있다면 어떨까요?** + +이번 챕터에서는 GitHub Copilot CLI가 여러분의 일상 도구가 됩니다. 매일 의존하고 있는 워크플로(테스팅, 리팩터링, 디버깅, Git) 안에서 Copilot CLI를 직접 사용해 봅니다. + +## 🎯 학습 목표 + +이 챕터를 마치면 다음과 같은 일을 할 수 있게 됩니다. + +- Copilot CLI로 종합적인 코드 리뷰 수행하기 +- 레거시 코드를 안전하게 리팩터링하기 +- AI의 도움으로 이슈 디버깅하기 +- 자동으로 테스트 생성하기 +- Copilot CLI를 git 워크플로에 통합하기 + +> ⏱️ **예상 소요 시간**: 약 60분 (읽기 15분 + 실습 45분) + +--- + +## 🧩 실생활 비유: 목수의 워크플로 + +목수는 단순히 도구 사용법만 아는 것이 아니라, 작업별로 *워크플로*를 가지고 있습니다. + +가구 만들기(측정, 절단, 조립, 마감), 손상 수리(평가, 제거, 수리, 매칭), 품질 점검(검사, 접합부 테스트, 정렬 확인) 세 가지 워크플로 레인을 보여 주는 장인의 작업장 + +마찬가지로 개발자도 작업별로 워크플로를 가지고 있습니다. GitHub Copilot CLI는 이러한 각 워크플로를 향상시켜 일상적인 코딩 작업에서 더욱 효율적이고 효과적으로 일할 수 있도록 도와줍니다. + +--- + +# 다섯 가지 워크플로 + +코드 리뷰, 테스팅, 디버깅, 리팩터링, git 통합 워크플로를 나타내는 다섯 개의 빛나는 네온 아이콘 + +아래 각 워크플로는 독립적으로 구성되어 있습니다. 현재 필요한 것을 골라 보거나, 전체를 차례대로 진행해 보세요. + +--- + +## 원하는 길을 선택하세요 + +이 챕터에서는 개발자가 일반적으로 사용하는 다섯 가지 워크플로를 다룹니다. **하지만 한 번에 전부 읽을 필요는 없습니다!** 각 워크플로는 아래 접을 수 있는 섹션 안에 독립적으로 들어 있습니다. 필요한 것, 그리고 현재 프로젝트에 가장 잘 맞는 것을 골라 보세요. 나머지는 나중에 다시 돌아와서 살펴봐도 됩니다. + +코드 리뷰, 리팩터링, 디버깅, 테스트 생성, Git 통합의 다섯 가지 개발 워크플로를 가로형 스윔레인으로 표현 + +| 하고 싶은 일 | 이동하기 | +|---|---| +| 머지 전에 코드 리뷰하기 | [Workflow 1: Code Review](#workflow-1-code-review) | +| 지저분하거나 오래된 코드 정리하기 | [Workflow 2: Refactoring](#workflow-2-refactoring) | +| 버그를 추적하고 수정하기 | [Workflow 3: Debugging](#workflow-3-debugging) | +| 코드에 대한 테스트 생성하기 | [Workflow 4: Test Generation](#workflow-4-test-generation) | +| 더 나은 커밋과 PR 작성하기 | [Workflow 5: Git Integration](#workflow-5-git-integration) | +| 코딩 전에 리서치하기 | [Quick Tip: Research Before You Plan or Code](#quick-tip-research-before-you-plan-or-code) | +| 처음부터 끝까지 버그 수정 워크플로 살펴보기 | [Putting It All Together](#putting-it-all-together-bug-fix-workflow) | + +**아래에서 워크플로를 선택해 펼쳐 보고**, 해당 영역에서 GitHub Copilot CLI가 개발 과정을 어떻게 향상시키는지 확인해 보세요. + +--- + + +
+Workflow 1: Code Review - 파일 리뷰, /review 에이전트 사용, 심각도 체크리스트 작성 + +코드 리뷰 워크플로: 리뷰, 이슈 식별, 우선순위 지정, 체크리스트 생성 + +### 기본 리뷰 + +이 예제에서는 `@` 기호를 사용해 파일을 참조함으로써, Copilot CLI가 리뷰를 위해 파일 내용에 직접 접근할 수 있도록 합니다. + +```bash +copilot + +> Review @samples/book-app-project/book_app.py for code quality +``` + +--- + +
+🎬 실제 동작 보기! + +![Code Review Demo](../../../03-development-workflows/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 provides detailed review + +> The user input handling - are there any edge cases I'm missing? + +# Copilot CLI shows potential issues with empty strings, special characters + +> Create a checklist of all issues found, prioritized by severity + +# Copilot CLI generates prioritized action items +``` + +### 리뷰 체크리스트 템플릿 + +Copilot CLI에게 출력 형식을 명시적으로 요청해 보세요(여기서는 이슈에 그대로 붙여넣을 수 있는 심각도별 markdown 체크리스트). + +```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에서의 두 가지 변경 유형을 이해해야 합니다. + +| 변경 유형 | 의미 | 확인 방법 | +|-------------|---------------|------------| +| **Staged 변경** | `git add`로 다음 커밋에 포함하도록 표시한 파일 | `git diff --staged` | +| **Unstaged 변경** | 수정했지만 아직 추가하지 않은 파일 | `git diff` | + +```bash +# Quick reference +git status # Shows both staged and unstaged +git add file.py # Stage a file for commit +git diff # Shows unstaged changes +git diff --staged # Shows staged changes +``` + +### /review 명령 사용하기 + +`/review` 명령은 내장된 **code-review 에이전트**를 호출하며, 이 에이전트는 staged/unstaged 변경 사항을 신호 대 잡음비가 높은 출력으로 분석하도록 최적화되어 있습니다. 자유 형식의 프롬프트를 작성하는 대신 슬래시 명령을 사용해 전문화된 내장 에이전트를 트리거하세요. + +```bash +copilot + +> /review +# Invokes the code-review agent on staged/unstaged changes +# Provides focused, actionable feedback + +> /review Check for security issues in authentication +# Run review with specific focus area +``` + +> 💡 **팁**: code-review 에이전트는 변경 사항이 대기 중일 때 가장 잘 동작합니다. `git add`로 파일을 스테이징하면 더 집중된 리뷰를 받을 수 있습니다. + +
+ +--- + + +
+Workflow 2: Refactoring - 코드 재구성, 관심사 분리, 에러 처리 개선 + +리팩터링 워크플로: 코드 평가, 변경 계획, 구현, 동작 검증 + +### 간단한 리팩터링 + +> **먼저 이것부터 시도해 보세요:** `@samples/book-app-project/book_app.py The command handling uses if/elif chains. Refactor it to use a dictionary dispatch pattern.` + +간단한 개선부터 시작하세요. book 앱에서 다음을 시도해 보세요. 각 프롬프트는 `@` 파일 참조와 구체적인 리팩터링 지시를 함께 사용해, 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 +``` + +> 💡 **리팩터링이 처음이신가요?** 복잡한 변형을 시도하기 전에 type hint 추가나 변수명 개선처럼 간단한 요청부터 시작해 보세요. + +--- + +
+🎬 실제 동작 보기! + +![Refactor Demo](../../../03-development-workflows/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 + +# Get tests first + +> Now refactor the BookCollection class to use a context manager for file operations + +# Refactor with confidence - tests verify behavior is preserved +``` + +
+ +--- + + +
+Workflow 3: Debugging - 버그 추적, 보안 감사, 파일 간 이슈 추적 + +디버깅 워크플로: 에러 이해, 근본 원인 파악, 수정, 테스트 + +### 간단한 디버깅 + +> **먼저 이것부터 시도해 보세요:** `@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.` + +무엇이 잘못되었는지 설명하는 것부터 시작하세요. 다음은 buggy book 앱에서 시도해 볼 수 있는 일반적인 디버깅 패턴입니다. 각 프롬프트는 `@` 파일 참조와 명확한 증상 설명을 함께 사용해, Copilot CLI가 버그를 찾고 진단할 수 있도록 합니다. + +```bash +copilot + +# Pattern: "Expected X but got 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. + +# Pattern: "Unexpected behavior" +> @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. + +# Pattern: "Wrong results" +> @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](../../../03-development-workflows/images/fix-bug-demo.gif) + +*데모 출력은 매번 달라질 수 있습니다. 사용하는 모델, 도구, 응답이 여기 보이는 것과 다를 수 있습니다.* + +
+ +--- + +### "버그 탐정" - AI가 관련된 다른 버그를 찾아냅니다 + +이 부분에서 컨텍스트 인식 디버깅의 진가가 드러납니다. buggy book 앱에서 다음 시나리오를 시도해 보세요. `@`로 파일 전체를 제공하고, 사용자가 보고한 증상만 설명하세요. Copilot CLI는 근본 원인을 추적하고, 근처에 있는 다른 버그까지 발견해 줄 수도 있습니다. + +```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는 파일 전체를 읽고, 버그 보고의 컨텍스트를 이해한 뒤, 명확한 설명과 함께 구체적인 수정안을 제시합니다. + +> 💡 **보너스**: Copilot CLI는 파일 전체를 분석하기 때문에, 여러분이 묻지 않은 *다른* 이슈까지 발견하는 경우가 많습니다. 예를 들어, author 검색을 수정하면서 `find_book_by_title`의 대소문자 구분 버그까지 함께 짚어 줄 수도 있습니다! + +### 실전 보안 사이드바 + +자기 코드의 디버깅도 중요하지만, 운영 애플리케이션의 보안 취약점을 이해하는 것은 매우 중요합니다. 다음 예제를 시도해 보세요. 익숙하지 않은 파일을 Copilot CLI에 가리키며 보안 이슈를 감사해 달라고 요청합니다. + +```bash +copilot + +> @samples/buggy-code/python/user_service.py Find all security vulnerabilities in this Python user service +``` + +이 파일은 운영 앱에서 실제로 마주치게 되는 보안 패턴을 보여 줍니다. + +> 💡 **자주 마주치는 보안 용어:** +> - **SQL Injection**: 사용자 입력이 데이터베이스 쿼리에 직접 들어가, 공격자가 악성 명령을 실행할 수 있게 되는 취약점 +> - **Parameterized queries**: 안전한 대안으로, 플레이스홀더(`?`)를 사용해 사용자 데이터와 SQL 명령을 분리합니다 +> - **Race condition**: 두 작업이 동시에 일어나며 서로 간섭하는 상황 +> - **XSS (Cross-Site Scripting)**: 공격자가 웹 페이지에 악성 스크립트를 주입하는 공격 + +--- + +### 에러 이해하기 + +스택 트레이스를 `@` 파일 참조와 함께 프롬프트에 직접 붙여넣으면, 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? +``` + +
+ +--- + + +
+Workflow 4: Test Generation - 종합적인 테스트와 엣지 케이스를 자동으로 생성 + +테스트 생성 워크플로: 함수 분석, 테스트 생성, 엣지 케이스 포함, 실행 + +> **먼저 이것부터 시도해 보세요:** `@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](../../../03-development-workflows/images/test-gen-demo.gif) + +*데모 출력은 매번 달라질 수 있습니다. 사용하는 모델, 도구, 응답이 여기 보이는 것과 다를 수 있습니다.* + +
+ +--- + +**얻게 되는 결과**: 다음을 포함한 15개 이상의 종합 테스트를 받게 됩니다. + +```python +class TestBookCollection: + # Happy path + def test_add_book_creates_new_book(self): + ... + def test_list_books_returns_all_books(self): + ... + + # Find operations + 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): + ... + + # Edge cases + def test_add_book_with_empty_title(self): + ... + def test_remove_nonexistent_book(self): + ... + def test_mark_as_read_nonexistent_book(self): + ... + + # Data persistence + def test_save_books_persists_to_json(self): + ... + def test_load_books_handles_missing_file(self): + ... + def test_load_books_handles_corrupted_json(self): + ... + + # Special characters + 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에 던져 보세요. 적절한 셸 명령을 생성해 줍니다. + +```bash +copilot + +> How do I run the tests? Show me the pytest command. + +# Copilot CLI responds: +# cd samples/book-app-project && python -m pytest tests/ +# Or for verbose output: python -m pytest tests/ -v +# To see print statements: 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 +``` + +
+ +--- + + +
+Workflow 5: Git Integration - 커밋 메시지, PR 설명, /pr, /delegate, /diff + +Git 통합 워크플로: 변경 사항 스테이징, 메시지 생성, 커밋, PR 생성 + +> 💡 **이 워크플로는 기본적인 git 사용법(스테이징, 커밋, 브랜치)에 익숙하다고 가정합니다.** git이 처음이라면 다른 네 가지 워크플로를 먼저 시도해 보세요. + +### 커밋 메시지 생성 + +> **먼저 이것부터 시도해 보세요:** `copilot -p "Generate a conventional commit message for: $(git diff --staged)"` — 변경 사항을 스테이징한 다음 이 명령을 실행해, Copilot CLI가 커밋 메시지를 작성하는 모습을 확인해 보세요. + +이 예제는 `-p` 인라인 프롬프트 플래그를 셸 명령 치환과 함께 사용해, `git diff` 출력을 Copilot CLI에 직접 파이프하여 일회성 커밋 메시지를 생성합니다. `$(...)` 구문은 괄호 안의 명령을 실행한 뒤 그 출력을 바깥 명령에 삽입합니다. + +```bash + +# See what changed +git diff --staged + +# Generate commit message using [Conventional Commit](../../../GLOSSARY.md#conventional-commit) format +# (structured messages like "feat(books): add search" or "fix(data): handle empty input") +copilot -p "Generate a conventional commit message for: $(git diff --staged)" + +# Output: "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](../../../03-development-workflows/images/git-integration-demo.gif) + +*데모 출력은 매번 달라질 수 있습니다. 사용하는 모델, 도구, 응답이 여기 보이는 것과 다를 수 있습니다.* + +
+ +--- + +### 변경 사항 설명 + +`git show` 출력을 `-p` 프롬프트에 파이프하면, 마지막 커밋에 대한 평범한 언어의 요약을 받을 수 있습니다. + +```bash +# What did this commit change? +copilot -p "Explain what this commit does: $(git show HEAD --stat)" +``` + +### PR 설명 + +`git log` 출력을 구조화된 프롬프트 템플릿과 결합해, 완전한 pull request 설명을 자동으로 생성할 수 있습니다. + +```bash +# Generate PR description from branch changes +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)" +``` + +### 인터랙티브 모드에서 현재 브랜치에 /pr 사용하기 + +Copilot CLI의 인터랙티브 모드에서 브랜치 작업을 하고 있다면, `/pr` 명령으로 pull request 작업을 할 수 있습니다. `/pr`을 사용해 PR을 보거나, 새 PR을 만들거나, 기존 PR을 수정하거나, 브랜치 상태에 따라 Copilot CLI가 자동으로 결정하도록 할 수 있습니다. + +```bash +copilot + +> /pr [view|create|fix|auto] +``` + +### 푸시 전 리뷰 + +`git diff main..HEAD`를 `-p` 프롬프트 안에 넣으면, 모든 브랜치 변경 사항을 푸시 전에 빠르게 점검할 수 있습니다. + +```bash +# Last check before pushing +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 + +# Or use the & prefix shortcut: +> & Fix the typo in the README header + +# Copilot CLI: +# 1. Commits your changes to a new branch +# 2. Opens a draft pull request +# 3. Works in the background on GitHub +# 4. Requests your review when done +``` + +다른 작업에 집중하면서 완료시키고 싶은, 잘 정의된 작업에 매우 유용합니다. + +### 세션 변경 사항 리뷰를 위한 /diff 사용 + +`/diff` 명령은 현재 세션 동안 이루어진 모든 변경 사항을 보여 줍니다. 커밋하기 전에 Copilot CLI가 수정한 모든 내용을 시각적인 diff로 확인할 때 이 슬래시 명령을 사용하세요. + +```bash +copilot + +# After making some changes... +> /diff + +# Shows a visual diff of all files modified in this session +# Great for reviewing before committing +``` + +
+ +--- + +## 빠른 팁: 계획하거나 코딩하기 전에 먼저 리서치하기 + +라이브러리를 조사하거나, 모범 사례를 이해하거나, 익숙하지 않은 주제를 탐색해야 할 때, 코드를 작성하기 전에 `/research`를 사용해 깊이 있는 리서치를 진행해 보세요. + +```bash +copilot + +> /research What are the best Python libraries for validating user input in CLI apps? +``` + +Copilot은 GitHub 저장소와 웹 자료를 검색한 뒤, 참고 자료와 함께 요약을 반환합니다. 새 기능을 시작하기 전에 정보에 기반한 결정을 내리고 싶을 때 유용합니다. 결과는 `/share`로 공유할 수 있습니다. + +> 💡 **팁**: `/research`는 `/plan`보다 *먼저* 사용할 때 잘 동작합니다. 접근 방식을 리서치한 뒤, 구현을 계획하세요. + +--- + +## 모두 합치기: 버그 수정 워크플로 + +다음은 보고된 버그를 수정하는 전체 워크플로입니다. + +```bash + +# 1. Understand the bug report +copilot + +> Users report: 'Finding books by author name doesn't work for partial names' +> @samples/book-app-project/books.py Analyze and identify the likely cause + +# 2. Debug the issue and fix (continuing in same session) +> Based on the analysis, show me the find_by_author function and explain the issue + +> Fix the find_by_author function to handle partial name matches + +# 3. Generate tests for the fix +> @samples/book-app-project/books.py Generate pytest tests specifically for: +> - Full author name match +> - Partial author name match +> - Case-insensitive matching +> - Author name not found + +# Exit the interactive session + +> /exit + +# 4. Run git add + +# Stage the changes so git diff --staged has something to work with +git add . + +# 5. Generate commit message +copilot -p "Generate commit message for: $(git diff --staged)" + +# Example Output: "fix(books): support partial author name search" + +# 6. Commit changes (optional) + +git commit -m "" +``` + +### 버그 수정 워크플로 요약 + +| 단계 | 작업 | Copilot 명령 | +|------|--------|-----------------| +| 1 | 버그 이해 | `> [describe bug] @relevant-file.py Analyze the likely cause` | +| 2 | 분석 및 수정 | `> Show me the function and fix the issue` | +| 3 | 테스트 생성 | `> Generate tests for [specific scenarios]` | +| 4 | 변경 사항 스테이징 | `git add .` | +| 5 | 커밋 메시지 생성 | `copilot -p "Generate commit message for: $(git diff --staged)"` | +| 6 | 변경 사항 커밋 | `git commit -m ""` | + +--- + +# 실습 + +코드가 표시된 모니터, 램프, 커피 컵, 헤드폰이 놓인 따뜻한 분위기의 책상 - 실습 준비가 된 모습 + +이제 여러분이 직접 이 워크플로들을 적용해 볼 차례입니다. + +--- + +## ▶️ 직접 해 보기 + +데모를 끝마쳤다면, 다음 변형을 시도해 보세요. + +1. **버그 탐정 챌린지**: `samples/book-app-buggy/books_buggy.py`의 `mark_as_read` 함수를 디버깅해 달라고 Copilot CLI에 요청해 보세요. 한 권만이 아니라 모든 책이 읽음 처리되는 이유를 잘 설명해 주었나요? + +2. **테스트 챌린지**: book 앱의 `add_book` 함수에 대한 테스트를 생성해 보세요. 여러분이 떠올리지 못했을 엣지 케이스가 몇 개나 포함되어 있는지 세어 보세요. + +3. **커밋 메시지 챌린지**: book 앱 파일에 작은 변경을 가하고 스테이징(`git add .`)한 뒤 다음을 실행해 보세요. + ```bash + copilot -p "Generate a conventional commit message for: $(git diff --staged)" + ``` + 여러분이 빠르게 작성했을 것보다 메시지가 더 나은가요? + +**셀프 체크**: "이 버그를 디버깅해 줘"가 "버그를 찾아 줘"보다 더 강력한 이유를 설명할 수 있다면, 개발 워크플로를 이해한 것입니다(컨텍스트가 중요합니다!). + +--- + +## 📝 과제 + +### 메인 챌린지: 리팩터링, 테스트, 그리고 출시 + +실습 예제는 `find_book_by_title`과 코드 리뷰에 집중했습니다. 이제 `book-app-project`의 다른 함수에 동일한 워크플로 기술을 적용해 보세요. + +1. **리뷰**: `books.py`의 `remove_book()`을 엣지 케이스와 잠재적 이슈 관점에서 리뷰해 달라고 Copilot CLI에 요청합니다. + `@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. **리팩터링**: 대소문자 구분 없는 매칭이나, 책을 찾지 못했을 때 유용한 피드백을 반환하는 등 엣지 케이스를 처리하도록 `remove_book()`을 개선해 달라고 Copilot CLI에 요청합니다. +3. **테스트**: 개선된 `remove_book()` 함수에 대해 다음을 다루는 pytest 테스트를 생성합니다. + - 존재하는 책을 제거 + - 대소문자 구분 없는 제목 매칭 + - 존재하지 않는 책에 대해 적절한 피드백 반환 + - 빈 컬렉션에서 제거 +4. **리뷰**: 변경 사항을 스테이징하고 `/review`를 실행해 남아 있는 이슈가 있는지 확인합니다. +5. **커밋**: conventional commit 메시지를 생성합니다. + `copilot -p "Generate a conventional commit message for: $(git diff --staged)"` + +
+💡 힌트 (클릭하여 펼치기) + +**각 단계에 대한 샘플 프롬프트:** + +```bash +copilot + +# Step 1: Review +> @samples/book-app-project/books.py Review the remove_book() function. What edge cases are not handled? + +# Step 2: Refactor +> 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. + +# Step 3: Test +> 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 + +# Step 4: Review +> /review + +# Step 5: Commit +> 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 실습은 Python이 아니라 **Node.js**를 사용합니다. 여기서 연습하는 GitHub Copilot CLI 기법(이슈 생성, 코드 생성, 터미널에서의 협업)은 어떤 언어에든 적용할 수 있습니다. + +이 실습에서는 Node.js 계산기 앱을 만들면서, GitHub Copilot CLI로 이슈를 만들고, 코드를 생성하고, 터미널에서 협업하는 방법을 보여 줍니다. CLI를 설치하고, 템플릿과 에이전트를 사용하며, 명령줄 기반의 반복적인 개발을 연습하게 됩니다. + +##### ["Create applications with the Copilot CLI" Skills 실습 시작하기](https://github.com/skills/create-applications-with-the-copilot-cli) + +--- + +
+🔧 흔한 실수와 트러블슈팅 (클릭하여 펼치기) + +### 흔한 실수 + +| 실수 | 무슨 일이 벌어지나 | 해결 방법 | +|---------|--------------|-----| +| "Review this code"처럼 모호한 프롬프트 사용 | 구체적인 이슈를 놓친 일반적인 피드백 | 구체적으로: "Review for SQL injection, XSS, and auth issues" | +| 코드 리뷰에 `/review`를 사용하지 않음 | 최적화된 code-review 에이전트를 놓침 | 신호 대 잡음비가 높은 출력에 맞게 튜닝된 `/review` 사용 | +| 컨텍스트 없이 "find bugs"라고만 요청 | Copilot CLI가 어떤 버그를 겪고 있는지 모름 | 증상을 설명: "Users report X happens when Y" | +| 프레임워크를 지정하지 않고 테스트 생성 | 테스트가 잘못된 문법이나 단언 라이브러리를 쓸 수 있음 | 명시: "Generate tests using Jest" 또는 "using pytest" | + +### 트러블슈팅 + +**리뷰가 불완전해 보일 때** - 무엇을 봐야 하는지 더 구체적으로 알려주세요. + +```bash +copilot + +# Instead of: +> Review @samples/book-app-project/book_app.py + +# Try: +> 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 command reference](https://docs.github.com/en/copilot/reference/cli-command-reference)에서 확인하세요. + +--- + +## ✅ 체크포인트: 핵심을 마스터했습니다 + +**축하합니다!** 이제 GitHub Copilot CLI로 생산적으로 일하는 데 필요한 모든 핵심 기술을 갖추었습니다. + +| 기술 | 챕터 | 할 수 있게 된 것 | +|-------|---------|----------------| +| 기본 명령 | Ch 01 | 인터랙티브 모드, 플랜 모드, 프로그래매틱 모드(-p), 슬래시 명령 사용 | +| 컨텍스트 | Ch 02 | `@`로 파일 참조, 세션 관리, 컨텍스트 윈도우 이해 | +| 워크플로 | Ch 03 | 코드 리뷰, 리팩터링, 디버깅, 테스트 생성, git 통합 | + +챕터 04~06은 추가적인 기능들을 다루며, 더 큰 강력함을 더해 주는 학습 가치가 있는 내용입니다. + +--- + +## 🛠️ 나만의 워크플로 만들기 + +GitHub Copilot CLI를 사용하는 단 하나의 "정답"은 없습니다. 자신만의 패턴을 만들어 가는 동안 참고할 만한 몇 가지 팁입니다. + +> 📚 **공식 문서**: GitHub의 권장 워크플로와 팁은 [Copilot CLI best practices](https://docs.github.com/copilot/how-tos/copilot-cli/cli-best-practices)에서 확인하세요. + +- 사소하지 않은 작업이라면 **`/plan`으로 시작하세요.** 실행 전에 계획을 다듬으세요. 좋은 계획은 더 나은 결과로 이어집니다. +- **잘 동작한 프롬프트는 저장해 두세요.** Copilot CLI가 실수했을 때, 무엇이 잘못되었는지 메모해 두세요. 시간이 지나면 여러분만의 플레이북이 됩니다. +- **자유롭게 실험하세요.** 어떤 개발자는 길고 상세한 프롬프트를 선호하고, 어떤 개발자는 짧은 프롬프트와 후속 질문을 선호합니다. 다양한 접근 방식을 시도해 보고 자연스럽게 느껴지는 것을 찾아보세요. + +> 💡 **다음에 배울 것**: 챕터 04와 05에서는 자신의 모범 사례를 Copilot CLI가 자동으로 로드하는 커스텀 인스트럭션과 스킬로 코드화하는 방법을 배웁니다. + +--- + +## ➡️ 다음 단계 + +남은 챕터들은 Copilot CLI의 기능을 확장하는 추가 기능들을 다룹니다. + +| 챕터 | 다루는 내용 | 언제 필요한가 | +|---------|----------------|---------------------| +| Ch 04: Agents | 전문화된 AI 페르소나 만들기 | 도메인 전문가(프론트엔드, 보안)가 필요할 때 | +| Ch 05: Skills | 작업별 인스트럭션 자동 로드 | 같은 프롬프트를 자주 반복할 때 | +| Ch 06: MCP | 외부 서비스 연결 | GitHub, 데이터베이스 등에서 실시간 데이터가 필요할 때 | + +**추천**: 일주일 정도 핵심 워크플로를 사용해 본 뒤, 구체적인 필요가 생겼을 때 챕터 04~06으로 돌아오세요. + +--- + +## 추가 주제로 계속하기 + +**[Chapter 04: Agents and Custom Instructions](../04-agents-custom-instructions/README.md)**에서는 다음을 배웁니다. + +- 내장 에이전트(`/plan`, `/review`) 사용 +- `.agent.md` 파일로 전문화된 에이전트(프론트엔드 전문가, 보안 감사자) 만들기 +- 멀티 에이전트 협업 패턴 +- 프로젝트 표준을 위한 커스텀 인스트럭션 파일 + +--- + +**[← Chapter 02로 돌아가기](../02-context-conversations/README.md)** | **[Chapter 04로 계속하기 →](../04-agents-custom-instructions/README.md)** diff --git a/localization/ko-kr/04-agents-custom-instructions/README.md b/localization/ko-kr/04-agents-custom-instructions/README.md new file mode 100644 index 00000000..40e82578 --- /dev/null +++ b/localization/ko-kr/04-agents-custom-instructions/README.md @@ -0,0 +1,783 @@ +![4장: 에이전트와 사용자 정의 지침](../../../04-agents-custom-instructions/images/chapter-header.png) + +> **Python 코드 리뷰어, 테스트 전문가, 보안 리뷰어를... 도구 하나로 모두 고용할 수 있다면 어떨까요?** + +3장에서는 코드 리뷰, 리팩터링, 디버깅, 테스트 생성, 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. **핵심 개념 이해하기:** 에이전트는 일반인이 아닌 전문가에게 자문을 구하는 것과 같습니다. "프런트엔드 에이전트"는 접근성과 컴포넌트 패턴에 자동으로 집중합니다. 에이전트 지침에 이미 명시되어 있기 때문에 매번 상기시켜 줄 필요가 없습니다. + + +## 내장 에이전트 + +**3장 개발 워크플로에서 이미 일부 내장 에이전트를 사용해 봤습니다!** +
`/plan`과 `/review`는 사실 내장 에이전트입니다. 이제 내부에서 무슨 일이 일어나고 있는지 알게 되었습니다. 전체 목록은 다음과 같습니다: + +| 에이전트 | 호출 방법 | 하는 일 | +|-------|---------------|--------------| +| **Plan** | `/plan` 또는 `Shift+Tab` (모드 순환) | 코딩 전에 단계별 구현 계획을 작성합니다 | +| **Code-review** | `/review` | 스테이징/언스테이징된 변경 사항을 집중적이고 실행 가능한 피드백으로 리뷰합니다 | +| **Init** | `/init` | 프로젝트 구성 파일(지침, 에이전트)을 생성합니다 | +| **Explore** | *자동* | Copilot에게 코드베이스를 탐색하거나 분석하도록 요청할 때 내부적으로 사용됩니다 | +| **Task** | *자동* | 테스트, 빌드, 린트, 의존성 설치 같은 명령을 실행합니다 | + +
+ +**내장 에이전트 실제 사용 예** - Plan, Code-review, Explore, Task 호출 예시 + +```bash +copilot + +# Invoke the Plan agent to create an implementation plan +> /plan Add input validation for book year in the book app + +# Invoke the Code-review agent on your changes +> /review + +# Explore and Task agents are invoked automatically when relevant: +> Run the test suite # Uses Task agent + +> Explore how book data is loaded # Uses Explore agent +``` + +Task 에이전트는 어떨까요? 이 에이전트는 무대 뒤에서 진행 상황을 관리·추적하고, 깔끔하고 명확한 형식으로 결과를 보고합니다: + +| 결과 | 표시 내용 | +|---------|--------------| +| ✅ **성공** | 간단한 요약 (예: "All 247 tests passed", "Build succeeded") | +| ❌ **실패** | 스택 트레이스, 컴파일러 오류, 상세 로그가 포함된 전체 출력 | + + +> 📚 **공식 문서**: [GitHub Copilot CLI Agents](https://docs.github.com/copilot/how-tos/use-copilot-agents/use-copilot-cli#use-custom-agents) + +--- + +# Copilot CLI에 에이전트 추가하기 + +자신만의 에이전트를 정의해 워크플로의 일부로 만들 수 있습니다! 한 번 정의해 두면, 그 다음에는 지시만 하면 됩니다! + +네 개의 다채로운 AI 로봇이 각자 다른 도구를 들고 함께 서 있는 모습 - 전문화된 에이전트의 능력을 표현 + +## 🗂️ 에이전트 추가하기 + +에이전트 파일은 `.agent.md` 확장자를 가진 마크다운 파일입니다. 두 부분으로 구성됩니다: YAML 프런트매터(메타데이터)와 마크다운 지침입니다. + +> 💡 **YAML 프런트매터가 처음이신가요?** 파일 맨 위에 `---` 표시로 둘러싸인 작은 설정 블록을 말합니다. YAML은 `key: value` 쌍의 모음일 뿐이며, 나머지 파일은 일반 마크다운입니다. + +다음은 최소 구성의 에이전트입니다: + +```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 +# Or copy one to your personal agents folder (available in every project) +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`를 사용하고 **no agent**를 선택하세요. + +--- + +# 에이전트 더 깊이 들여다보기 + +작업대 위에서 부품과 도구에 둘러싸여 조립되고 있는 로봇 - 사용자 정의 에이전트 제작을 표현 + +> 💡 **이 섹션은 선택 사항입니다.** 내장 에이전트(`/plan`, `/review`)만으로도 대부분의 워크플로에 충분히 강력합니다. 작업 전반에 걸쳐 일관되게 적용되는 전문성이 필요할 때 사용자 정의 에이전트를 만드세요. + +아래의 각 주제는 독립적으로 구성되어 있습니다. **관심 있는 부분을 골라 읽으세요. 한 번에 다 읽을 필요는 없습니다.** + +| 하고 싶은 것 | 이동할 곳 | +|---|---| +| 에이전트가 일반 프롬프트보다 나은 이유 보기 | [Specialist vs Generic](#specialist-vs-generic-see-the-difference) | +| 한 기능에 여러 에이전트 결합하기 | [Working with Multiple Agents](#working-with-multiple-agents) | +| 에이전트 정리·명명·공유하기 | [Organizing & Sharing Agents](#organizing--sharing-agents) | +| 항상 활성화되는 프로젝트 컨텍스트 설정하기 | [Configuring Your Project for Copilot](#configuring-your-project-for-copilot) | +| YAML 속성과 도구 찾아보기 | [Agent File Reference](#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 Reviewer 에이전트와 함께 + +```bash +copilot + +> /agent +# Select "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 +- ✅ 적절한 오류 처리를 포함한 입력 검증 +- ✅ 더 나은 성능을 위한 리스트 컴프리헨션 +- ✅ 엣지 케이스 처리 (누락되거나 잘못된 year 값) +- ✅ PEP 8 준수 형식 +- ✅ 방어적 프로그래밍 관행 + +**핵심 차이**: 같은 프롬프트인데, 결과는 비교할 수 없을 만큼 좋아졌습니다. 에이전트는 우리가 미처 요청하지 못했을 전문성을 함께 제공합니다. + +
+ +--- + + +
+여러 에이전트 함께 사용하기 - 전문가 결합, 세션 도중 전환, 도구로서의 에이전트 + +## 여러 에이전트 함께 사용하기 + +진정한 힘은 전문가들이 한 기능을 위해 함께 일할 때 발휘됩니다. + +### 예시: 간단한 기능 만들기 + +```bash +copilot + +> I want to add a "search by year range" feature to the book app + +# Use python-reviewer for design +> /agent +# Select "python-reviewer" + +> @samples/book-app-project/books.py Design a find_by_year_range method. What's the best approach? + +# Switch to pytest-helper for test design +> /agent +# Select "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? + +# Synthesize both designs +> Create an implementation plan that includes the method implementation and comprehensive tests. +``` + +**핵심 통찰**: 여러분은 전문가들을 지휘하는 아키텍트입니다. 세부 사항은 그들이 처리하고, 비전은 여러분이 책임집니다. + +
+🎬 실제로 동작하는 모습 보기! + +![Python Reviewer 데모](../../../04-agents-custom-instructions/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` +- 필요할 때는 구체적으로: 단순한 `frontend`보다 `react-typescript`처럼 + +--- + +### 팀과 공유하기 + +`.github/agents/`에 에이전트 파일을 두면 버전 관리됩니다. 저장소에 푸시하면 모든 팀원이 자동으로 받게 됩니다. 그런데 에이전트는 Copilot이 프로젝트에서 읽는 여러 파일 유형 중 하나일 뿐입니다. Copilot은 누군가 `/agent`를 실행하지 않아도 모든 세션에 자동으로 적용되는 **지침 파일**도 지원합니다. + +이렇게 생각해 보세요: 에이전트는 필요할 때 호출하는 전문가이고, 지침 파일은 항상 활성화된 팀 규칙입니다. + +### 파일을 두는 위치 + +이미 두 가지 주요 위치를 알고 있습니다(위 [에이전트 파일을 두는 위치](#where-to-put-agent-files) 참조). 다음 결정 트리를 참고해 선택하세요: + +에이전트 파일 위치 결정 트리: 실험 중 → 현재 폴더, 팀 사용 → .github/agents/, 어디서나 → ~/.copilot/agents/ + +**간단하게 시작하세요:** 프로젝트 폴더에 `*.agent.md` 파일 하나를 만드세요. 만족스러우면 영구적인 위치로 옮기면 됩니다. + +에이전트 파일 외에도 Copilot은 `/agent` 없이 자동으로 적용되는 **프로젝트 수준 지침 파일**도 읽습니다. `AGENTS.md`, `.instructions.md`, `/init`에 대해서는 아래 [Configuring Your Project for 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`는 권장 형식입니다. Copilot 및 다른 AI 코딩 도구에서 모두 동작하는 [열린 표준](https://agents.md/)입니다. 저장소 루트에 두면 Copilot이 자동으로 읽습니다. 이 프로젝트의 [AGENTS.md](../../../AGENTS.md)는 실제 동작하는 예시입니다. + +전형적인 `AGENTS.md`는 프로젝트 컨텍스트, 코드 스타일, 보안 요구 사항, 테스트 표준을 기술합니다. 예시 파일의 패턴을 따라 자신만의 파일을 작성해 보세요. + +### 사용자 정의 지침 파일 (.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`, `Bash`) +- `agent` - 다른 사용자 정의 에이전트 호출 + +> 📖 **공식 문서**: [Custom agents configuration](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 + +# Create the agents directory (if it doesn't exist) +mkdir -p .github/agents + +# Create a code reviewer agent +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 + +# Create a documentation agent +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 + +# Now use them +copilot --agent reviewer +> Review @samples/book-app-project/books.py + +# Or switch agents +copilot +> /agent +# Select "documentor" +> Document @samples/book-app-project/books.py +``` + +--- + +## 📝 과제 + +### 메인 챌린지: 전문화된 에이전트 팀 만들기 + +직접 해 보기 예시에서는 `reviewer`와 `documentor` 에이전트를 만들었습니다. 이번에는 다른 작업, 즉 책 앱의 데이터 검증을 개선하기 위해 에이전트를 만들고 사용하는 연습을 해 봅시다: + +1. 책 앱에 맞춘 3개의 에이전트 파일(`.agent.md`)을 만들고, 각 에이전트당 하나씩 `.github/agents/`에 배치합니다 +2. 에이전트 구성: + - **data-validator**: `data.json`에서 누락되거나 잘못된 데이터(빈 author, 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 +# Select "data-validator" from the list +> @samples/book-app-project/data.json Check for books with empty author fields or invalid years +``` + +**팁:** YAML 프런트매터의 `description` 필드는 에이전트가 동작하기 위해 반드시 필요합니다. + +
+ +### 보너스 챌린지: 지침 라이브러리 + +요청 시 호출하는 에이전트를 만들어 봤습니다. 이제 그 반대편을 시도해 보세요. **지침 파일**은 `/agent` 없이도 Copilot이 모든 세션에서 자동으로 읽는 파일입니다. + +`.github/instructions/` 폴더에 최소 3개의 지침 파일을 만드세요: +- PEP 8과 타입 힌트 규칙을 강제하기 위한 `python-style.instructions.md` +- 테스트 파일에서 pytest 컨벤션을 강제하기 위한 `test-standards.instructions.md` +- JSON 데이터 항목을 검증하기 위한 `data-quality.instructions.md` + +각 지침 파일을 책 앱 코드에 적용해 테스트해 보세요. + +--- + +
+🔧 흔한 실수와 문제 해결 (펼치려면 클릭) + +### 흔한 실수 + +| 실수 | 발생하는 일 | 해결 방법 | +|---------|--------------|-----| +| 에이전트 프런트매터에 `description` 누락 | 에이전트가 로드되지 않거나 발견되지 않음 | YAML 프런트매터에 항상 `description:`을 포함하세요 | +| 잘못된 에이전트 파일 위치 | 사용하려고 할 때 에이전트를 찾을 수 없음 | `~/.copilot/agents/` (개인) 또는 `.github/agents/` (프로젝트)에 두세요 | +| `.agent.md` 대신 `.md` 사용 | 파일이 에이전트로 인식되지 않을 수 있음 | `python-reviewer.agent.md`처럼 파일 이름을 지정하세요 | +| 지나치게 긴 에이전트 프롬프트 | 30,000자 제한에 걸릴 수 있음 | 에이전트 정의는 집중적으로 유지하고, 상세 지침은 skill을 사용하세요 | + +### 문제 해결 + +**에이전트를 찾을 수 없음** - 에이전트 파일이 다음 위치 중 하나에 있는지 확인하세요: +- `~/.copilot/agents/` +- `.github/agents/` + +사용 가능한 에이전트 목록 보기: + +```bash +copilot +> /agent +# Shows all available agents +``` + +**에이전트가 지침을 따르지 않음** - 프롬프트를 보다 명시적으로 작성하고 에이전트 정의에 더 많은 세부 정보를 추가하세요: +- 버전을 포함한 구체적인 프레임워크/라이브러리 +- 팀 컨벤션 +- 예시 코드 패턴 + +**사용자 정의 지침이 로드되지 않음** - 프로젝트에서 `/init`을 실행해 프로젝트별 지침을 설정하세요: + +```bash +copilot +> /init +``` + +또는 비활성화되어 있는지 확인하세요: +```bash +# Don't use --no-custom-instructions if you want them loaded +copilot # This loads custom instructions by default +``` + +
+ +--- + +# 요약 + +## 🔑 핵심 정리 + +1. **내장 에이전트**: `/plan`과 `/review`는 직접 호출하며, Explore와 Task는 자동으로 동작합니다 +2. **사용자 정의 에이전트**는 `.agent.md` 파일에 정의된 전문가입니다 +3. **좋은 에이전트**는 명확한 전문성, 표준, 출력 형식을 갖춥니다 +4. **다중 에이전트 협업**은 전문성을 결합해 복잡한 문제를 해결합니다 +5. **지침 파일**(`.instructions.md`)은 자동 적용되는 팀 표준을 코드화합니다 +6. **일관된 결과**는 잘 정의된 에이전트 지침에서 나옵니다 + +> 📋 **빠른 참조**: 명령과 단축키의 전체 목록은 [GitHub Copilot CLI command reference](https://docs.github.com/en/copilot/reference/cli-command-reference)를 참고하세요. + +--- + +## ➡️ 다음 단계 + +에이전트는 *Copilot이 코드에 접근하고 목적에 맞춰 행동하는 방식*을 바꿉니다. 다음으로 배울 **skill**은 *어떤 단계*를 따르는지를 바꿉니다. 에이전트와 skill의 차이가 궁금하신가요? 5장에서 정면으로 다룹니다. + +**[5장: Skills 시스템](../05-skills/README.md)** 에서는 다음을 배웁니다: + +- 슬래시 명령 없이 프롬프트에서 자동으로 트리거되는 skill +- 커뮤니티 skill 설치 +- SKILL.md 파일로 사용자 정의 skill 만들기 +- 에이전트, skill, MCP의 차이 +- 각각을 언제 사용해야 하는지 + +--- + +**[← 3장으로 돌아가기](../03-development-workflows/README.md)** | **[5장으로 계속 →](../05-skills/README.md)** diff --git a/localization/ko-kr/05-skills/README.md b/localization/ko-kr/05-skills/README.md new file mode 100644 index 00000000..5f912269 --- /dev/null +++ b/localization/ko-kr/05-skills/README.md @@ -0,0 +1,886 @@ +![Chapter 05: Skills System](../../../05-skills/images/chapter-header.png) + +> **만약 Copilot이 매번 설명할 필요 없이 여러분 팀의 모범 사례를 자동으로 적용해 준다면 어떨까요?** + +이번 장에서는 Agent Skills(에이전트 스킬)에 대해 배웁니다. Skills는 작업과 관련될 때 Copilot이 자동으로 불러오는 지시문 폴더입니다. 에이전트가 Copilot이 *생각하는 방식*을 바꾼다면, 스킬은 Copilot에게 *작업을 완료하는 구체적인 방법*을 알려 줍니다. 보안 관련 질문을 할 때마다 Copilot이 적용하는 보안 감사 스킬을 만들고, 일관된 코드 품질을 보장하는 팀 표준 리뷰 기준을 구축하며, Copilot CLI, VS Code, GitHub Copilot 클라우드 에이전트에서 스킬이 어떻게 동작하는지 익히게 됩니다. + + +## 🎯 학습 목표 + +이 장을 마치고 나면 다음을 할 수 있습니다: + +- Agent Skills의 동작 방식과 사용 시점 이해 +- SKILL.md 파일로 사용자 지정 스킬 만들기 +- 공유 저장소의 커뮤니티 스킬 사용 +- 스킬, 에이전트, MCP를 언제 사용할지 구분 + +> ⏱️ **예상 소요 시간**: 약 55분 (읽기 20분 + 실습 35분) + +--- + +## 🧩 실생활 비유: 전동 공구 + +범용 드릴은 유용하지만, 전용 부속을 끼우면 훨씬 강력해집니다. +전동 공구 - Copilot의 능력을 확장하는 스킬 + + +스킬도 같은 방식으로 동작합니다. 작업에 따라 드릴 비트를 바꿔 끼우듯이, 다양한 작업을 위해 Copilot에 스킬을 추가할 수 있습니다: + +| 스킬 부속 | 용도 | +|------------|---------| +| `commit` | 일관된 커밋 메시지 생성 | +| `security-audit` | OWASP 취약점 점검 | +| `generate-tests` | 포괄적인 pytest 테스트 작성 | +| `code-checklist` | 팀 코드 품질 표준 적용 | + + + +*스킬은 Copilot이 할 수 있는 일을 확장하는 전용 부속입니다* + +--- + +# 스킬의 동작 방식 + +별이 빛나는 배경 위에 빛의 궤적으로 연결된, Copilot 스킬을 나타내는 RPG 스타일의 빛나는 스킬 아이콘들 + +스킬이 무엇이고, 왜 중요하며, 에이전트 및 MCP와 어떻게 다른지 알아봅니다. + +--- + +## *스킬이 처음이신가요?* 여기서 시작하세요! + +1. **이미 사용 가능한 스킬 확인하기:** + ```bash + copilot + > /skills list + ``` + 이 명령은 Copilot이 찾을 수 있는 모든 스킬을 보여 줍니다. CLI 자체에 함께 제공되는 **기본 내장 스킬**과 프로젝트 및 개인 폴더의 스킬도 포함됩니다. + + > 💡 **기본 내장 스킬**: Copilot CLI에는 처음부터 사용할 수 있는 스킬이 미리 설치되어 있습니다. 예를 들어 `customizing-copilot-cloud-agents-environment` 스킬은 Copilot 클라우드 에이전트의 환경을 사용자 지정하는 가이드를 제공합니다. 이런 스킬은 별도로 만들거나 설치할 필요가 없습니다. `/skills list`를 실행해 어떤 스킬이 있는지 확인해 보세요. + +2. **실제 스킬 파일 살펴보기:** 제공된 [code-checklist SKILL.md](../../../.github/skills/code-checklist/SKILL.md)를 보고 패턴을 확인해 보세요. YAML frontmatter와 마크다운 지시문으로만 구성되어 있습니다. + +3. **핵심 개념 이해하기:** 스킬은 작업별 지시문이며, 여러분의 프롬프트가 스킬의 description과 일치하면 Copilot이 *자동으로* 불러옵니다. 따로 활성화할 필요 없이 자연스럽게 질문하기만 하면 됩니다. + + +## 스킬 이해하기 + +Agent Skills는 지시문, 스크립트, 리소스를 담은 폴더로, 작업과 관련될 때 Copilot이 **자동으로 불러옵니다**. Copilot은 여러분의 프롬프트를 읽고 일치하는 스킬이 있는지 확인한 뒤 관련 지시문을 자동으로 적용합니다. + +```bash +copilot + +> Check books.py against our quality checklist +# Copilot detects this matches your "code-checklist" skill +# and automatically applies its Python quality checklist + +> Generate tests for the BookCollection class +# Copilot loads your "pytest-gen" skill +# and applies your preferred test structure + +> What are the code quality issues in this file? +# Copilot loads your "code-checklist" skill +# and checks against your team's standards +``` + +> 💡 **핵심 포인트**: 스킬은 여러분의 프롬프트가 스킬의 description과 일치하면 **자동으로 트리거됩니다**. 자연스럽게 묻기만 하면 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 +``` + +특정 스킬이 반드시 사용되도록 명시적으로 제어하고 싶을 때 유용합니다. + +#### 한 메시지에서 여러 스킬 결합하기 + +**한 메시지에서 두 개 이상의 스킬을 호출**할 수 있으며, 스킬 슬래시 명령은 프롬프트의 어디에든 — 맨 앞이 아니라도 — 등장할 수 있습니다. 두 가지 다른 검사를 한 번에 처리하고 싶을 때 편리합니다: + +```bash +> Check @samples/book-app-project/book_app.py with /code-checklist and also run /generate-tests for it + +> Review the auth module /security-audit then /code-checklist the result +``` + +Copilot은 같은 응답에서 호출된 각 스킬을 모두 적용해, 메시지를 여러 번 보낼 필요를 줄여 줍니다. + +> 💡 **팁**: 스킬 슬래시 명령은 문장에서 가장 자연스러운 곳에 두세요. 메시지의 시작, 중간, 끝 어디든 좋습니다. + +> 📝 **스킬 호출 vs 에이전트 호출**: 스킬 호출과 에이전트 호출을 혼동하지 마세요: +> - **스킬**: `/skill-name `, 예: `/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는 아직 걱정하지 마세요. [Chapter 06](../06-mcp-servers/)에서 다룹니다. 스킬이 전체 그림에 어떻게 들어맞는지 보여 주기 위해 여기에 함께 소개합니다.* + +에이전트, 스킬, MCP 서버의 차이점과 워크플로에서 어떻게 결합되는지 보여 주는 비교 다이어그램 + +| 기능 | 하는 일 | 사용 시점 | +|---------|--------------|-------------| +| **에이전트(Agents)** | AI가 생각하는 방식을 변경 | 다양한 작업에 걸친 전문성이 필요할 때 | +| **스킬(Skills)** | 작업별 지시문을 제공 | 구체적이고 반복 가능한 작업에 자세한 단계가 필요할 때 | +| **MCP** | 외부 서비스와 연결 | API의 실시간 데이터가 필요할 때 | + +폭넓은 전문성에는 에이전트, 특정 작업 지시에는 스킬, 외부 데이터에는 MCP를 사용합니다. 한 에이전트가 대화 중에 하나 이상의 스킬을 사용할 수도 있습니다. 예를 들어 에이전트에게 코드 점검을 요청하면 `security-audit` 스킬과 `code-checklist` 스킬을 자동으로 함께 적용할 수 있습니다. + +> 📚 **자세히 알아보기**: 스킬 형식과 모범 사례에 대한 전체 레퍼런스는 공식 [About Agent Skills](https://docs.github.com/copilot/concepts/agents/about-agent-skills) 문서를 참고하세요. + +--- + +## 수동 프롬프트에서 자동 전문성으로 + +스킬을 만드는 방법으로 들어가기 전에, 스킬이 *왜* 배울 만한 가치가 있는지 먼저 살펴보겠습니다. 일관성에서 얻는 이점을 보고 나면 "어떻게"가 더 잘 이해될 것입니다. + +### 스킬 사용 전: 들쭉날쭉한 리뷰 + +매번 코드 리뷰를 할 때마다 무언가를 빠뜨릴 수 있습니다: + +```bash +copilot + +> Review this code for issues +# Generic review - might miss your team's specific concerns +``` + +또는 매번 긴 프롬프트를 작성합니다: + +```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. 스킬 description을 확인해 `code-checklist` 스킬이 일치한다고 판단합니다. +3. 팀의 품질 체크리스트를 자동으로 불러옵니다. +4. 여러분이 일일이 나열하지 않아도 모든 검사를 적용합니다. + +스킬 자동 트리거 동작 방식 - Copilot이 여러분의 프롬프트를 적절한 스킬에 자동으로 매칭하는 4단계 흐름 + +*자연스럽게 질문하세요. 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 +``` + +**차이점**: 팀의 표준이 매번 자동으로 적용되며, 직접 적어 입력할 필요가 없습니다. + +--- + +
+🎬 동작 모습 보기! + +![Skill Trigger Demo](../../../05-skills/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 +``` + +**위력**: 모든 팀원이 동일한 표준을 자동으로 적용합니다. 신규 입사자가 체크리스트를 외울 필요가 없습니다. 스킬이 알아서 처리하기 때문입니다. + +--- + +# 사용자 지정 스킬 만들기 + +스킬 생성과 관리를 상징하는, 빛나는 LEGO 같은 블록으로 벽을 쌓아 올리는 사람과 로봇의 손 + +SKILL.md 파일로 직접 스킬을 만들어 봅니다. + +--- + +## 스킬 위치 + +스킬은 `.github/skills/`(프로젝트 전용) 또는 `~/.copilot/skills/`(사용자 수준)에 저장합니다. + +### Copilot이 스킬을 찾는 방법 + +Copilot은 다음 위치를 자동으로 스캔합니다: + +| 위치 | 범위 | +|----------|-------| +| `.github/skills/` | 프로젝트 전용 (git을 통해 팀과 공유) | +| `~/.copilot/skills/` | 사용자 전용 (개인 스킬) | + +### 스킬 구조 + +각 스킬은 자체 폴더 안에 `SKILL.md` 파일을 가집니다. 선택적으로 스크립트, 예제, 기타 리소스를 함께 포함할 수 있습니다: + +``` +.github/skills/ +└── my-skill/ + ├── SKILL.md # Required: Skill definition and instructions + ├── examples/ # Optional: Example files Copilot can reference + │ └── sample.py + └── scripts/ # Optional: Scripts the skill can use + └── validate.sh +``` + +> 💡 **팁**: 디렉터리 이름은 SKILL.md frontmatter의 `name`과 일치해야 합니다(소문자, 단어는 하이픈으로 구분). + +### SKILL.md 형식 + +스킬은 YAML frontmatter가 있는 단순한 마크다운 형식을 사용합니다: + +```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` | 아니오 | 이 스킬에 적용되는 라이선스 | + +> 📖 **공식 문서**: [About Agent Skills](https://docs.github.com/copilot/concepts/agents/about-agent-skills) + +### 첫 번째 스킬 만들기 + +OWASP Top 10 취약점을 점검하는 보안 감사 스킬을 만들어 봅시다: + +```bash +# Create skill directory +mkdir -p .github/skills/security-audit + +# Create the SKILL.md file +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 + +# Test your skill (skills load automatically based on your prompt) +copilot + +> @samples/book-app-project/ Check this code for security vulnerabilities +# Copilot detects "security vulnerabilities" matches your skill +# and automatically applies its OWASP checklist +``` + +**예상 출력** (실제 결과는 달라질 수 있음): + +``` +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 +``` + +--- + +## 좋은 스킬 description 작성하기 + +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 +--- +``` + +> 💡 **팁**: 자연스럽게 질문할 때 사용하는 키워드를 description에 포함하세요. "security review"라고 말한다면 description에도 "security review"를 넣으세요. + +### 스킬과 에이전트 결합하기 + +스킬과 에이전트는 함께 동작합니다. 에이전트는 전문성을 제공하고, 스킬은 구체적인 지시문을 제공합니다: + +```bash +# Start with a code-reviewer agent +copilot --agent code-reviewer + +> Check the book app for quality issues +# code-reviewer agent's expertise combines +# with your code-checklist skill's checklist +``` + +--- + +# 스킬 관리와 공유 + +설치된 스킬을 확인하고, 커뮤니티 스킬을 찾아보고, 직접 만든 스킬을 공유합니다. + +CLI 스킬을 발견, 사용, 생성, 공유하는 사이클을 보여 주는 스킬 관리와 공유 + +--- + +## `/skills` 명령으로 스킬 관리하기 + +`/skills` 명령으로 설치된 스킬을 관리합니다: + +| 명령 | 하는 일 | +|---------|--------------| +| `/skills list` | 설치된 모든 스킬 표시 | +| `/skills info ` | 특정 스킬의 세부 정보 확인 | +| `/skills add ` | 스킬 활성화 (저장소 또는 마켓플레이스에서) | +| `/skills remove ` | 스킬 비활성화 또는 제거 | +| `/skills reload` | SKILL.md 파일을 편집한 뒤 스킬 다시 불러오기 | + +> 💡 **기억하세요**: 프롬프트마다 스킬을 "활성화"할 필요는 없습니다. 한 번 설치된 스킬은 프롬프트가 description과 일치하면 **자동으로 트리거됩니다**. 위 명령들은 어떤 스킬을 사용할 수 있게 할지 관리하기 위한 것이지, 스킬을 사용하기 위한 것이 아닙니다. + +### 예제: 스킬 목록 보기 + +```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 +``` + +--- + +
+동작 모습 보기! + +![List Skills Demo](../../../05-skills/images/list-skills-demo.gif) + +*데모 출력은 다양합니다. 사용하는 모델, 도구, 응답에 따라 화면과 다를 수 있습니다.* + +
+ +--- + +### `/skills reload`는 언제 사용할까요? + +스킬의 SKILL.md 파일을 만들거나 수정한 뒤 `/skills reload`를 실행하면 Copilot을 재시작하지 않고도 변경 사항을 반영할 수 있습니다: + +```bash +# Edit your skill file +# Then in Copilot: +> /skills reload +Skills reloaded successfully. +``` + +> 💡 **참고**: `/compact`로 대화 기록을 요약한 뒤에도 스킬은 계속 유효합니다. 압축 후에 다시 불러올 필요는 없습니다. + +--- + +## 커뮤니티 스킬 찾고 사용하기 + +### 플러그인으로 스킬 설치하기 + +> 💡 **플러그인이란?** 플러그인은 스킬, 에이전트, MCP 서버 구성을 함께 묶을 수 있는 설치 가능한 패키지입니다. Copilot CLI를 위한 "앱 스토어" 확장이라고 생각하면 됩니다. + +`/plugin` 명령으로 이러한 패키지를 둘러보고 설치할 수 있습니다: + +```bash +copilot + +> /plugin list +# Shows installed plugins + +> /plugin marketplace +# Browse available plugins + +> /plugin install +# Install a plugin from the marketplace +``` + +로컬 플러그인 카탈로그를 최신 상태로 유지하려면 다음을 실행해 새로 고치세요: + +```bash +copilot plugin marketplace update +``` + +플러그인은 여러 기능을 함께 묶을 수 있습니다. 하나의 플러그인이 서로 연관된 스킬, 에이전트, MCP 서버 구성을 함께 담고 있을 수도 있습니다. + +### 커뮤니티 스킬 저장소 + +미리 만들어진 스킬은 커뮤니티 저장소에서도 받을 수 있습니다: + +- **[Awesome Copilot](https://github.com/github/awesome-copilot)** - 스킬 문서와 예제를 포함한 공식 GitHub Copilot 리소스 + +### GitHub CLI로 커뮤니티 스킬 설치하기 + +GitHub 저장소에서 스킬을 가장 쉽게 설치하는 방법은 `gh skill install` 명령을 사용하는 것입니다([GitHub CLI v2.90.0 이상](https://github.blog/changelog/2026-04-16-manage-agent-skills-with-github-cli/) 필요): + +```bash +# Browse and interactively select a skill from awesome-copilot +gh skill install github/awesome-copilot + +# Or install a specific skill directly +gh skill install github/awesome-copilot code-checklist + +# Install for personal use across all projects (user scope) +gh skill install github/awesome-copilot code-checklist --scope user +``` + +> ⚠️ **설치 전 확인하세요**: 스킬을 설치하기 전에는 항상 `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. **스킬 만들기 챌린지**: 다음 3가지 항목을 점검하는 `quick-review` 스킬을 만들어 보세요: + - 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` 스킬을 만듭니다. +3. 스킬에는 다음이 포함되어야 합니다: + - 명확한 name과 description (description은 매칭에 매우 중요!) + - 구체적인 형식 규칙 (예: title, author, year, read status로 구성된 마크다운 표) + - 출력 규칙 (예: 읽음 여부에 ✅/❌ 사용, 연도순 정렬) +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`으로 직접 호출도 시도해 보세요. + +**성공 기준**: 책 컬렉션에 대해 질문하면 Copilot이 자동으로 적용하는 동작 가능한 `book-summary` 스킬이 만들어졌습니다. + +
+💡 힌트 (펼쳐 보기) + +**시작 템플릿**: `.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 +# The skill should auto-trigger based on the description match +``` + +**트리거되지 않는다면:** `/skills reload`를 실행한 뒤 다시 물어보세요. + +
+ +### 보너스 챌린지: 커밋 메시지 스킬 + +1. 일관된 형식의 컨벤셔널 커밋 메시지를 생성하는 `commit-message` 스킬을 만드세요. +2. 변경 사항을 스테이징한 뒤 "Generate a commit message for my staged changes"라고 물어 테스트해 보세요. +3. 스킬을 문서화하고 `copilot-skill` 토픽을 달아 GitHub에 공유하세요. + +--- + +
+🔧 흔한 실수와 트러블슈팅 (펼쳐 보기) + +### 흔한 실수 + +| 실수 | 어떤 일이 일어나는가 | 해결 방법 | +|---------|--------------|-----| +| 파일 이름을 `SKILL.md`가 아닌 다른 이름으로 지정 | 스킬이 인식되지 않음 | 파일 이름은 정확히 `SKILL.md`여야 함 | +| 모호한 `description` 필드 | 스킬이 자동으로 불러와지지 않음 | description은 핵심 발견 메커니즘. 구체적인 트리거 단어를 사용 | +| frontmatter에 `name` 또는 `description` 누락 | 스킬 로드 실패 | YAML frontmatter에 두 필드 모두 추가 | +| 잘못된 폴더 위치 | 스킬을 찾지 못함 | `.github/skills/skill-name/`(프로젝트) 또는 `~/.copilot/skills/skill-name/`(개인) 사용 | + +### 트러블슈팅 + +**스킬이 사용되지 않을 때** - 기대했는데 Copilot이 스킬을 사용하지 않는다면: + +1. **description 확인**: 여러분이 묻는 방식과 일치하나요? + ```markdown + # Bad: Too vague + description: Reviews code + + # Good: Includes trigger words + description: Use for code reviews, checking code quality, + finding bugs, security issues, and best practice violations + ``` + +2. **파일 위치 확인**: + ```bash + # Project skills + ls .github/skills/ + + # User 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/ # Folder name + └── SKILL.md # Must be exactly SKILL.md (case-sensitive) +``` + +스킬을 만들거나 수정한 뒤에는 `/skills reload`를 실행해 변경 사항이 반영되도록 하세요. + +**스킬이 로드되는지 확인하기** - Copilot에게 직접 물어보세요: +```bash +> What skills do you have available for checking code quality? +# Copilot will describe relevant skills it found +``` + +**내 스킬이 실제로 동작하는지 어떻게 알 수 있나요?** + +1. **출력 형식 확인**: 스킬이 출력 형식(예: `[CRITICAL]` 태그)을 지정했다면 응답에서 이를 찾아보세요. +2. **직접 묻기**: 응답을 받은 뒤 "Did you use any skills for that?"라고 물어보세요. +3. **있을 때와 없을 때 비교**: 같은 프롬프트를 `--no-custom-instructions`와 함께 실행해 차이를 확인해 보세요: + ```bash + # With skills + copilot --allow-all -p "Review @file.py for security issues" + + # Without skills (baseline comparison) + copilot --allow-all -p "Review @file.py for security issues" --no-custom-instructions + ``` +4. **특정 검사 항목 확인**: 스킬이 구체적인 검사("functions over 50 lines" 등)를 포함한다면 출력에 그것이 등장하는지 확인하세요. + +
+ +--- + +# 요약 + +## 🔑 핵심 정리 + +1. **스킬은 자동입니다**: 프롬프트가 스킬의 description과 일치하면 Copilot이 자동으로 불러옵니다. +2. **직접 호출**: `/skill-name` 슬래시 명령으로 스킬을 직접 호출할 수도 있습니다. +3. **SKILL.md 형식**: YAML frontmatter(name, description, 선택적 license)와 마크다운 지시문으로 구성됩니다. +4. **위치가 중요합니다**: 프로젝트/팀 공유는 `.github/skills/`, 개인 사용은 `~/.copilot/skills/`. +5. **description이 핵심**: 자연스럽게 묻는 방식과 일치하는 description을 작성하세요. + +> 📋 **빠른 참조**: 명령과 단축키 전체 목록은 [GitHub Copilot CLI command reference](https://docs.github.com/en/copilot/reference/cli-command-reference)를 확인하세요. + +--- + +## ➡️ 다음 단계 + +스킬은 자동 로드되는 지시문으로 Copilot이 할 수 있는 일을 확장합니다. 그렇다면 외부 서비스에 연결하는 것은 어떨까요? 그것이 바로 MCP의 역할입니다. + +**[Chapter 06: MCP Servers](../06-mcp-servers/README.md)**에서는 다음을 배웁니다: + +- MCP(Model Context Protocol)란 무엇인가 +- GitHub, 파일 시스템, 문서 서비스에 연결하기 +- MCP 서버 구성하기 +- 다중 서버 워크플로 + +--- + +**[← Chapter 04로 돌아가기](../04-agents-custom-instructions/README.md)** | **[Chapter 06으로 계속하기 →](../06-mcp-servers/README.md)** diff --git a/localization/ko-kr/06-mcp-servers/README.md b/localization/ko-kr/06-mcp-servers/README.md new file mode 100644 index 00000000..75fdc8c7 --- /dev/null +++ b/localization/ko-kr/06-mcp-servers/README.md @@ -0,0 +1,974 @@ +![Chapter 06: MCP Servers](../../../06-mcp-servers/images/chapter-header.png) + +> **Copilot이 GitHub 이슈를 읽고, 데이터베이스를 확인하고, PR까지 만들 수 있다면... 그것도 모두 터미널에서 가능하다면 어떨까요?** + +지금까지 Copilot은 여러분이 직접 제공한 것만 다룰 수 있었습니다. `@`로 참조한 파일, 대화 기록, 그리고 자체 학습 데이터가 그것이죠. 그런데 만약 Copilot이 스스로 GitHub 저장소를 확인하거나, 프로젝트 파일을 둘러보거나, 라이브러리의 최신 문서를 찾아볼 수 있다면 어떨까요? + +바로 그것이 MCP(Model Context Protocol)가 하는 일입니다. MCP는 Copilot을 외부 서비스에 연결해 실시간의 실제 데이터에 접근할 수 있게 해주는 방식입니다. Copilot이 연결되는 각 서비스를 "MCP 서버"라고 부릅니다. 이 챕터에서는 이러한 연결을 몇 가지 설정해 보고, 어떻게 Copilot을 훨씬 더 유용하게 만드는지 직접 확인해 보겠습니다. + +> 💡 **이미 MCP에 익숙하신가요?** [퀵 스타트로 바로 이동](#-use-the-built-in-github-mcp)해서 정상 동작을 확인하고 서버를 구성해 보세요. + +## 🎯 학습 목표 + +이 챕터를 마치면 다음을 할 수 있습니다: + +- MCP가 무엇이며 왜 중요한지 이해하기 +- `/mcp` 명령으로 MCP 서버 관리하기 +- GitHub, 파일 시스템, 문서용 MCP 서버 구성하기 +- book app 프로젝트에서 MCP 기반 워크플로 사용하기 +- 커스텀 MCP 서버를 언제, 어떻게 만들지 알기 (선택) + +> ⏱️ **예상 소요 시간**: 약 50분 (읽기 15분 + 실습 35분) + +--- + +## 🧩 실생활 비유: 브라우저 확장 프로그램 + +MCP 서버는 브라우저 확장 프로그램과 같습니다 + +MCP 서버를 브라우저 확장 프로그램이라고 생각해 보세요. 브라우저 자체로도 웹 페이지를 보여줄 수 있지만, 확장 프로그램은 브라우저를 추가 서비스에 연결해 줍니다: + +| 브라우저 확장 | 연결되는 대상 | MCP 등가물 | +|-------------------|---------------------|----------------| +| 비밀번호 관리자 | 비밀번호 저장소 | **GitHub MCP** → 저장소, 이슈, PR | +| Grammarly | 글쓰기 분석 서비스 | **Context7 MCP** → 라이브러리 문서 | +| 파일 관리자 | 클라우드 저장소 | **Filesystem MCP** → 로컬 프로젝트 파일 | + +확장 프로그램이 없어도 브라우저는 충분히 유용하지만, 확장 프로그램이 있으면 강력한 도구가 됩니다. MCP 서버도 Copilot에게 같은 일을 합니다. 실시간의 실제 데이터 소스에 연결해 주어, GitHub 이슈를 읽고, 파일 시스템을 탐색하고, 최신 문서를 가져오는 등 더 많은 일을 자동으로 할 수 있게 해줍니다. + +***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 관리 명령을 보고 싶으신가요?** 채팅 안에서 `/mcp` 슬래시 명령으로 또는 터미널에서 직접 `copilot mcp`로 서버를 관리할 수 있습니다. 이 챕터 끝에 있는 [전체 명령 레퍼런스](#-additional-mcp-commands)를 참고하세요. + +
+🎬 직접 동작 확인하기! + +![MCP Status Demo](../../../06-mcp-servers/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이 여러분의 실제 개발 환경을 인식하도록 만들어 줍니다. + +> 📚 **공식 문서**: GitHub Copilot에서 MCP가 어떻게 동작하는지 더 깊이 알아보려면 [About MCP](https://docs.github.com/copilot/concepts/context/mcp)를 참고하세요. + +--- + +# MCP 서버 구성하기 + +MCP 서버 구성을 나타내는 전문 오디오 믹싱 보드의 노브와 슬라이더를 조정하는 손 + +이제 MCP가 동작하는 모습을 보았으니, 추가 서버를 설정해 봅시다. 서버를 추가하는 방법은 두 가지입니다: **내장 레지스트리에서 추가**(가장 쉬움 — CLI에서 가이드 설정)하거나 **구성 파일을 수동으로 편집**(더 유연함)하는 것입니다. 어떤 방법을 선택할지 모르겠다면 레지스트리 옵션부터 시작해 보세요. + +--- + +## 레지스트리에서 MCP 서버 설치하기 + +CLI에는 인기 있는 서버를 발견하고 가이드 설정으로 설치할 수 있는 내장 MCP 서버 레지스트리가 있습니다. JSON 편집이 필요 없습니다. + +```bash +copilot + +> /mcp search +``` + +Copilot이 사용 가능한 서버를 보여주는 인터랙티브 선택기를 엽니다. 하나를 선택하면 CLI가 필요한 구성(API 키, 경로 등)을 안내하고 자동으로 구성에 추가합니다. + +> 💡 **레지스트리를 사용하는 이유?** 시작하기 가장 쉬운 방법입니다. npm 패키지 이름, 명령 인자, JSON 구조를 알 필요가 없습니다. CLI가 모두 처리해 줍니다. + +--- + +## MCP 구성 파일 + +MCP 서버는 `~/.copilot/mcp-config.json`(사용자 수준, 모든 프로젝트에 적용) 또는 `.mcp.json`(프로젝트 수준, 프로젝트 루트에 위치)에서 구성됩니다. 위에서 `/mcp search`를 사용했다면 CLI가 이미 이 파일을 만들거나 업데이트했지만, 커스터마이징을 위해 형식을 이해해 두면 유용합니다. + +> ⚠️ **참고**: `.vscode/mcp.json`은 더 이상 MCP 구성 소스로 지원되지 않습니다. 기존 `.vscode/mcp.json`이 있다면 프로젝트 루트의 `.mcp.json`으로 마이그레이션하세요. CLI는 오래된 구성 파일을 감지하면 마이그레이션 힌트를 표시합니다. + +```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 서버](#filesystem-server) | +| 최신 라이브러리 문서 가져오기 | [Context7 서버](#context7-server-documentation) | +| 선택적 추가 기능 살펴보기 (커스텀 서버, web_fetch) | [기본을 넘어서](#beyond-the-basics) | + +
+Filesystem 서버 - Copilot이 프로젝트 파일을 탐색하게 하기 + + +### Filesystem 서버 + +```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 서버(filesystem, 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에는 어떤 URL의 콘텐츠든 가져올 수 있는 내장 `web_fetch` 도구가 포함되어 있습니다. 터미널을 떠나지 않고도 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, filesystem, Context7)가 대부분의 사용 사례를 다루므로 이는 완전히 선택 사항입니다. + +📖 book app을 예시로 한 전체 워크스루는 [커스텀 MCP 서버 가이드](mcp-custom-server.md)를 참고하세요. + +📚 더 많은 배경 지식은 [MCP for Beginners 코스](https://github.com/microsoft/mcp-for-beginners)를 참고하세요. + +
+ + + +### 전체 구성 파일 + +다음은 filesystem과 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`으로 저장하거나, 프로젝트별 구성을 위해 프로젝트 루트의 `.mcp.json`으로 저장하세요. + +--- + +# MCP 서버 사용하기 + +이제 MCP 서버를 구성했으니, 무엇을 할 수 있는지 살펴봅시다. + +MCP 서버 사용하기 - 개발자 CLI가 GitHub, Filesystem, Context7, 커스텀/Web Fetch 서버에 연결된 허브 앤 스포크 다이어그램 + +--- + +## 서버 사용 예시 + +**탐색할 서버를 고르거나 순서대로 진행해 보세요.** + +| 시도해 보고 싶은 것... | 이동 | +|---|---| +| GitHub 저장소, 이슈, PR | [GitHub 서버](#github-server-built-in) | +| 프로젝트 파일 탐색 | [Filesystem 서버 사용](#filesystem-server-usage) | +| 라이브러리 문서 조회 | [Context7 서버 사용](#context7-server-usage) | +| 커스텀 서버, Microsoft Learn MCP 및 web_fetch 사용 | [기본을 넘어서 - 사용](#beyond-the-basics-usage) | + +
+GitHub 서버 (내장) - 저장소, 이슈, PR 등에 접근 + + +### GitHub 서버 (내장) + +GitHub MCP 서버는 **내장되어 있습니다**. Copilot에 로그인했다면(초기 설정 중에 했을 것입니다), 이미 동작합니다. 구성이 필요 없습니다! + +> 💡 **동작하지 않나요?** `/login`을 실행하여 GitHub로 다시 인증하세요. + +
+Dev Container에서의 인증 + +- **GitHub Codespaces** (권장): 인증이 자동입니다. `gh` CLI가 Codespace 토큰을 상속받습니다. 별도의 작업이 필요 없습니다. +- **로컬 dev container (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 +``` + +
+ +| 기능 | 예시 | +|---------|----------| +| **저장소 정보** | 커밋, 브랜치, 기여자 보기 | +| **이슈** | 이슈 나열, 생성, 검색, 댓글 작성 | +| **풀 리퀘스트** | PR 보기, diff 확인, 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 +``` + +> 💡 **자신의 포크에서 작업 중이신가요?** 이 코스 저장소를 포크했다면 이슈와 풀 리퀘스트를 만드는 것 같은 쓰기 작업도 시도해 볼 수 있습니다. 아래 연습에서 함께 실습해 봅니다. + +> ⚠️ **결과가 보이지 않나요?** GitHub MCP는 로컬 파일이 아니라 저장소의 원격(github.com)을 대상으로 동작합니다. 저장소에 원격이 있는지 확인하세요: `git remote -v`로 확인할 수 있습니다. + +
+ +
+Filesystem 서버 - 프로젝트 파일 탐색 및 분석 + + +### Filesystem 서버 + +구성이 완료되면 filesystem 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.md)를 보고 book-lookup 서버를 구축했다면, 책 컬렉션을 직접 조회할 수 있습니다: + +```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**: 내장 `web_fetch` 도구를 사용하여 어떤 URL에서든 콘텐츠를 가져올 수 있습니다: + +```bash +copilot + +> Fetch and summarize the README from https://github.com/facebook/react +``` + +
+ +--- + +## 다중 서버 워크플로 + +이 워크플로들은 개발자들이 "이제는 이거 없이는 일하고 싶지 않아"라고 말하는 이유를 보여줍니다. 각 예시는 단일 세션에서 여러 MCP 서버를 결합합니다. + +MCP를 사용한 이슈에서 PR까지 워크플로 - GitHub 이슈를 받는 것부터 풀 리퀘스트를 만드는 것까지의 전체 흐름을 보여줌 + +*완전한 MCP 워크플로: GitHub MCP가 저장소 데이터를 가져오고, Filesystem MCP가 코드를 찾고, Context7 MCP가 모범 사례를 제공하며, Copilot이 분석을 처리합니다* + +아래 각 예시는 독립적입니다. **관심 있는 것을 골라 보거나 모두 읽어 보세요.** + +| 보고 싶은 것... | 이동 | +|---|---| +| 여러 서버가 함께 동작하는 모습 | [다중 서버 탐색](#multi-server-exploration) | +| 한 세션에서 이슈에서 PR까지 진행 | [이슈에서 PR로 워크플로](#issue-to-pr-workflow) | +| 빠른 프로젝트 상태 점검 | [상태 대시보드](#health-dashboard) | + +
+다중 서버 탐색 - 한 세션에서 filesystem, GitHub, Context7 결합 + + +#### 여러 MCP 서버로 Book App 탐색하기 + +```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 Workflow Demo](../../../06-mcp-servers/images/mcp-workflow-demo.gif) + +*데모 출력은 다를 수 있습니다. 사용하는 모델, 도구, 응답은 여기 표시된 것과 다를 수 있습니다.* + +
+ +**결과**: 코드 탐색 → 이력 검토 → 모범 사례 조회 → 개선 계획. **모두 하나의 터미널 세션에서, 세 개의 MCP 서버를 함께 사용합니다.** + +
+ +
+이슈에서 PR로 워크플로 - 터미널을 떠나지 않고 GitHub 이슈에서 풀 리퀘스트까지 진행 + + +#### 이슈에서 PR로 워크플로 (자신의 저장소에서) + +쓰기 권한이 있는 자신의 포크나 저장소에서 가장 잘 동작합니다: + +> 💡 **지금 시도해 볼 수 없어도 걱정하지 마세요.** 읽기 전용 클론에 있다면 과제에서 연습하게 됩니다. 지금은 흐름을 이해하기 위해 그냥 읽어 보세요. + +```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 implements year validation in 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 +``` + +**복사-붙여넣기 없음. 컨텍스트 전환 없음. 하나의 터미널 세션.** + +
+ +
+상태 대시보드 - 여러 서버를 사용한 빠른 프로젝트 상태 점검 + + +#### 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를 이해했고, 서버 구성 방법을 보았으며, 실제 워크플로가 동작하는 모습을 확인했습니다. 이제 직접 시도해 볼 시간입니다. + +--- + +## ▶️ 직접 해보기 + +이제 여러분 차례입니다! 다음 연습을 완료하여 book app 프로젝트에서 MCP 서버를 사용하는 방법을 연습해 보세요. + +### 연습 1: MCP 상태 확인하기 + +먼저 어떤 MCP 서버가 사용 가능한지 확인해 봅시다: + +```bash +copilot + +> /mcp show +``` + +GitHub 서버가 활성화된 상태로 표시되어야 합니다. 그렇지 않다면 `/login`을 실행하여 인증하세요. + +--- + +### 연습 2: Filesystem MCP로 Book App 탐색하기 + +filesystem 서버를 구성했다면 이를 사용해 book app을 탐색해 보세요: + +```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`와 그 함수들을 나열합니다. + +> 💡 **filesystem MCP를 아직 구성하지 않으셨나요?** 위 [전체 구성](#complete-configuration-file) 섹션에서 구성 파일을 만드세요. 그런 다음 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 서버 결합하기 + +이제 단일 세션에서 filesystem과 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 파일을 읽고(filesystem MCP) "The Hobbit", "1984", "Dune", "To Kill a Mockingbird", "Mysterious Book" 등 5권의 책을 나열한 다음, GitHub에서 커밋 이력을 조회합니다. + +**자가 점검**: 왜 "내 저장소의 커밋 이력 확인"이 수동으로 `git log`를 실행하고 그 출력을 프롬프트에 붙여넣는 것보다 나은지 설명할 수 있다면 MCP를 이해한 것입니다. + +--- + +## 📝 과제 + +### 메인 챌린지: Book App MCP 탐색 + +book app 프로젝트에서 MCP 서버를 함께 사용하는 연습을 합니다. 단일 Copilot 세션에서 다음 단계를 완료하세요: + +1. **MCP 동작 확인**: `/mcp show`를 실행하고 최소한 GitHub 서버가 활성화되어 있는지 확인하세요 +2. **filesystem MCP 설정**(아직 안 했다면): filesystem 서버 구성으로 `~/.copilot/mcp-config.json`을 만드세요 +3. **코드 탐색**: Copilot에게 filesystem 서버를 사용하도록 요청하세요: + - `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/`의 파일을 변경한 최근 커밋 나열 + - 열린 이슈나 풀 리퀘스트가 있는지 확인 +5. **서버 결합**: 단일 프롬프트에서 Copilot에게 다음을 요청하세요: + - `samples/book-app-project/tests/test_books.py`의 테스트 파일 읽기 + - 테스트된 함수와 `books.py`의 모든 함수 비교 + - 누락된 테스트 커버리지 요약 + +**성공 기준**: 단일 Copilot 세션에서 filesystem과 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 +} +``` +저자는 비어 있고 연도가 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.md)를 따라 어떤 API에든 연결되는 자신만의 MCP 서버를 Python으로 구축해 보세요. + +--- + +
+🔧 흔한 실수 및 문제 해결 (펼치려면 클릭) + +### 흔한 실수 + +| 실수 | 결과 | 해결 | +|---------|--------------|-----| +| GitHub MCP가 내장임을 모름 | 수동으로 설치/구성하려 함 | GitHub MCP는 기본 포함입니다. 그냥 시도해 보세요: "List the recent commits in this repo" | +| 잘못된 위치에서 구성 파일을 찾음 | MCP 설정을 찾거나 편집할 수 없음 | 사용자 수준 구성은 `~/.copilot/mcp-config.json`에, 프로젝트 수준은 프로젝트 루트의 `.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 +# Run the server command manually to see errors +npx -y @modelcontextprotocol/server-github +``` + +**MCP 도구가 사용 불가** - 서버가 활성화되어 있는지 확인하세요: +```bash +copilot + +> /mcp show +# Check if server is listed and enabled +``` + +서버가 비활성화된 경우 다시 활성화하는 방법은 아래의 [추가 `/mcp` 명령](#-additional-mcp-commands)을 참고하세요. + +
+ +--- + +
+📚 추가 MCP 명령 (펼치려면 클릭) + + +MCP 서버는 두 가지 방법으로 관리할 수 있습니다: **채팅 세션 내에서 슬래시 명령** 사용, 또는 터미널에서 직접 **`copilot mcp` 명령** 사용(채팅 세션 필요 없음). + +### 옵션 1: 슬래시 명령 (채팅 세션 내에서) + +이미 `copilot` 안에 있을 때 사용합니다: + +| 명령 | 동작 | +|---------|--------------| +| `/mcp show` | 구성된 모든 MCP 서버와 상태 표시 | +| `/mcp add` | 새 서버 추가를 위한 인터랙티브 설정 | +| `/mcp edit ` | 기존 서버 구성 편집 | +| `/mcp enable ` | 비활성화된 서버 활성화 (세션 간 유지) | +| `/mcp disable ` | 서버 비활성화 (세션 간 유지) | +| `/mcp delete ` | 서버 영구 제거 | +| `/mcp auth ` | OAuth를 사용하는 MCP 서버로 다시 인증 (예: 계정 전환 후) | + +### 옵션 2: `copilot mcp` 명령 (터미널에서) + +채팅 세션을 먼저 시작하지 않고도 터미널에서 직접 MCP 서버를 관리할 수 있습니다: + +```bash +# List all configured MCP servers +copilot mcp list + +# Enable a server +copilot mcp enable filesystem + +# Disable a server +copilot mcp disable context7 +``` + +> 💡 **언제 어느 것을 사용해야 하나요?** 이미 채팅 세션에 있을 때는 `/mcp` 슬래시 명령을 사용하세요. 세션을 시작하기 전에 서버 설정을 빠르게 확인하거나 변경하고 싶을 때는 터미널에서 `copilot mcp`를 사용하세요. + +이 코스의 대부분에서 필요한 것은 `/mcp show`뿐입니다. 다른 명령들은 시간이 지나면서 더 많은 서버를 관리하게 될 때 유용해집니다. + +
+ +--- + +# 요약 + +## 🔑 핵심 정리 + +1. **MCP**는 Copilot을 외부 서비스(GitHub, 파일 시스템, 문서)에 연결합니다 +2. **GitHub MCP는 내장되어 있습니다** - 구성이 필요 없으며, `/login`만 하면 됩니다 +3. **Filesystem과 Context7**은 `~/.copilot/mcp-config.json`을 통해 구성됩니다 +4. **다중 서버 워크플로**는 단일 세션에서 여러 소스의 데이터를 결합합니다 +5. **두 가지 방법으로 서버 관리**: 채팅 안에서 `/mcp` 슬래시 명령을 사용하거나, 터미널에서 `copilot mcp`를 사용하세요 +6. **커스텀 서버**는 어떤 API에든 연결할 수 있게 해줍니다 (선택, 부록 가이드에서 다룸) + +> 📋 **빠른 참조**: 명령과 단축키의 전체 목록은 [GitHub Copilot CLI 명령 레퍼런스](https://docs.github.com/en/copilot/reference/cli-command-reference)를 참고하세요. + +--- + +## ➡️ 다음 단계 + +이제 모든 구성 요소를 갖추셨습니다: 모드, 컨텍스트, 워크플로, 에이전트, 스킬, MCP. 이제 모두 합쳐 볼 시간입니다. + +**[챕터 07: 모두 합치기](../07-putting-it-together/README.md)**에서는 다음을 배웁니다: + +- 통합된 워크플로에서 에이전트, 스킬, MCP 결합하기 +- 아이디어부터 병합된 PR까지 완전한 기능 개발 +- 훅을 통한 자동화 +- 팀 환경을 위한 모범 사례 + +--- + +**[← 챕터 05로 돌아가기](../05-skills/README.md)** | **[챕터 07로 계속 →](../07-putting-it-together/README.md)** diff --git a/localization/ko-kr/06-mcp-servers/mcp-custom-server.md b/localization/ko-kr/06-mcp-servers/mcp-custom-server.md new file mode 100644 index 00000000..1f058d7f --- /dev/null +++ b/localization/ko-kr/06-mcp-servers/mcp-custom-server.md @@ -0,0 +1,176 @@ +# 커스텀 MCP 서버 만들기 + +> ⚠️ **이 콘텐츠는 완전히 선택 사항입니다.** 미리 만들어진 MCP 서버(GitHub, filesystem, Context7)만 사용해도 Copilot CLI로 매우 생산적으로 작업할 수 있습니다. 이 가이드는 Copilot을 사내 커스텀 API에 연결하고 싶은 개발자를 위한 것입니다. 더 자세한 내용은 [MCP for Beginners 코스](https://github.com/microsoft/mcp-for-beginners)를 참고해 보세요. +> +> **사전 준비:** +> - Python에 익숙할 것 +> - `async`/`await` 패턴 이해 +> - 시스템에 `pip` 설치 (이 dev container에는 포함되어 있습니다) +> +> **[← 6장으로 돌아가기: MCP 서버](README.md)** + +--- + +Copilot을 여러분의 API에 연결하고 싶으신가요? 이 코스 전반에서 사용해 온 book app 프로젝트와 연결되는, 책 정보를 조회하는 간단한 MCP 서버를 Python으로 만드는 방법을 소개합니다. + +## 프로젝트 설정 + +```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 스키마를 작성할 필요가 없습니다! + +## 설정 + +`~/.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 for Beginners 코스](https://github.com/microsoft/mcp-for-beginners) + +--- + +**[← 6장으로 돌아가기: MCP 서버](README.md)** diff --git a/localization/ko-kr/07-putting-it-together/README.md b/localization/ko-kr/07-putting-it-together/README.md new file mode 100644 index 00000000..dc03cd03 --- /dev/null +++ b/localization/ko-kr/07-putting-it-together/README.md @@ -0,0 +1,512 @@ +![7장: 모두 합치기](../../../07-putting-it-together/images/chapter-header.png) + +> **지금까지 배운 모든 것이 이곳에서 하나로 합쳐집니다. 아이디어에서 머지된 PR까지, 한 번의 세션으로 끝내 보세요.** + +이번 장에서는 지금까지 배운 모든 내용을 하나의 완성된 워크플로로 통합해 봅니다. 다중 에이전트 협업으로 기능을 만들고, 커밋 전에 보안 이슈를 잡아내는 pre-commit 훅을 설정하며, Copilot을 CI/CD 파이프라인에 통합하고, 단일 터미널 세션 안에서 기능 아이디어를 머지된 PR로 끌고 가는 과정을 익힙니다. 바로 이 지점에서 GitHub Copilot CLI는 진짜 의미의 생산성 증폭기가 됩니다. + +> 💡 **참고**: 이번 장은 지금까지 배운 모든 것을 결합하는 방법을 보여 줍니다. **생산적으로 작업하기 위해 반드시 에이전트, 스킬, MCP가 필요한 것은 아닙니다(물론 매우 유용할 수 있습니다).** 핵심 워크플로인 설명 → 계획 → 구현 → 테스트 → 리뷰 → 배포는 0~3장에서 다룬 기본 기능만으로도 충분히 동작합니다. + +## 🎯 학습 목표 + +이 장을 마치면 다음을 할 수 있습니다: + +- 에이전트, 스킬, MCP(Model Context Protocol)를 통합된 워크플로 안에서 결합하기 +- 여러 도구를 함께 활용해 완성된 기능 만들기 +- 훅으로 기본적인 자동화 구성하기 +- 전문적인 개발을 위한 모범 사례 적용하기 + +> ⏱️ **예상 소요 시간**: 약 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, use /pr to operate on the pull request for the current branch +> /pr [view|create|fix|auto] + +# Or ask naturally if you want Copilot to draft it from the terminal +> 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가 하나의 통합 워크플로로 결합되는 모습 + +4~6장을 마친 파워 유저를 위해, 다음 워크플로들은 에이전트와 스킬, MCP가 어떻게 효율을 배가시키는지 보여 줍니다. + +## 통합 패턴 + +다음은 모든 것을 결합할 때 머릿속에 그릴 멘탈 모델입니다: + +통합 패턴 - 4단계 워크플로: 컨텍스트 수집(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 훅은 팀 단위에서 유용하지만, 생산적으로 작업하기 위해 꼭 필요한 것은 아닙니다. 이제 막 시작하는 단계라면 건너뛰어도 됩니다. +> +> ⚠️ **성능 참고**: 이 훅은 스테이징된 파일마다 `copilot -p`를 호출하므로 파일당 몇 초가 소요됩니다. 커밋 규모가 크다면 핵심 파일로만 제한하거나, `/review`를 통해 수동으로 리뷰하는 방식을 고려해 보세요. + +**git 훅**은 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 사용자**: `timeout` 명령은 macOS에 기본 포함되어 있지 않습니다. `brew install coreutils`로 설치하거나, `timeout 60` 부분을 타임아웃 가드 없이 단순한 호출로 바꿔 사용하세요. + +> 📚 **공식 문서**: 훅 API 전체는 [Use hooks](https://docs.github.com/copilot/how-tos/copilot-cli/use-hooks) 및 [Hooks configuration reference](https://docs.github.com/copilot/reference/hooks-configuration) 문서를 참고하세요. +> +> 💡 **내장 대안**: Copilot CLI에는 pre-commit과 같은 이벤트에서 자동 실행되는 내장 훅 시스템(`copilot hooks`)도 있습니다. 위처럼 직접 구성하는 git 훅은 모든 것을 세밀하게 제어할 수 있는 반면, 내장 시스템은 설정이 더 간단합니다. 위의 공식 문서를 참고해 자신의 워크플로에 맞는 방식을 선택하세요. + +이제 모든 커밋마다 빠른 보안 리뷰가 수행됩니다: + +```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으로 워크플로를 재사용 가능하게 만들기 + +워크플로를 위키에만 정리해 두는 대신, 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 리뷰를 자동화할 수 있습니다. 리뷰 댓글을 자동으로 게시하고 critical 이슈만 필터링하는 등의 기능을 포함합니다. + +> 📖 **더 알아보기**: 완전한 GitHub Actions 워크플로, 구성 옵션, 트러블슈팅 팁은 [CI/CD 통합](../appendices/ci-cd-integration.md) 문서를 참고하세요. + +--- + +# 실습 + +모니터에 코드가 띄워져 있고, 램프와 커피잔, 헤드폰이 놓인 따뜻한 분위기의 데스크 - 실습을 위한 준비된 모습 + +전체 워크플로를 직접 실습해 봅시다. + +--- + +## ▶️ 직접 해 보기 + +데모를 마쳤다면, 다음 변형들도 시도해 보세요: + +1. **엔드 투 엔드 챌린지**: 작은 기능 하나를 골라 보세요(예: "안 읽은 책 목록", "CSV로 내보내기"). 다음과 같이 전체 워크플로를 사용합니다: + - `/plan`으로 계획 세우기 + - 에이전트(python-reviewer, pytest-helper)로 설계 + - 구현 + - 테스트 생성 + - PR 생성 + +2. **자동화 챌린지**: 코드 리뷰 자동화 워크플로의 pre-commit 훅을 설정해 보세요. 의도적으로 파일 경로 취약점을 포함한 커밋을 시도해 봅니다. 차단되나요? + +3. **나만의 프로덕션 워크플로**: 자주 수행하는 작업에 대해 여러분만의 워크플로를 설계해 체크리스트로 정리해 보세요. 어떤 부분을 스킬, 에이전트, 훅으로 자동화할 수 있을까요? + +**자기 점검**: 동료에게 에이전트, 스킬, MCP가 어떻게 함께 동작하는지, 그리고 각각을 언제 사용해야 하는지 설명할 수 있다면 이 강의를 마친 것입니다. + +--- + +## 📝 과제 + +### 메인 챌린지: 엔드 투 엔드 기능 만들기 + +실습 예제에서는 "안 읽은 책 목록" 기능을 만들어 보았습니다. 이번에는 다른 기능인 **연도 범위로 책 검색하기**를 가지고 전체 워크플로를 연습해 보세요: + +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를 사용해 기획, 구현, 테스트, 문서화, 리뷰까지 포함한 전체 흐름으로 아이디어부터 커밋까지 기능을 완성했다면 성공입니다. + +> 💡 **보너스**: 4장에서 에이전트를 설정해 두었다면, 직접 만든 커스텀 에이전트도 활용해 보세요. 예를 들어 구현 리뷰용 error-handler 에이전트와 README 업데이트용 doc-writer 에이전트를 만들어 사용할 수 있습니다. + +
+💡 힌트 (클릭해서 펼치기) + +**이번 장 첫 부분의 ["한 세션으로 아이디어부터 머지된 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 | +| 커밋 전에 리뷰하지 않기 | 보안 이슈나 버그가 그대로 통과합니다 | 항상 `/review`를 실행하거나 [pre-commit 훅](#workflow-2-code-review-automation-optional)을 사용하세요 | +| 팀과 워크플로를 공유하는 것을 잊기 | 팀원마다 같은 일을 다시 만들게 됩니다 | 공용 에이전트, 스킬, 인스트럭션에 패턴을 문서화하세요 | + +
+ +--- + +# 정리 + +## 🔑 핵심 정리 + +1. **통합 > 분리**: 도구를 결합할 때 영향력이 극대화됩니다. +2. **컨텍스트가 먼저**: 분석 전에 필요한 컨텍스트를 항상 모으세요. +3. **에이전트는 분석, 스킬은 실행**: 일에 맞는 도구를 사용하세요. +4. **반복은 자동화하기**: 훅과 스크립트는 효율을 배가시킵니다. +5. **워크플로를 문서화하기**: 공유 가능한 패턴은 팀 전체에 도움이 됩니다. + +> 📋 **빠른 참고**: 전체 명령과 단축키 목록은 [GitHub Copilot CLI 명령 레퍼런스](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 문서](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) +- [MCP 서버 레지스트리](https://github.com/modelcontextprotocol/servers) +- [커뮤니티 스킬](https://github.com/topics/copilot-skill) + +--- + +**정말 잘하셨습니다! 이제 멋진 것을 직접 만들어 볼 차례입니다.** + +**[← 6장으로 돌아가기](../06-mcp-servers/README.md)** | **[강의 홈으로 돌아가기 →](../README.md)** diff --git a/localization/ko-kr/README.md b/localization/ko-kr/README.md new file mode 100644 index 00000000..ef9d4717 --- /dev/null +++ b/localization/ko-kr/README.md @@ -0,0 +1,110 @@ +![GitHub Copilot CLI for Beginners](../../images/copilot-banner.png) + +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](../../LICENSE)  +[![Open project in 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)  +[![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  +[![Join 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) + +# GitHub Copilot CLI for Beginners + +> **✨ AI 기반 커맨드라인 어시스턴트로 개발 워크플로우를 강화하는 방법을 배워 보세요.** + +GitHub Copilot CLI는 AI 어시스턴트를 터미널로 직접 가져옵니다. 브라우저나 코드 에디터로 전환하지 않고도, 커맨드라인을 떠나지 않고 질문하고, 완전한 기능의 애플리케이션을 생성하고, 코드를 검토하고, 테스트를 생성하고, 문제를 디버그할 수 있습니다. + +24시간 7일 내내 코드를 읽고, 혼란스러운 패턴을 설명하고, 더 빠르게 작업할 수 있도록 도와주는 지식이 풍부한 동료가 항상 곁에 있는 것과 같습니다! + +> 📘 **웹 환경을 선호하시나요?** 이 강의를 GitHub에서 바로 따라가거나, [Awesome Copilot](https://awesome-copilot.github.com/learning-hub/cli-for-beginners/)에서 더 일반적인 브라우징 환경으로 볼 수 있습니다. + +이 강의는 다음 분들을 대상으로 합니다: + +- **커맨드라인에서 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 등 | 에이전트 모드, 채팅, 인라인 제안 | +| [**Copilot on GitHub.com**](https://github.com/copilot) | GitHub | 저장소에 대한 몰입형 채팅, 에이전트 생성 등 | +| [**GitHub Copilot 클라우드 에이전트**](https://docs.github.com/copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks) | GitHub | 에이전트에게 이슈를 할당하면 PR을 받아볼 수 있습니다 | + +이 강의는 **GitHub Copilot CLI**에 집중하여, AI 어시스턴트를 터미널로 직접 가져옵니다. + +## 📚 강의 구성 + +![GitHub Copilot CLI 학습 경로](../../images/learning-path.png) + +| 챕터 | 제목 | 학습 내용 | +|:-------:|-------|-------------------| +| 00 | 🚀 [빠른 시작](./00-quick-start/README.md) | 설치 및 확인 | +| 01 | 👋 [첫걸음](./01-setup-and-first-steps/README.md) | 라이브 데모 + 세 가지 상호작용 모드 | +| 02 | 🔍 [컨텍스트와 대화](./02-context-conversations/README.md) | 멀티 파일 프로젝트 분석 | +| 03 | ⚡ [개발 워크플로우](./03-development-workflows/README.md) | 코드 리뷰, 디버그, 테스트 생성 | +| 04 | 🤖 [특화된 AI 어시스턴트 만들기](./04-agents-custom-instructions/README.md) | 워크플로우에 맞는 커스텀 에이전트 | +| 05 | 🛠️ [반복 작업 자동화](./05-skills/README.md) | 자동으로 로드되는 스킬 | +| 06 | 🔌 [GitHub, 데이터베이스 & API 연결](./06-mcp-servers/README.md) | MCP 서버 통합 | +| 07 | 🎯 [모든 것을 합쳐서](./07-putting-it-together/README.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를 효과적으로 사용하는 데 도움이 되는 명령어와 키보드 단축키를 찾아볼 수 있습니다. + +## 🙋 도움 받기 + +- 🐛 **버그를 발견하셨나요?** [이슈 열기](https://github.com/github/copilot-cli-for-beginners/issues) +- 📚 **공식 문서:** [GitHub Copilot CLI 문서](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) + +## 기여하기 + +> **참고**: 강의에 사용된 코드는 리뷰, 설명, 디버깅 중 특정 유형의 출력을 생성하도록 설계되었으므로, 기존 코드를 변경하는 PR은 수락할 수 없습니다. + +**기여 방법:** + +1. 이 저장소를 포크하고 로컬 머신에 클론합니다 +2. 기능 브랜치를 만듭니다 (`git checkout -b my-improvement`) +3. 변경 사항을 적용합니다 +4. 풀 리퀘스트를 제출합니다 + +## 라이선스 + +이 프로젝트는 MIT 오픈 소스 라이선스 조건에 따라 라이선스가 부여됩니다. 전체 조건은 [LICENSE](../../LICENSE) 파일을 참조해 주세요. diff --git a/localization/ko-kr/appendices/README.md b/localization/ko-kr/appendices/README.md new file mode 100644 index 00000000..a1ebd743 --- /dev/null +++ b/localization/ko-kr/appendices/README.md @@ -0,0 +1,12 @@ +# 부록 + +이 부록들은 본 강의의 핵심 내용을 보완하는 추가 주제를 다룹니다. 해당 기능이 필요할 때 골라서 읽을 수 있는 선택 자료입니다. + +| 부록 | 설명 | 사전 학습 | +|----------|-------------|--------------| +| [추가 컨텍스트 기능](additional-context.md) | 이미지 작업과 다중 디렉터리 권한 다루기 | 2장 | +| [CI/CD 통합](ci-cd-integration.md) | 자동화된 리뷰를 위한 GitHub Actions 워크플로 | 7장 | + +--- + +**[← 강의 홈으로 돌아가기](../README.md)** diff --git a/localization/ko-kr/appendices/additional-context.md b/localization/ko-kr/appendices/additional-context.md new file mode 100644 index 00000000..31632588 --- /dev/null +++ b/localization/ko-kr/appendices/additional-context.md @@ -0,0 +1,140 @@ +# 추가 컨텍스트 기능 + +> 📖 **사전 학습**: 이 부록을 읽기 전에 [2장: 컨텍스트와 대화](../02-context-conversations/README.md)를 먼저 마쳐 주세요. + +이 부록에서는 두 가지 추가 컨텍스트 기능을 다룹니다. 이미지 다루기와 여러 디렉터리에 대한 권한 관리입니다. + +--- + +## 이미지로 작업하기 + +`@` 문법을 사용해 대화에 이미지를 포함할 수 있습니다. Copilot은 스크린샷, 목업, 다이어그램을 비롯한 다양한 시각 자료를 분석할 수 있습니다. + +### 기본 이미지 참조 + +```bash +copilot + +> @screenshot.png What's happening in this UI? + +# Copilot analyzes the image and responds + +> @mockup.png @current-design.png Compare these two designs + +# You can also drag and drop images or paste from clipboard +``` + +### 지원되는 이미지 형식 + +| 형식 | 가장 잘 어울리는 용도 | +|--------|----------| +| PNG | 스크린샷, UI 목업, 다이어그램 | +| JPG/JPEG | 사진, 복잡한 이미지 | +| GIF | 단순한 다이어그램(첫 프레임만 사용) | +| WebP | 웹 스크린샷 | + +### 실용적인 이미지 활용 사례 + +**1. UI 디버깅** +```bash +> @bug-screenshot.png The button doesn't align properly. What CSS might cause this? +``` + +**2. 디자인 구현** +```bash +> @figma-export.png Write the HTML and Tailwind CSS to match this design +``` + +**3. 에러 분석** +```bash +> @error-screenshot.png What does this error mean and how do I fix it? +``` + +**4. 아키텍처 리뷰** +```bash +> @whiteboard-diagram.png Convert this architecture diagram to a Mermaid diagram I can put in docs +``` + +**5. 변경 전/후 비교** +```bash +> @before.png @after.png What changed between these two versions of the UI? +``` + +### 이미지와 코드 결합하기 + +이미지는 코드 컨텍스트와 결합될 때 더욱 강력해집니다: + +```bash +copilot + +> @screenshot-of-bug.png @src/components/Header.jsx +> The header looks wrong in the screenshot. What's causing it in the code? +``` + +### 이미지 사용 팁 + +- **스크린샷은 잘라내세요** - 관련 부분만 남기면 컨텍스트 토큰을 아낄 수 있습니다. +- **고대비를 사용하세요** - 분석할 UI 요소가 잘 보이도록 합니다. +- **필요하면 표시를 더하세요** - 업로드 전에 문제 영역에 동그라미를 치거나 강조 표시를 해 두세요. +- **개념 하나당 이미지 한 장** - 여러 장도 가능하지만 초점을 분명히 해 주세요. + +--- + +## 권한 패턴 + +기본적으로 Copilot은 현재 디렉터리의 파일에 접근할 수 있습니다. 그 외 위치의 파일을 다루려면 권한을 부여해야 합니다. + +### 디렉터리 추가하기 + +```bash +# Add a directory to the allowed list +copilot --add-dir /path/to/other/project + +# Add multiple directories +copilot --add-dir ~/workspace --add-dir /tmp +``` + +### 모든 경로 허용하기 + +```bash +# Disable path restrictions entirely (use with caution) +copilot --allow-all-paths +``` + +### 세션 안에서 + +```bash +copilot + +> /add-dir /path/to/other/project +# Now you can reference files from that directory + +> /list-dirs +# See all allowed directories + +> /yolo +# Quick alias for /allow-all on — auto-approves all permission prompts +``` + +### 자동화 환경에서 + +```bash +# Allow all permissions for non-interactive scripts +copilot -p "Review @src/" --allow-all + +# Or use the memorable alias +copilot -p "Review @src/" --yolo +``` + +### 다중 디렉터리 접근이 필요한 상황 + +이러한 권한이 필요한 대표적인 시나리오들입니다: + +1. **모노레포 작업** - 여러 패키지에 걸친 코드 비교 +2. **프로젝트 간 리팩터링** - 공유 라이브러리 업데이트 +3. **문서 프로젝트** - 여러 코드베이스를 함께 참조 +4. **마이그레이션 작업** - 기존 구현과 새 구현 비교 + +--- + +**[← 2장으로 돌아가기](../02-context-conversations/README.md)** | **[부록 목록으로 돌아가기](README.md)** diff --git a/localization/ko-kr/appendices/ci-cd-integration.md b/localization/ko-kr/appendices/ci-cd-integration.md new file mode 100644 index 00000000..7013f4b5 --- /dev/null +++ b/localization/ko-kr/appendices/ci-cd-integration.md @@ -0,0 +1,199 @@ +# CI/CD 통합 + +> 📖 **사전 학습**: 이 부록을 읽기 전에 [7장: 모두 합치기](../07-putting-it-together/README.md)를 먼저 마쳐 주세요. +> +> ⚠️ **이 부록은 이미 CI/CD 파이프라인을 운영 중인 팀을 위한 것입니다.** GitHub Actions나 CI/CD 개념이 처음이라면, 7장의 [코드 리뷰 자동화](../07-putting-it-together/README.md#workflow-3-code-review-automation-optional) 섹션에 있는 더 단순한 pre-commit 훅 방식부터 시작하세요. + +이 부록에서는 풀 리퀘스트에서 자동 코드 리뷰를 수행하기 위해 GitHub Copilot CLI를 CI/CD 파이프라인에 통합하는 방법을 보여 줍니다. + +--- + +## GitHub Actions 워크플로 + +다음 워크플로는 풀 리퀘스트가 열리거나 업데이트될 때 변경된 파일을 자동으로 리뷰합니다: + +```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 # Needed to compare with main branch + + - name: Install Copilot CLI + run: npm install -g @github/copilot + + - name: Review Changed Files + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Get list of changed JS/TS files + 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 + + # Use --silent to suppress progress output + 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'); + + // Only post if there's meaningful content + 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 +# Security-only review +copilot --allow-all -p "Security review of @$file. Check for: SQL injection, XSS, hardcoded secrets, authentication issues." --silent + +# Performance-only review +copilot --allow-all -p "Performance review of @$file. Check for: N+1 queries, memory leaks, blocking operations." --silent +``` + +### 큰 PR 다루기 + +파일이 많은 PR에서는 배치로 처리하거나 개수를 제한하는 방법을 고려해 보세요: + +```yaml +# Limit to first 10 files +FILES=$(git diff --name-only origin/main...HEAD | grep -E '\.(js|ts)$' | head -10) + +# Or set a timeout per file +timeout 60 copilot --allow-all -p "Review @$file" --silent || echo "Review timed out" +``` + +### 팀 공통 구성 + +팀 전체에서 일관된 리뷰를 보장하려면 공유 구성 파일을 만들어 두세요: + +```json +// .copilot/config.json (committed to repo) +{ + "model": "claude-sonnet-4.5", + "permissions": { + "allowedPaths": ["src/**/*", "tests/**/*"], + "deniedPaths": [".env*", "secrets/**/*", "*.min.js"] + } +} +``` + +--- + +## 대안: PR 리뷰 봇 + +더 정교한 리뷰 워크플로가 필요하다면, GitHub Copilot 클라우드 에이전트를 활용하는 것도 좋은 선택입니다: + +```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 +``` + +### 큰 파일에서 토큰 한도 초과 + +매우 큰 파일은 건너뛰세요: + +```bash +if [ $(wc -l < "$file") -lt 500 ]; then + copilot --allow-all -p "Review @$file" --silent +else + echo "Skipping $file (too large)" +fi +``` + +--- + +**[← 7장으로 돌아가기](../07-putting-it-together/README.md)** | **[부록 목록으로 돌아가기](README.md)** diff --git a/localization/pt-br/00-quick-start/README.md b/localization/pt-br/00-quick-start/README.md new file mode 100644 index 00000000..cd51509d --- /dev/null +++ b/localization/pt-br/00-quick-start/README.md @@ -0,0 +1,290 @@ +![Capítulo 00: Início Rápido](../../../00-quick-start/images/chapter-header.png) + +Bem-vindo! Neste capítulo, você irá instalar o GitHub Copilot CLI (Interface de Linha de Comando), fazer login com a sua conta do GitHub e verificar que tudo está funcionando. Este é um capítulo de configuração rápida. Assim que estiver pronto, as demos de verdade começam no Capítulo 01! + +## 🎯 Objetivos de aprendizado + +Ao final deste capítulo, você terá: + +- Instalado o GitHub Copilot CLI +- Feito login com a sua conta do GitHub +- Verificado que funciona com um teste simples + +> ⏱️ **Tempo estimado**: ~10 minutos (5 min de leitura + 5 min de prática) + +--- + +## ✅ Pré-requisitos + +- **Conta no GitHub** com acesso ao Copilot. [Veja as opções de assinatura](https://github.com/features/copilot/plans). Estudantes e professores podem acessar o Copilot Pro [gratuitamente pelo GitHub Education](https://education.github.com/pack). +- **Noções básicas de terminal**: Familiaridade com comandos como `cd` e `ls` + +### O que significa "Acesso ao Copilot" + +O GitHub Copilot CLI requer uma assinatura ativa do Copilot. Você pode verificar o seu status em [github.com/settings/copilot](https://github.com/settings/copilot). Você verá uma das seguintes opções: + +- **Copilot Individual** - Assinatura pessoal +- **Copilot Business** - Pela sua organização +- **Copilot Enterprise** - Pela sua empresa +- **GitHub Education** - Gratuito para estudantes/professores verificados + +Se você vir "Você não tem acesso ao GitHub Copilot", será necessário usar a opção gratuita, assinar um plano ou ingressar em uma organização que ofereça acesso. + +--- + +## Instalação + +> ⏱️ **Estimativa de tempo**: A instalação leva de 2 a 5 minutos. A autenticação adiciona mais 1 a 2 minutos. + +### GitHub Codespaces (Sem configuração) + +Se você não quiser instalar os pré-requisitos, pode usar o GitHub Codespaces, que já vem com o GitHub Copilot CLI pronto para uso (você precisará fazer login), além de Python e pytest pré-instalados. + +1. [Faça um fork deste repositório](https://github.com/github/copilot-cli-for-beginners/fork) para a sua conta no GitHub +2. Selecione **Code** > **Codespaces** > **Create codespace on main** +3. Aguarde alguns minutos para o contêiner ser construído +4. Você está pronto! O terminal será aberto automaticamente no ambiente do Codespace. + +> 💡 **Verifique no Codespace**: Execute `cd samples/book-app-project && python book_app.py help` para confirmar que Python e o aplicativo de exemplo estão funcionando. + +### Instalação Local + +Siga estes passos se quiser executar o Copilot CLI na sua máquina local com os exemplos do curso. + +1. Clone o repositório para ter os exemplos do curso na sua máquina: + + ```bash + git clone https://github.com/github/copilot-cli-for-beginners + cd copilot-cli-for-beginners + ``` + +2. Instale o Copilot CLI usando uma das opções a seguir. + + > 💡 **Não sabe qual escolher?** Use `npm` se você tiver Node.js instalado. Caso contrário, escolha a opção que corresponde ao seu sistema. + + ### Todas as plataformas (npm) + + ```bash + # Se você tem Node.js instalado, esta é uma forma rápida de obter o CLI + npm install -g @github/copilot + ``` + + ### macOS/Linux (Homebrew) + + ```bash + brew install copilot-cli + ``` + + ### Windows (WinGet) + + ```bash + winget install GitHub.Copilot + ``` + + ### macOS/Linux (Script de instalação) + + ```bash + curl -fsSL https://gh.io/copilot-install | bash + ``` + +
+Opcional: Ativar o autocompletar no shell + +O autocompletar no shell permite que você pressione **Tab** para completar subcomandos do `copilot`, opções de comandos e alguns valores de opções. Isso é opcional, mas pode ser útil quando você já estiver confortável usando o CLI. + +O Copilot CLI atualmente suporta scripts de autocompletar para Bash, Zsh e Fish: + +```shell +# Bash, somente a sessão atual +source <(copilot completion bash) + +# Bash, persistente no Linux +copilot completion bash | sudo tee /etc/bash_completion.d/copilot + +# Zsh +copilot completion zsh > "${fpath[1]}/_copilot" + +# Fish +copilot completion fish > ~/.config/fish/completions/copilot.fish +``` + +Reinicie seu shell após adicionar o autocompletar persistente. O PowerShell é suportado para executar o Copilot CLI no Windows, mas `copilot completion` atualmente suporta apenas Bash, Zsh e Fish. + +
+ +--- + +## Autenticação + +Abra uma janela de terminal na raiz do repositório `copilot-cli-for-beginners`, inicie o CLI e permita o acesso à pasta. + +```bash +copilot +``` + +Você será solicitado a confiar na pasta que contém o repositório (caso ainda não tenha feito isso). Você pode confiar apenas uma vez ou para todas as sessões futuras. + +Confiando em arquivos de uma pasta com o Copilot CLI + +Após confiar na pasta, você pode fazer login com a sua conta do GitHub. + +``` +> /login +``` + +**O que acontece a seguir:** + +1. O Copilot CLI exibe um código único (como `ABCD-1234`) +2. Seu navegador abre a página de autorização de dispositivo do GitHub. Faça login no GitHub caso ainda não tenha feito. +3. Insira o código quando solicitado +4. Selecione "Autorizar" para conceder acesso ao GitHub Copilot CLI +5. Retorne ao seu terminal — agora você está conectado! + +Fluxo de Autorização de Dispositivo - mostrando o processo de 5 etapas do login no terminal até a confirmação de login + +*O fluxo de autorização de dispositivo: o seu terminal gera um código, você o verifica no navegador e o Copilot CLI é autenticado.* + +**Dica**: O login persiste entre sessões. Você só precisa fazer isso uma vez, a menos que o seu token expire ou você saia explicitamente. + +--- + +## Verificar se funciona + +### Etapa 1: Testar o Copilot CLI + +Agora que você está conectado, vamos verificar se o Copilot CLI está funcionando. No terminal, inicie o CLI se ainda não tiver feito isso: + +```bash +> Say hello and tell me what you can help with +``` + +Após receber uma resposta, você pode sair do CLI: + +```bash +> /exit +``` + +--- + +
+🎬 Veja em ação! + +![Demo Olá](../../../00-quick-start/images/hello-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +**Saída esperada**: Uma resposta amigável listando as capacidades do Copilot CLI. + +### Etapa 2: Executar o aplicativo de livros de exemplo + +O curso fornece um aplicativo de exemplo que você irá explorar e melhorar ao longo do curso usando o CLI *(Você pode ver o código em /samples/book-app-project)*. Verifique se o *aplicativo de coleção de livros em Python* funciona antes de começar. Execute `python` ou `python3` dependendo do seu sistema. + +> **Observação:** Os exemplos principais mostrados ao longo do curso usam Python (`samples/book-app-project`), portanto você precisará ter [Python 3.10+](https://www.python.org/downloads/) disponível na sua máquina local se escolheu essa opção (o Codespace já o tem instalado). Versões em JavaScript (`samples/book-app-project-js`) e C# (`samples/book-app-project-cs`) também estão disponíveis se preferir trabalhar com essas linguagens. Cada exemplo tem um README com instruções para executar o aplicativo nessa linguagem. + +```bash +cd samples/book-app-project +python book_app.py list +``` + +**Saída esperada**: Uma lista de 5 livros incluindo "The Hobbit", "1984" e "Dune". + +### Etapa 3: Experimentar o Copilot CLI com o aplicativo de livros + +Volte primeiro para a raiz do repositório (se executou a Etapa 2): + +```bash +cd ../.. # Voltar para a raiz do repositório, se necessário +copilot +> What does @samples/book-app-project/book_app.py do? +``` + +**Saída esperada**: Um resumo das principais funções e comandos do aplicativo de livros. + +Se você vir um erro, verifique a [seção de solução de problemas](#troubleshooting) abaixo. + +Quando terminar, você pode sair do Copilot CLI: + +```bash +> /exit +``` + +--- + +## ✅ Você está pronto! + +É isso para a instalação. A diversão de verdade começa no Capítulo 01, onde você irá: + +- Ver a IA revisar o aplicativo de livros e encontrar problemas de qualidade de código instantaneamente +- Aprender três formas diferentes de usar o Copilot CLI +- Gerar código funcional a partir de linguagem natural + +**[Continuar para o Capítulo 01: Primeiros Passos →](../01-setup-and-first-steps/README.md)** + +--- + +## Solução de problemas + +### "copilot: command not found" + +O CLI não está instalado. Tente um método de instalação diferente: + +```bash +# Se o brew falhou, tente npm: +npm install -g @github/copilot + +# Ou o script de instalação: +curl -fsSL https://gh.io/copilot-install | bash +``` + +### "You don't have access to GitHub Copilot" + +1. Verifique se você tem uma assinatura do Copilot em [github.com/settings/copilot](https://github.com/settings/copilot) +2. Verifique se a sua organização permite acesso ao CLI se estiver usando uma conta de trabalho + +### "Authentication failed" + +Faça a autenticação novamente: + +```bash +copilot +> /login +``` + +### O navegador não abre automaticamente + +Visite manualmente [github.com/login/device](https://github.com/login/device) e insira o código exibido no seu terminal. + +### Token expirado + +Simplesmente execute `/login` novamente: + +```bash +copilot +> /login +``` + +### Ainda com problemas? + +- Consulte a [documentação do GitHub Copilot CLI](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) +- Pesquise nas [Issues do GitHub](https://github.com/github/copilot-cli/issues) + +--- + +## 🔑 Principais aprendizados + +1. **Um GitHub Codespace é uma forma rápida de começar** - Python, pytest e o GitHub Copilot CLI já vêm pré-instalados para que você pule direto para as demos +2. **Múltiplos métodos de instalação** - Escolha o que funciona para o seu sistema (Homebrew, WinGet, npm ou script de instalação) +3. **Autenticação única** - O login persiste até o token expirar +4. **O aplicativo de livros funciona** - Você usará `samples/book-app-project` ao longo de todo o curso + +> 📚 **Documentação oficial**: [Instalar o Copilot CLI](https://docs.github.com/copilot/how-tos/copilot-cli/cli-getting-started) para opções e requisitos de instalação. + +> 📋 **Referência rápida**: Veja a [referência de comandos do GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para uma lista completa de comandos e atalhos. + +--- + +**[Continuar para o Capítulo 01: Primeiros Passos →](../01-setup-and-first-steps/README.md)** diff --git a/localization/pt-br/01-setup-and-first-steps/README.md b/localization/pt-br/01-setup-and-first-steps/README.md new file mode 100644 index 00000000..25982075 --- /dev/null +++ b/localization/pt-br/01-setup-and-first-steps/README.md @@ -0,0 +1,690 @@ +![Capítulo 01: Primeiros Passos](../../../01-setup-and-first-steps/images/chapter-header.png) + +> **Veja a IA encontrar bugs instantaneamente, explicar código confuso e gerar scripts funcionais. Depois aprenda três formas diferentes de usar o GitHub Copilot CLI.** + +Este capítulo é onde a mágica começa! Você vai experimentar em primeira mão por que os desenvolvedores descrevem o GitHub Copilot CLI como ter um engenheiro sênior disponível a qualquer hora. Você verá a IA encontrar bugs de segurança em segundos, terá código complexo explicado em linguagem simples e gerará scripts funcionais instantaneamente. Em seguida, você dominará os três modos de interação (Interativo, Plan e Programático) para saber exatamente qual usar para cada tarefa. + +> ⚠️ **Pré-requisitos**: Certifique-se de ter concluído o **[Capítulo 00: Início Rápido](../00-quick-start/README.md)** primeiro. Você precisará do GitHub Copilot CLI instalado e autenticado antes de executar as demos abaixo. + +## 🎯 Objetivos de aprendizado + +Ao final deste capítulo, você será capaz de: + +- Experimentar o aumento de produtividade que o GitHub Copilot CLI proporciona por meio de demos práticas +- Escolher o modo certo (Interativo, Plan ou Programático) para qualquer tarefa +- Usar slash commands para controlar suas sessões + +> ⏱️ **Tempo estimado**: ~45 minutos (15 min de leitura + 30 min de prática) + +--- + +# Sua Primeira Experiência com o Copilot CLI + +Desenvolvedor sentado em uma mesa com código no monitor e partículas brilhantes representando a assistência de IA + +Mergulhe de cabeça e veja o que o Copilot CLI pode fazer. + +--- + +## Começando com Conforto: Seus Primeiros Prompts + +Antes de mergulhar nas demos impressionantes, vamos começar com alguns prompts simples que você pode experimentar agora mesmo. **Nenhum repositório de código necessário**! Basta abrir um terminal e iniciar o Copilot CLI: + +```bash +copilot +``` + +Experimente estes prompts para iniciantes: + +``` +> 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 +``` + +Não usa Python? Sem problema! Basta fazer perguntas sobre a linguagem de sua preferência. + +Perceba como parece natural. Basta fazer perguntas como você faria a um colega. Quando terminar de explorar, digite `/exit` para encerrar a sessão. + +**O ponto-chave**: O GitHub Copilot CLI é conversacional. Você não precisa de uma sintaxe especial para começar. Apenas faça perguntas em linguagem natural. + +## Veja em Ação + +Agora vamos ver por que os desenvolvedores chamam isso de "ter um engenheiro sênior disponível a qualquer hora." + +> 📖 **Lendo os Exemplos**: Linhas começando com `>` são prompts que você digita dentro de uma sessão interativa do Copilot CLI. Linhas sem o prefixo `>` são comandos de shell que você executa no seu terminal. + +> 💡 **Sobre as Saídas de Exemplo**: As saídas de exemplo mostradas ao longo deste curso são ilustrativas. Como as respostas do Copilot CLI variam a cada vez, os seus resultados diferirão em redação, formatação e detalhes. Concentre-se no *tipo* de informação retornada, não no texto exato. + +### Demo 1: Revisão de código em segundos + +O curso inclui arquivos de exemplo com problemas de qualidade de código intencionais. Se você está trabalhando na sua máquina local e ainda não clonou o repositório, execute o comando `git clone` abaixo, navegue até a pasta `copilot-cli-for-beginners` e então execute o comando `copilot`. + +```bash +# Clone o repositório do curso se estiver trabalhando localmente e ainda não tiver feito isso +git clone https://github.com/github/copilot-cli-for-beginners +cd copilot-cli-for-beginners + +# Inicie o Copilot +copilot +``` + +Dentro da sessão interativa do Copilot CLI, execute o seguinte: + +``` +> Review @samples/book-app-project/book_app.py for code quality issues and suggest improvements +``` + +> 💡 **Para que serve o símbolo `@`?** O símbolo `@` diz ao Copilot CLI para ler um arquivo. Você aprenderá tudo sobre isso no Capítulo 02. Por enquanto, apenas copie o comando exatamente como mostrado. + +--- + +
+🎬 Veja em ação! + +![Demo de Revisão de Código](../../../01-setup-and-first-steps/images/code-review-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +**O ponto-chave**: Uma revisão de código profissional em segundos. A revisão manual levaria... bem... mais tempo do que isso! + +--- + +### Demo 2: Explicar código confuso + +Já ficou olhando para um código sem entender o que ele faz? Experimente isso na sua sessão do Copilot CLI: + +``` +> Explain what @samples/book-app-project/books.py does in simple terms +``` + +--- + +
+🎬 Veja em ação! + +![Demo de Explicação de Código](../../../01-setup-and-first-steps/images/explain-code-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +**O que acontece**: (a sua saída pode diferir) O Copilot CLI lê o arquivo, entende o código e o explica em linguagem simples. + +``` +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 +``` + +**O ponto-chave**: Código complexo explicado como um mentor paciente o explicaria. + +--- + +### Demo 3: Gerar código funcional + +Precisa de uma função para a qual normalmente gastaria 15 minutos pesquisando? Ainda na sua sessão: + +``` +> Write a Python function that takes a list of books and returns statistics: + total count, number read, number unread, oldest and newest book +``` + +--- + +
+🎬 Veja em ação! + +![Demo de Geração de Código](../../../01-setup-and-first-steps/images/generate-code-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +**O que acontece**: Uma função completa e funcional em segundos que você pode copiar, colar e executar. + +Quando terminar de explorar, saia da sessão: + +``` +> /exit +``` + +**O ponto-chave**: Gratificação instantânea, e você permaneceu em uma única sessão contínua o tempo todo. + +--- + +# Modos e Comandos + +Painel de controle futurista com telas brilhantes, mostradores e equalizadores representando os modos e comandos do Copilot CLI + +Você acabou de ver o que o Copilot CLI pode fazer. Agora vamos entender *como* usar essas capacidades com eficiência. A chave está em saber qual dos três modos de interação usar para diferentes situações. + +> 💡 **Observação**: O Copilot CLI também possui um modo **Autopilot** (piloto automático) onde ele executa tarefas sem esperar pela sua entrada. É poderoso, mas requer a concessão de permissões totais e usa requisições premium de forma autônoma. Este curso se concentra nos três modos abaixo. Vamos indicar o Autopilot quando você estiver confortável com o básico. + +--- + +## 🧩 Analogia com o Mundo Real: Jantar Fora + +Pense em usar o GitHub Copilot CLI como sair para jantar. Do planejamento da viagem ao pedido, situações diferentes pedem abordagens diferentes: + +| Modo | Analogia do Jantar | Quando Usar | +|------|--------------------|-------------| +| **Plan** | GPS até o restaurante | Tarefas complexas - trace o caminho, revise as paradas, concorde com o plano, depois execute | +| **Interactive** | Conversar com o garçom | Exploração e iteração - faça perguntas, personalize, receba feedback em tempo real | +| **Programmatic** | Pedido no drive-through | Tarefas rápidas e específicas - fique no seu ambiente, obtenha um resultado rápido | + +Assim como sair para jantar, você vai aprender naturalmente quando cada abordagem faz sentido. + +Três Formas de Usar o GitHub Copilot CLI - Modo Plan (GPS até o restaurante), Modo Interativo (conversar com o garçom), Modo Programático (drive-through) + +*Escolha o seu modo com base na tarefa: Plan para mapear primeiro, Interactive para colaboração de ida e volta, Programmatic para resultados rápidos em uma única tentativa* + +### Qual Modo Devo Usar Primeiro? + +**Comece com o modo Interativo.** +- Você pode experimentar e fazer perguntas de acompanhamento +- O contexto se constrói naturalmente através da conversa +- Erros são fáceis de corrigir com `/clear` + +Quando estiver confortável, experimente: +- **Modo Programático** (`copilot -p ""`) para perguntas rápidas e pontuais +- **Modo Plan** (`/plan`) quando precisar planejar as coisas em mais detalhes antes de codificar + +--- + +## Os Três Modos + +### Modo 1: Modo Interativo (comece aqui) + +Modo Interativo - Como conversar com um garçom que pode responder perguntas e ajustar o pedido + +**Melhor para**: Exploração, iteração, conversas com múltiplas trocas. Como conversar com um garçom que pode responder perguntas, receber feedback e ajustar o pedido em tempo real. + +Inicie uma sessão interativa: + +```bash +copilot +``` + +Como você já viu até aqui, aparecerá um prompt onde você pode digitar naturalmente. Para obter ajuda sobre os comandos disponíveis, basta digitar: + +``` +> /help +``` + +**Ponto-chave**: O modo Interativo mantém o contexto. Cada mensagem se baseia nas anteriores, assim como uma conversa real. + +#### Exemplo do Modo Interativo + +```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 +``` + +Perceba como cada prompt se baseia na resposta anterior. Você está tendo uma conversa, não recomeçando do zero a cada vez. + +--- + +### Modo 2: Modo Plan + +Modo Plan - Como planejar uma rota antes de uma viagem usando GPS + +**Melhor para**: Tarefas complexas onde você quer revisar a abordagem antes da execução. Similar a planejar uma rota antes de uma viagem usando GPS. + +O modo Plan ajuda você a criar um plano passo a passo antes de escrever qualquer código. Use o comando `/plan` ou pressione **Shift+Tab** para alternar para o Modo Plan: + +```bash +copilot + +> /plan Add a "mark as read" command to the book app +``` + +> 💡 **Dica**: **Shift+Tab** alterna entre modos: Interativo → Plan → Autopilot. Pressione a qualquer momento durante uma sessão interativa para mudar de modo sem digitar um comando. + +Você também pode lançar o Copilot CLI diretamente no modo plan usando o flag `--plan`: + +```bash +copilot --plan +``` + +**Saída do modo plan:** (a sua saída pode diferir) + +``` +📋 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] +``` + +**Ponto-chave**: O modo Plan permite revisar e modificar a abordagem antes que qualquer código seja escrito. Quando um plano estiver completo, você pode até dizer ao Copilot CLI para salvá-lo em um arquivo para referência posterior. Por exemplo, "Save this plan to `mark_as_read_plan.md`" criaria um arquivo markdown com os detalhes do plano. + +> 💡 **Quer algo mais complexo?** Experimente: `/plan Add search and filter capabilities to the book app`. O modo Plan escala desde funcionalidades simples até aplicações completas. + +> 📚 **Modo Autopilot**: Você pode ter notado que Shift+Tab alterna para um terceiro modo chamado **Autopilot**. No modo Autopilot, o Copilot trabalha em um plano completo sem esperar pela sua entrada a cada etapa — como delegar uma tarefa a um colega e dizer "me avise quando terminar." O fluxo de trabalho típico é plan → aceitar → autopilot, o que significa que você precisa ser bom em escrever planos primeiro. Você também pode lançar diretamente no modo autopilot com `copilot --autopilot`. Fique confortável com os modos Interativo e Plan primeiro, depois consulte a [documentação oficial](https://docs.github.com/copilot/concepts/agents/copilot-cli/autopilot) quando estiver pronto. + +--- + +### Modo 3: Modo Programático + +Modo Programático - Como usar um drive-through para um pedido rápido + +**Melhor para**: Automação, scripts, CI/CD, comandos de uma única execução. Como usar um drive-through para um pedido rápido sem precisar conversar com um garçom. + +Use o flag `-p` para comandos pontuais que não precisam de interação: + +```bash +# Gerar código +copilot -p "Write a function that checks if a number is even or odd" + +# Obter ajuda rápida +copilot -p "How do I read a JSON file in Python?" +``` + +**Ponto-chave**: O modo Programático fornece uma resposta rápida e sai. Sem conversa, apenas entrada → saída. + +
+📚 Indo Além: Usando o Modo Programático em Scripts (clique para expandir) + +Quando estiver confortável, você pode usar `-p` em scripts de shell: + +```bash +#!/bin/bash + +# Gerar mensagens de commit automaticamente +COMMIT_MSG=$(copilot -p "Generate a commit message for: $(git diff --staged)") +git commit -m "$COMMIT_MSG" + +# Revisar um arquivo +copilot --allow-all -p "Review @myfile.py for issues" +``` +> ⚠️ **Sobre `--allow-all`**: Este flag ignora todos os prompts de permissão, permitindo que o Copilot CLI leia arquivos, execute comandos e acesse URLs sem pedir permissão primeiro. Isso é necessário para o modo programático (`-p`) pois não há sessão interativa para aprovar ações. Use `--allow-all` apenas com prompts que você mesmo escreveu e em diretórios que você confia. Nunca use com entradas não confiáveis ou em diretórios sensíveis. + +
+ +--- + +## Slash Commands Essenciais + +Estes comandos são ótimos para aprender inicialmente ao começar a usar o Copilot CLI: + +| Comando | O que Faz | Quando Usar | +|---------|-----------|-------------| +| `/ask` | Fazer uma pergunta rápida sem afetar o histórico da conversa | Quando você quer uma resposta rápida sem desviar da tarefa atual | +| `/clear` | Limpar a conversa e começar do zero | Ao trocar de assunto | +| `/help` | Mostrar todos os comandos disponíveis | Quando você esquece um comando | +| `/model` | Mostrar ou trocar o modelo de IA | Quando você quer mudar o modelo de IA | +| `/plan` | Planejar seu trabalho antes de codificar | Para funcionalidades mais complexas | +| `/research` | Pesquisa profunda usando fontes do GitHub e da web | Quando você precisa investigar um assunto antes de codificar | +| `/exit` | Encerrar a sessão | Quando terminar | + +> 💡 **`/ask` versus chat regular**: Normalmente cada mensagem que você envia se torna parte da conversa em andamento e afeta respostas futuras. `/ask` é um atalho "fora do registro" — perfeito para perguntas pontuais como `/ask What does YAML mean?` sem poluir o contexto da sua sessão. + +> 💡 **Autocompletar com Tab**: Ao digitar um slash command, pressione **Tab** para autocompletar o nome do comando ou percorrer os subcomandos e argumentos disponíveis. Isso é especialmente útil quando você não lembra o nome exato de um comando. + +É isso para começar! À medida que você se sentir confortável, pode explorar comandos adicionais. + +> 📚 **Documentação oficial**: [Referência de comandos do CLI](https://docs.github.com/copilot/reference/cli-command-reference) para a lista completa de comandos e flags. + +
+📚 Comandos Adicionais (clique para expandir) + +> 💡 Os comandos essenciais acima cobrem muito do que você fará no uso diário. Esta referência está aqui para quando você estiver pronto para explorar mais. + +### Ambiente do Agente + +| Comando | O que Faz | +|---------|-----------| +| `/agent` | Navegar e selecionar entre os agentes disponíveis | +| `/env` | Mostrar detalhes do ambiente carregado — quais instruções, servidores MCP, skills, agentes e plugins estão ativos | +| `/init` | Inicializar instruções do Copilot para o seu repositório | +| `/mcp` | Gerenciar a configuração do servidor MCP | +| `/skills` | Gerenciar skills para capacidades aprimoradas | + +> 💡 Agentes são abordados no [Capítulo 04](../04-agents-custom-instructions/README.md), skills no [Capítulo 05](../05-skills/README.md), e servidores MCP no [Capítulo 06](../06-mcp-servers/README.md). + +### Modelos e Subagentes + +| Comando | O que Faz | +|---------|-----------| +| `/delegate` | Delegar tarefa ao agente de nuvem do GitHub Copilot | +| `/fleet` | Dividir uma tarefa complexa em subtarefas paralelas para conclusão mais rápida | +| `/model` | Mostrar ou trocar o modelo de IA | +| `/tasks` | Ver subagentes em segundo plano e sessões de shell desanexadas | + +### Código + +| Comando | O que Faz | +|---------|-----------| +| `/diff` | Revisar as alterações feitas no diretório atual | +| `/pr` | Operar em pull requests para a branch atual | +| `/research` | Executar investigação de pesquisa profunda usando fontes do GitHub e da web | +| `/review` | Executar o agente de revisão de código para analisar alterações | +| `/terminal-setup` | Ativar suporte a entrada multilinha (shift+enter e ctrl+enter) | + +### Permissões + +| Comando | O que Faz | +|---------|-----------| +| `/add-dir ` | Adicionar um diretório à lista de permitidos | +| `/allow-all [on\|off\|show]` | Auto-aprovar todos os prompts de permissão; use `on` para ativar, `off` para desativar, `show` para verificar o status atual | +| `/yolo` | Atalho rápido para `/allow-all on` — auto-aprova todos os prompts de permissão. | +| `/cwd`, `/cd [diretório]` | Ver ou mudar o diretório de trabalho | +| `/list-dirs` | Mostrar todos os diretórios permitidos | + +> ⚠️ **Use com cautela**: `/allow-all` e `/yolo` ignoram prompts de confirmação. Ótimo para projetos confiáveis, mas tenha cuidado com código não confiável. + +### Sessão + +| Comando | O que Faz | +|---------|-----------| +| `/clear` | Abandona a sessão atual (sem histórico salvo) e inicia uma nova conversa | +| `/compact` | Resumir a conversa para reduzir o uso de contexto | +| `/context` | Mostrar uso e visualização do token da janela de contexto | +| `/keep-alive` | Evitar que o sistema entre em suspensão enquanto o Copilot CLI está ativo — útil para tarefas longas em um laptop | +| `/new` | Encerra a sessão atual (salvando-a no histórico para busca/retomada) e inicia uma nova conversa. | +| `/resume` | Mudar para uma sessão diferente (opcionalmente especifique o ID ou nome da sessão) | +| `/rename` | Renomear a sessão atual (omita o nome para gerar um automaticamente) | +| `/rewind` | Abrir um seletor de linha do tempo para voltar a qualquer ponto anterior da conversa | +| `/usage` | Exibir métricas de uso e estatísticas da sessão | +| `/session` | Mostrar informações da sessão e resumo do espaço de trabalho; use `/session delete`, `/session delete `, ou `/session delete-all` para remover sessões | +| `/share` | Exportar a sessão como um arquivo markdown, GitHub gist ou arquivo HTML independente | + +### Exibição + +| Comando | O que Faz | +|---------|-----------| +| `/statusline` (ou `/footer`) | Personalizar quais itens aparecem na barra de status na parte inferior da sessão (diretório, branch, esforço, janela de contexto, cota) | +| `/theme` | Ver ou definir o tema do terminal | + +### Ajuda e Feedback + +| Comando | O que Faz | +|---------|-----------| +| `/changelog` | Exibir o changelog para versões do CLI | +| `/feedback` | Enviar feedback ao GitHub | +| `/help` | Mostrar todos os comandos disponíveis | + +### Comandos de Shell Rápidos + +Execute comandos de shell diretamente sem IA prefixando com `!`: + +```bash +copilot + +> !git status +# Executa git status diretamente, sem passar pela IA + +> !python -m pytest tests/ +# Executa pytest diretamente +``` + +### Trocando de Modelos + +O Copilot CLI suporta múltiplos modelos de IA da OpenAI, Anthropic, Google e outros. Os modelos disponíveis para você dependem do seu nível de assinatura e região. Use `/model` para ver suas opções e alternar entre eles: + +```bash +copilot +> /model + +# Mostra os modelos disponíveis e permite que você escolha um. Selecione Sonnet 4.5. +``` + +> 💡 **Dica**: Alguns modelos custam mais "requisições premium" do que outros. Modelos marcados com **1x** (como Claude Sonnet 4.5) são um ótimo padrão. São capazes e eficientes. Modelos com multiplicadores maiores consomem sua cota de requisições premium mais rápido, então guarde-os para quando realmente precisar. + +> 💡 **Não sabe qual modelo escolher?** Selecione **`Auto`** no seletor de modelos para deixar o Copilot escolher automaticamente o melhor modelo disponível para cada sessão. Este é um ótimo padrão se você está apenas começando e não quer pensar sobre a seleção de modelos. + +
+ +--- + +# Prática + +Mesa de trabalho aconchegante com monitor mostrando código, abajur, xícara de café e fones de ouvido prontos para a prática + +Hora de colocar em prática o que você aprendeu. + +--- + +## ▶️ Experimente Você Mesmo + +### Exploração Interativa + +Inicie o Copilot e use prompts de acompanhamento para melhorar iterativamente o aplicativo de livros: + +```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 +``` + +### Planejar uma Funcionalidade + +Use `/plan` para ter o Copilot CLI mapeando uma implementação antes de escrever qualquer código: + +```bash +copilot + +> /plan Add a search feature to the book app that can find books by title or author + +# Revise o plano +# Aprove ou modifique +# Veja a implementação passo a passo +``` + +### Automatizar com o Modo Programático + +O flag `-p` permite que você execute o Copilot CLI diretamente do seu terminal sem entrar no modo interativo. Copie e cole o seguinte script no seu terminal (não dentro do Copilot) a partir da raiz do repositório para revisar todos os arquivos Python no aplicativo de livros. + +```bash +# Revisar todos os arquivos Python no aplicativo de livros +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 +# Revisar todos os arquivos Python no aplicativo de livros +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" +} +``` + +--- + +Após concluir as demos, experimente estas variações: + +1. **Desafio Interativo**: Inicie o `copilot` e explore o aplicativo de livros. Pergunte sobre `@samples/book-app-project/books.py` e solicite melhorias 3 vezes seguidas. + +2. **Desafio do Modo Plan**: Execute `/plan Add rating and review features to the book app`. Leia o plano com atenção. Faz sentido? + +3. **Desafio Programático**: Execute `copilot --allow-all -p "List all functions in @samples/book-app-project/book_app.py and describe what each does"`. Funcionou na primeira tentativa? + +--- + +## 💡 Dica: Controle Sua Sessão CLI pela Web ou Celular + +O GitHub Copilot CLI suporta **sessões remotas**, permitindo que você monitore e interaja com uma sessão do CLI em execução por meio de um navegador web (no desktop ou celular) ou pelo aplicativo GitHub Mobile, sem estar fisicamente no seu terminal. + +Inicie uma sessão remota com o flag `--remote`: + +```bash +copilot --remote +``` + +O Copilot CLI exibirá um link e fornecerá acesso a um QR code. Abra o link no seu celular ou em uma aba do navegador desktop para acompanhar a sessão em tempo real, enviar prompts de acompanhamento, revisar planos e controlar o agente remotamente. As sessões são específicas do usuário, portanto você só pode acessar as suas próprias sessões do Copilot CLI. + +Você também pode ativar o acesso remoto de dentro de uma sessão ativa a qualquer momento: + +``` +> /remote +``` + +Mais detalhes sobre sessões remotas podem ser encontrados na [documentação do Copilot CLI](https://docs.github.com/copilot/how-tos/copilot-cli/steer-remotely). + +--- + +## 📝 Atividade + +### Desafio Principal: Melhorar os Utilitários do Aplicativo de Livros + +Os exemplos práticos focaram em revisar e refatorar `book_app.py`. Agora pratique as mesmas habilidades em um arquivo diferente, `utils.py`: + +1. Inicie uma sessão interativa: `copilot` +2. Peça ao Copilot CLI para resumir o arquivo: "Summarize @samples/book-app-project/utils.py and explain what each function in this file does" +3. Peça para adicionar validação de entrada: "Add validation to `get_user_choice()` so it handles empty input and non-numeric entries" +4. Peça para melhorar o tratamento de erros: "What happens if `get_book_details()` receives an empty string for the title? Add guards for that." +5. Peça uma docstring: "Add a comprehensive docstring to `get_book_details()` with parameter descriptions and return values" +6. Observe como o contexto se mantém entre os prompts. Cada melhoria se baseia na última +7. Saia com `/exit` + +**Critérios de sucesso**: Você deve ter um `utils.py` melhorado com validação de entrada, tratamento de erros e uma docstring, tudo construído por meio de uma conversa com múltiplas trocas. + +
+💡 Dicas (clique para expandir) + +**Prompts de exemplo para tentar:** +```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 +``` + +**Problemas comuns:** +- Se o Copilot CLI fizer perguntas de esclarecimento, basta respondê-las naturalmente +- O contexto se mantém, então cada prompt se baseia no anterior +- Use `/clear` se quiser recomeçar + +
+ +### Desafio Bônus: Compare os Modos + +Os exemplos usaram `/plan` para uma funcionalidade de busca e `-p` para revisões em lote. Agora experimente os três modos em uma única tarefa nova: adicionar um método `list_by_year()` à classe `BookCollection`: + +1. **Interativo**: `copilot` → peça para projetar e construir o método passo a passo +2. **Plan**: `/plan Add a list_by_year(start, end) method to BookCollection that filters books by publication year range` +3. **Programático**: `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"` + +**Reflexão**: Qual modo pareceu mais natural? Quando você usaria cada um? + +--- + +
+🔧 Erros Comuns e Solução de Problemas (clique para expandir) + +### Erros Comuns + +| Erro | O que Acontece | Solução | +|------|----------------|---------| +| Digitar `exit` em vez de `/exit` | O Copilot CLI trata "exit" como um prompt, não como um comando | Slash commands sempre começam com `/` | +| Usar `-p` para conversas com múltiplas trocas | Cada chamada com `-p` é isolada sem memória de chamadas anteriores | Use o modo interativo (`copilot`) para conversas que se baseiam em contexto | +| Esquecer as aspas em prompts com `$` ou `!` | O shell interpreta caracteres especiais antes de o Copilot CLI os ver | Envolva os prompts em aspas: `copilot -p "What does $HOME mean?"` | +| Pressionar Esc uma vez para cancelar uma tarefa em execução | Um único Esc não cancela mais trabalhos em andamento (para prevenir acidentes) | Pressione **Esc duas vezes** para cancelar enquanto o Copilot CLI está processando | + +### Solução de Problemas + +**"Model not available"** - Sua assinatura pode não incluir todos os modelos. Use `/model` para ver o que está disponível. + +**"Context too long"** - Sua conversa usou toda a janela de contexto. Use `/clear` para reiniciar ou inicie uma nova sessão. + +**"Rate limit exceeded"** - Aguarde alguns minutos e tente novamente. Considere usar o modo programático para operações em lote com intervalos. + +
+ +--- + +# Resumo + +## 🔑 Principais Aprendizados + +1. **O modo Interativo** é para exploração e iteração - o contexto se mantém. É como ter uma conversa com alguém que se lembra do que você disse até aquele momento. +2. **O modo Plan** é normalmente para tarefas mais complexas. Revise antes da implementação. +3. **O modo Programático** é para automação. Sem necessidade de interação. +4. **Os comandos essenciais** (`/ask`, `/help`, `/clear`, `/plan`, `/research`, `/model`, `/exit`) cobrem a maior parte do uso diário. + +> 📋 **Referência rápida**: Veja a [referência de comandos do GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para uma lista completa de comandos e atalhos. + +--- + +## ➡️ O Que Vem a Seguir + +Agora que você entende os três modos, vamos aprender a fornecer contexto ao Copilot CLI sobre o seu código. + +No **[Capítulo 02: Contexto e Conversas](../02-context-conversations/README.md)**, você aprenderá: + +- A sintaxe `@` para referenciar arquivos e diretórios +- Gerenciamento de sessões com `--resume` e `--continue` +- Como o gerenciamento de contexto torna o Copilot CLI verdadeiramente poderoso + +--- + +**[← Voltar ao Início do Curso](../README.md)** | **[Continuar para o Capítulo 02 →](../02-context-conversations/README.md)** diff --git a/localization/pt-br/02-context-conversations/README.md b/localization/pt-br/02-context-conversations/README.md new file mode 100644 index 00000000..3569db72 --- /dev/null +++ b/localization/pt-br/02-context-conversations/README.md @@ -0,0 +1,908 @@ +![Capítulo 02: Contexto e Conversas](../../../02-context-conversations/images/chapter-header.png) + +> **E se a IA pudesse ver toda a sua base de código, não apenas um arquivo de cada vez?** + +Neste capítulo, você vai desbloquear o verdadeiro poder do GitHub Copilot CLI: o contexto. Você aprenderá a usar a sintaxe `@` para referenciar arquivos e diretórios, dando ao Copilot CLI um profundo entendimento da sua base de código. Você descobrirá como manter conversas entre sessões, retomar o trabalho dias depois exatamente onde parou, e verá como a análise entre múltiplos arquivos detecta bugs que revisões de arquivo único deixam escapar completamente. + +## 🎯 Objetivos de aprendizado + +Ao final deste capítulo, você será capaz de: + +- Usar a sintaxe `@` para referenciar arquivos, diretórios e imagens +- Retomar sessões anteriores com `--resume` e `--continue` +- Entender como as [janelas de contexto](../../../GLOSSARY.md#context-window) funcionam +- Escrever conversas eficazes com múltiplas trocas +- Gerenciar permissões de diretório para fluxos de trabalho com múltiplos projetos + +> ⏱️ **Tempo estimado**: ~50 minutos (20 min de leitura + 30 min de prática) + +--- + +## 🧩 Analogia com o Mundo Real: Trabalhando com um Colega + +O Contexto Faz a Diferença - Sem vs. Com Contexto + +*Assim como os seus colegas, o Copilot CLI não é um leitor de mentes. Fornecer mais informações ajuda tanto humanos quanto o Copilot a oferecerem suporte direcionado!* + +Imagine explicar um bug a um colega: + +> **Sem contexto**: "O aplicativo de livros não está funcionando." + +> **Com contexto**: "Olha em `books.py`, especialmente na função `find_book_by_title`. Ela não está fazendo correspondência sem distinção de maiúsculas e minúsculas." + +Para fornecer contexto ao Copilot CLI, use *a sintaxe `@`* para apontar o Copilot CLI para arquivos específicos. + +--- + +# Essencial: Contexto Básico + +Blocos de código brilhantes conectados por rastros de luz representando como o contexto flui pelas conversas do Copilot CLI + +Esta seção cobre tudo que você precisa para trabalhar eficientemente com contexto. Domine esses fundamentos primeiro. + +--- + +## A Sintaxe @ + +O símbolo `@` referencia arquivos e diretórios nos seus prompts. É como você diz ao Copilot CLI "olhe para este arquivo." + +> 💡 **Observação**: Todos os exemplos neste curso usam a pasta `samples/` incluída neste repositório, então você pode experimentar cada comando diretamente. + +### Experimente Agora (Sem Configuração Necessária) + +Você pode experimentar isso com qualquer arquivo no seu computador: + +```bash +copilot + +# Aponte para qualquer arquivo que você tenha +> Explain what @package.json does +> Summarize @README.md +> What's in @.gitignore and why? +``` + +> 💡 **Não tem um projeto disponível?** Crie um arquivo de teste rápido: +> ```bash +> echo "def greet(name): return 'Hello ' + name" > test.py +> copilot +> > What does @test.py do? +> ``` + +### Padrões Básicos do @ + +| Padrão | O que Faz | Exemplo de Uso | +|--------|-----------|----------------| +| `@file.py` | Referenciar um único arquivo | `Review @samples/book-app-project/books.py` | +| `@folder/` | Referenciar todos os arquivos em um diretório | `Review @samples/book-app-project/` | +| `@file1.py @file2.py` | Referenciar múltiplos arquivos | `Compare @samples/book-app-project/book_app.py @samples/book-app-project/books.py` | + +### Referenciar um Único Arquivo + +```bash +copilot + +> Explain what @samples/book-app-project/utils.py does +``` + +--- + +
+🎬 Veja em ação! + +![Demo de Contexto de Arquivo](../../../02-context-conversations/images/file-context-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +### Referenciar Múltiplos Arquivos + +```bash +copilot + +> Compare @samples/book-app-project/book_app.py and @samples/book-app-project/books.py for consistency +``` + +### Referenciar um Diretório Inteiro + +```bash +copilot + +> Review all files in @samples/book-app-project/ for error handling +``` + +--- + +## Inteligência Entre Arquivos + +É aqui que o contexto se torna um superpoder. A análise de arquivo único é útil. A análise entre múltiplos arquivos é transformadora. + +Inteligência Entre Arquivos - comparando análise de arquivo único versus análise entre múltiplos arquivos, mostrando como analisar arquivos juntos revela bugs, fluxo de dados e padrões invisíveis em isolamento + +### Demo: Encontrar Bugs que Abrangem Múltiplos Arquivos + +```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? +``` + +> 💡 **Opção Avançada**: Para análise entre arquivos com foco em segurança, experimente os exemplos de Python com bugs: +> ```bash +> > @samples/buggy-code/python/user_service.py @samples/buggy-code/python/payment_processor.py +> > Find security vulnerabilities that span BOTH files +> ``` + +--- + +
+🎬 Veja em ação! + +![Demo de Múltiplos Arquivos](../../../02-context-conversations/images/multi-file-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +**O que o Copilot CLI descobre**: + +``` +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 +``` + +**Por que isso importa**: Uma revisão de arquivo único perderia o quadro geral. Apenas a análise entre arquivos revela: +- **Código duplicado** que deveria ser consolidado +- **Padrões de fluxo de dados** mostrando como os componentes interagem +- **Problemas arquiteturais** que afetam a manutenibilidade + +--- + +### Demo: Entender uma Base de Código em 60 Segundos + +Comparação em tela dividida mostrando revisão manual de código levando 1 hora versus análise assistida por IA levando 10 segundos + +Novo em um projeto? Aprenda sobre ele rapidamente usando o Copilot CLI. + +```bash +copilot + +> @samples/book-app-project/ +> +> In one paragraph, what does this app do and what are its biggest quality issues? +``` + +**O que você obtém**: +``` +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. +``` + +**Resultado**: O que leva uma hora de leitura de código comprimido em 10 segundos. Você sabe exatamente onde focar. + +--- + +## Exemplos Práticos + +### Exemplo 1: Revisão de Código com Contexto + +```bash +copilot + +> @samples/book-app-project/books.py Review this file for potential bugs + +# O Copilot CLI agora tem o conteúdo completo do arquivo e pode dar feedback específico: +# "Linha 49: Comparação com distinção de maiúsculas pode deixar livros passarem..." +# "Linha 29: Erros de decodificação JSON são capturados, mas a corrupção de dados não é registrada..." + +> What about @samples/book-app-project/book_app.py? + +# Agora revisando book_app.py, mas ainda ciente do contexto de books.py +``` + +### Exemplo 2: Entendendo uma Base de Código + +```bash +copilot + +> @samples/book-app-project/books.py What does this module do? + +# O Copilot CLI lê books.py e entende a classe BookCollection + +> @samples/book-app-project/ Give me an overview of the code structure + +# O Copilot CLI analisa o diretório e resume + +> How does the app save and load books? + +# O Copilot CLI pode rastrear pelo código que já viu +``` + +
+🎬 Veja uma conversa com múltiplas trocas em ação! + +![Demo de Múltiplas Trocas](../../../02-context-conversations/images/multi-turn-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +### Exemplo 3: Refatoração entre Múltiplos Arquivos + +```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. + +# O Copilot CLI vê ambos os arquivos e pode sugerir como mesclar o código duplicado +``` + +--- + +## Gerenciamento de Sessões + +As sessões são salvas automaticamente enquanto você trabalha. Você pode retomar sessões anteriores para continuar de onde parou. + +### Sessões se Salvam Automaticamente + +Cada conversa é salva automaticamente. Basta sair normalmente: + +```bash +copilot + +> @samples/book-app-project/ Let's improve error handling across all modules + +[... faça algum trabalho ...] + +> /exit +``` + +### Retomar a Sessão Mais Recente + +```bash +# Continue de onde parou +copilot --continue +``` + +### Retomar uma Sessão Específica + +```bash +# Escolha de uma lista de sessões interativamente +copilot --resume + +# Ou retome uma sessão específica por ID +copilot --resume=abc123 + +# Ou retome pelo nome que você deu à sessão +copilot --resume="my book app review" +``` + +> 💡 **Como encontro um ID de sessão?** Você não precisa memorizá-los. Executar `copilot --resume` sem um ID mostra uma lista interativa das suas sessões anteriores, seus nomes, IDs e quando foram usadas pela última vez. Basta escolher a que você quer. +> +> **E com múltiplos terminais?** Cada janela de terminal é sua própria sessão com seu próprio contexto. Se você tem o Copilot CLI aberto em três terminais, são três sessões separadas. Executar `--resume` a partir de qualquer terminal permite que você navegue por todas elas. O flag `--continue` pega a sessão do diretório de trabalho atual primeiro; se não houver nenhuma lá, ele pega a sessão mais recentemente ativa. +> +> **Posso trocar de sessões sem reiniciar?** Sim. Use o slash command `/resume` de dentro de uma sessão ativa: +> ``` +> > /resume +> # Mostra uma lista de sessões para alternar +> ``` + +### Organize Suas Sessões + +Dê nomes significativos às sessões para encontrá-las facilmente depois. Você pode nomear uma sessão quando a inicia, ou renomeá-la a qualquer momento dentro da sessão: + +```bash +# Nomear uma sessão quando você a inicia +copilot --name book-app-review + +# Ou renomear a sessão atual de dentro dela +copilot + +> /rename book-app-review +# Sessão renomeada para identificação mais fácil +``` + +Uma vez que uma sessão tem um nome, você pode retomá-la diretamente pelo nome sem navegar por uma lista: + +```bash +copilot --resume=book-app-review +``` + +Para limpar sessões que você não precisa mais, use `/session delete` de dentro de uma sessão: + +```bash +copilot + +> /session delete # Exclui a sessão atual +> /session delete abc123 # Exclui uma sessão específica por ID +> /session delete-all # Exclui todas as sessões (use com cuidado!) +``` + +### Verificar e Gerenciar o Contexto + +À medida que você adiciona arquivos e conversa, a [janela de contexto](../../../GLOSSARY.md#context-window) do Copilot CLI vai se preenchendo. Vários comandos estão disponíveis para ajudá-lo a manter o controle: + +```bash +copilot + +> /context +Context usage: 62k/200k tokens (31%) + +> /clear +# Abandona a sessão atual (sem histórico salvo) e inicia uma nova conversa + +> /new +# Encerra a sessão atual (salvando-a no histórico para busca/retomada) e inicia uma nova conversa + +> /rewind +# Abre um seletor de linha do tempo permitindo que você retorne a um ponto anterior da conversa +``` + +> 💡 **Quando usar `/clear` ou `/new`**: Se você estava revisando books.py e quer mudar para discutir utils.py, execute /new primeiro (ou /clear se não precisar do histórico da sessão). Caso contrário, o contexto obsoleto do assunto anterior pode confundir as respostas. + +> 💡 **Cometeu um erro ou quer tentar uma abordagem diferente?** Use `/rewind` (ou pressione Esc duas vezes) para abrir um **seletor de linha do tempo** que permite que você volte a qualquer ponto anterior da sua conversa, não apenas ao mais recente. Isso é útil quando você tomou o caminho errado e quer voltar atrás sem começar do zero. + +--- + +### Continue de Onde Parou + +Linha do tempo mostrando como as sessões do GitHub Copilot CLI persistem por dias - comece na segunda-feira, retome na quarta-feira com todo o contexto restaurado + +*As sessões são salvas automaticamente quando você sai. Retome dias depois com contexto completo: arquivos, problemas e progresso, todos lembrados.* + +Imagine este fluxo de trabalho ao longo de múltiplos dias: + +```bash +# Segunda-feira: Iniciar revisão do aplicativo de livros com um nome já no início +copilot --name 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) +# Trabalhar na correção... + +> /exit +``` + +```bash +# Quarta-feira: Retome exatamente de onde parou, pelo nome +copilot --resume=book-app-review + +> 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 +``` + +**O que torna isso poderoso**: Dias depois, o Copilot CLI lembra: +- O arquivo exato em que você estava trabalhando +- A lista numerada de problemas +- Quais você já resolveu +- O contexto da sua conversa + +Sem precisar explicar novamente. Sem precisar reler arquivos. Apenas continue trabalhando. + +--- + +**🎉 Agora você conhece os fundamentos!** A sintaxe `@`, o gerenciamento de sessões (`--name`/`--continue`/`--resume`/`/rename`) e os comandos de contexto (`/context`/`/clear`) são suficientes para ser altamente produtivo. Tudo abaixo é opcional. Volte a isso quando estiver pronto. + +--- + +# Opcional: Indo Mais Fundo + +Caverna de cristal abstrata em tons de azul e roxo representando exploração mais profunda dos conceitos de contexto + +Esses tópicos se baseiam nos fundamentos acima. **Escolha o que lhe interessa ou pule para [Prática](#practice).** + +| Quero aprender sobre... | Ir para | +|---|---| +| Padrões de curinga e comandos avançados de sessão | [Padrões @ Adicionais & Comandos de Sessão](#additional-patterns) | +| Construir sobre contexto em múltiplos prompts | [Conversas Conscientes do Contexto](#context-aware-conversations) | +| Limites de tokens e `/compact` | [Entendendo as Janelas de Contexto](#understanding-context-windows) | +| Como escolher os arquivos certos para referenciar | [Escolhendo o que Referenciar](#choosing-what-to-reference) | +| Analisar capturas de tela e mockups | [Trabalhando com Imagens](#working-with-images) | + +
+Padrões @ Adicionais & Comandos de Sessão + + +### Padrões @ Adicionais + +Para usuários avançados, o Copilot CLI suporta padrões de curinga e referências de imagens: + +| Padrão | O que Faz | +|--------|-----------| +| `@folder/*.py` | Todos os arquivos .py na pasta | +| `@**/test_*.py` | Curinga recursivo: encontrar todos os arquivos de teste em qualquer lugar | +| `@image.png` | Arquivo de imagem para revisão de UI | + +```bash +copilot + +> Find all TODO comments in @samples/book-app-project/**/*.py +``` + +### Ver Informações da Sessão + +```bash +copilot + +> /session +# Mostra detalhes da sessão atual e resumo do espaço de trabalho + +> /usage +# Mostra métricas e estatísticas da sessão +``` + +### Compartilhar Sua Sessão + +```bash +copilot + +> /share file ./my-session.md +# Exporta a sessão como um arquivo markdown + +> /share gist +# Cria um GitHub gist com a sessão + +> /share html +# Exporta a sessão como um arquivo HTML interativo independente +# Útil para compartilhar relatórios de sessão polidos com colegas ou salvar para referência +``` + +
+ +
+Conversas Conscientes do Contexto + + +### Conversas Conscientes do Contexto + +A mágica acontece quando você tem conversas com múltiplas trocas que se baseiam umas nas outras. + +#### Exemplo: Aprimoramento Progressivo + +```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..." +[Shows typed version] + +> Now improve error handling + +Copilot CLI: "Building on the typed version, here's improved error handling..." +[Adds validation and proper exceptions] + +> Generate tests for this final version + +Copilot CLI: "Based on the class with types and error handling..." +[Generates comprehensive tests] +``` + +Perceba como cada prompt se baseia no trabalho anterior. Este é o poder do contexto. + +
+ +
+Entendendo as Janelas de Contexto + + +### Entendendo as Janelas de Contexto + +Você já conhece `/context` e `/clear` dos fundamentos. Aqui está a visão mais profunda de como as janelas de contexto funcionam. + +Toda IA tem uma "janela de contexto", que é a quantidade de texto que ela pode considerar de uma vez. + +Visualização da Janela de Contexto + +*A janela de contexto é como uma mesa: ela só pode conter uma quantidade limitada de coisas de uma vez. Arquivos, histórico de conversa e prompts de sistema ocupam espaço.* + +#### O que Acontece no Limite + +```bash +copilot + +> /context + +Context usage: 45,000 / 128,000 tokens (35%) + +# À medida que você adiciona mais arquivos e conversa, isso cresce + +> @large-codebase/ + +Context usage: 120,000 / 128,000 tokens (94%) + +# Aviso: Aproximando-se do limite de contexto + +> @another-large-file.py + +Context limit reached. Older context will be summarized. +``` + +#### O Comando `/compact` + +Quando seu contexto está ficando cheio, mas você não quer perder a conversa, `/compact` resume seu histórico para liberar tokens: + +```bash +copilot + +> /compact +# Resume o histórico da conversa, liberando espaço de contexto +# Suas principais descobertas e decisões são preservadas +``` + +#### Dicas de Eficiência de Contexto + +| Situação | Ação | Por quê | +|----------|------|---------| +| Começando um novo assunto | `/clear` | Remove contexto irrelevante | +| Tomou o caminho errado | `/rewind` | Voltar a qualquer ponto anterior | +| Conversa longa | `/compact` | Resume o histórico, libera tokens | +| Precisa de um arquivo específico | `@file.py` e não `@folder/` | Carrega apenas o que você precisa | +| Atingindo limites | `/new` ou `/clear` | Contexto fresco | +| Múltiplos assuntos | Use `/rename` por assunto | Fácil de retomar a sessão certa | + +#### Melhores Práticas para Bases de Código Grandes + +1. **Seja específico**: `@samples/book-app-project/books.py` em vez de `@samples/book-app-project/` +2. **Limpe o contexto entre assuntos**: Use `/new` ou `/clear` ao trocar de foco +3. **Use `/compact`**: Resume a conversa para liberar contexto +4. **Use múltiplas sessões**: Uma sessão por funcionalidade ou assunto + +
+ +
+Escolhendo o que Referenciar + + +### Escolhendo o que Referenciar + +Nem todos os arquivos são iguais quando se trata de contexto. Veja como escolher sabiamente: + +#### Considerações sobre Tamanho de Arquivo + +| Tamanho do Arquivo | [Tokens](../../../GLOSSARY.md#token) Aproximados | Estratégia | +|-------------------|--------------------------------------------------|-----------| +| Pequeno (<100 linhas) | ~500-1.500 tokens | Referencie livremente | +| Médio (100-500 linhas) | ~1.500-7.500 tokens | Referencie arquivos específicos | +| Grande (500+ linhas) | 7.500+ tokens | Seja seletivo, use arquivos específicos | +| Muito Grande (1000+ linhas) | 15.000+ tokens | Considere dividir ou direcionar seções | + +**Exemplos concretos:** +- Os 4 arquivos Python do aplicativo de livros combinados ≈ 2.000-3.000 tokens +- Um módulo Python típico (200 linhas) ≈ 3.000 tokens +- Um arquivo Flask API (400 linhas) ≈ 6.000 tokens +- Seu package.json ≈ 200-500 tokens +- Um prompt + resposta curtos ≈ 500-1.500 tokens + +> 💡 **Estimativa rápida para código:** Multiplique as linhas de código por ~15 para obter tokens aproximados. Tenha em mente que esta é apenas uma estimativa. + +#### O que Incluir vs. Excluir + +**Alto valor** (inclua estes): +- Pontos de entrada (`book_app.py`, `main.py`, `app.py`) +- Os arquivos específicos sobre os quais você está perguntando +- Arquivos diretamente importados pelo seu arquivo alvo +- Arquivos de configuração (`requirements.txt`, `pyproject.toml`) +- Modelos de dados ou dataclasses + +**Menor valor** (considere excluir): +- Arquivos gerados (saída compilada, assets empacotados) +- Módulos Node ou diretórios de fornecedor +- Arquivos de dados grandes ou fixtures +- Arquivos não relacionados à sua pergunta + +#### O Espectro de Especificidade + +``` +Menos específico ────────────────────────► Mais específico +@samples/book-app-project/ @samples/book-app-project/books.py:47-52 + │ │ + └─ Analisa tudo └─ Apenas o que você precisa + (usa mais contexto) (preserva contexto) +``` + +**Quando ir amplo** (`@samples/book-app-project/`): +- Exploração inicial da base de código +- Encontrar padrões em muitos arquivos +- Revisões de arquitetura + +**Quando ir específico** (`@samples/book-app-project/books.py`): +- Depurar um problema específico +- Revisão de código de um arquivo específico +- Perguntar sobre uma única função + +#### Exemplo Prático: Carregamento de Contexto Gradual + +```bash +copilot + +# Etapa 1: Começar com a estrutura +> @package.json What frameworks does this project use? + +# Etapa 2: Estreitar com base na resposta +> @samples/book-app-project/ Show me the project structure + +# Etapa 3: Focar no que importa +> @samples/book-app-project/books.py Review the BookCollection class + +# Etapa 4: Adicionar arquivos relacionados somente quando necessário +> @samples/book-app-project/book_app.py @samples/book-app-project/books.py How does the CLI use the BookCollection? +``` + +Esta abordagem gradual mantém o contexto focado e eficiente. + +
+ +
+Trabalhando com Imagens + + +### Trabalhando com Imagens + +Você pode incluir imagens nas suas conversas usando a sintaxe `@`, ou simplesmente **colar da área de transferência** (Cmd+V / Ctrl+V). O Copilot CLI pode analisar capturas de tela, mockups e diagramas para ajudar com depuração de UI, implementação de design e análise de erros. + +```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. +``` + +> 📖 **Saiba mais**: Veja [Funcionalidades Adicionais de Contexto](../appendices/additional-context.md#working-with-images) para formatos suportados, casos de uso práticos e dicas para combinar imagens com código. + +
+ +--- + +# Prática + +Mesa de trabalho aconchegante com monitor mostrando código, abajur, xícara de café e fones de ouvido prontos para a prática + +Hora de aplicar suas habilidades de contexto e gerenciamento de sessões. + +--- + +## ▶️ Experimente Você Mesmo + +### Revisão Completa do Projeto + +O curso inclui arquivos de exemplo que você pode revisar diretamente. Inicie o copilot e execute o prompt mostrado a seguir: + +```bash +copilot + +> @samples/book-app-project/ Give me a code quality review of this project + +# O Copilot CLI identificará problemas como: +# - Funções de exibição duplicadas +# - Validação de entrada ausente +# - Tratamento de erros inconsistente +``` + +> 💡 **Quer tentar com seus próprios arquivos?** Crie um pequeno projeto Python (`mkdir -p my-project/src`), adicione alguns arquivos .py e depois use `@my-project/src/` para revisá-los. Você pode pedir ao copilot para criar código de exemplo se quiser! + +### Fluxo de Trabalho de Sessão + +```bash +copilot + +> /rename book-app-review +> @samples/book-app-project/books.py Let's add input validation for empty titles + +[O Copilot CLI sugere abordagem de validação] + +> Implement that fix +> Now consolidate the duplicate display functions in @samples/book-app-project/ +> /exit + +# Mais tarde - retome de onde parou +copilot --continue + +> Generate tests for the changes we made +``` + +--- + +Após concluir as demos, experimente estas variações: + +1. **Desafio Entre Arquivos**: Analise como book_app.py e books.py trabalham juntos: + ```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. **Desafio de Sessão**: Inicie uma sessão, nomeie-a com `/rename my-first-session`, faça alguma coisa, saia com `/exit` e execute `copilot --continue`. Ela lembra o que você estava fazendo? + +3. **Desafio de Contexto**: Execute `/context` no meio de uma sessão. Quantos tokens você está usando? Experimente `/compact` e verifique novamente. (Veja [Entendendo as Janelas de Contexto](#understanding-context-windows) em Indo Mais Fundo para mais sobre `/compact`.) + +**Autoavaliação**: Você entende o contexto quando consegue explicar por que `@folder/` é mais poderoso do que abrir cada arquivo individualmente. + +--- + +## 📝 Atividade + +### Desafio Principal: Rastrear o Fluxo de Dados + +Os exemplos práticos focaram em revisões de qualidade de código e validação de entrada. Agora pratique as mesmas habilidades de contexto em uma tarefa diferente, rastreando como os dados se movem pelo aplicativo: + +1. Inicie uma sessão interativa: `copilot` +2. Referencie `books.py` e `book_app.py` juntos: + `@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. Traga o arquivo de dados para contexto adicional: + `@samples/book-app-project/data.json What happens if this JSON file is missing or corrupted? Which functions would fail?` +4. Peça uma melhoria entre arquivos: + `@samples/book-app-project/books.py @samples/book-app-project/utils.py Suggest a consistent error-handling strategy that works across both files.` +5. Renomeie a sessão: `/rename data-flow-analysis` +6. Saia com `/exit`, então retome com `copilot --continue` e faça uma pergunta de acompanhamento sobre o fluxo de dados + +**Critérios de sucesso**: Você consegue rastrear dados entre múltiplos arquivos, retomar uma sessão nomeada e obter sugestões entre arquivos. + +
+💡 Dicas (clique para expandir) + +**Como começar:** +```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 +``` + +Então retome com: `copilot --continue` + +**Comandos úteis:** +- `@file.py` - Referenciar um único arquivo +- `@folder/` - Referenciar todos os arquivos em uma pasta (observe a `/` no final) +- `/context` - Verificar quanto contexto você está usando +- `/rename ` - Nomear sua sessão para fácil retomada + +
+ +### Desafio Bônus: Limites de Contexto + +1. Referencie todos os arquivos do aplicativo de livros de uma vez com `@samples/book-app-project/` +2. Faça várias perguntas detalhadas sobre arquivos diferentes (`books.py`, `utils.py`, `book_app.py`, `data.json`) +3. Execute `/context` para ver o uso. Quão rapidamente ele se preenche? +4. Pratique usar `/compact` para recuperar espaço e continue a conversa +5. Tente ser mais específico com referências de arquivo (ex.: `@samples/book-app-project/books.py` em vez de toda a pasta) e veja como afeta o uso de contexto + +--- + +
+🔧 Erros Comuns e Solução de Problemas (clique para expandir) + +### Erros Comuns + +| Erro | O que Acontece | Solução | +|------|----------------|---------| +| Esquecer o `@` antes dos nomes de arquivo | O Copilot CLI trata "books.py" como texto simples | Use `@samples/book-app-project/books.py` para referenciar arquivos | +| Esperar que as sessões persistam automaticamente | Iniciar o `copilot` do zero perde todo o contexto anterior | Use `--continue` (última sessão) ou `--resume` (escolher uma sessão) | +| Referenciar arquivos fora do diretório atual | Erros de "Permissão negada" ou "Arquivo não encontrado" | Use `/add-dir /caminho/para/diretório` para conceder acesso | +| Não usar `/clear` ao trocar de assunto | Contexto antigo confunde respostas sobre o novo assunto | Execute `/clear` antes de iniciar uma tarefa diferente | + +### Solução de Problemas + +**Erros de "Arquivo não encontrado"** - Certifique-se de estar no diretório correto: + +```bash +pwd # Verificar diretório atual +ls # Listar arquivos + +# Então inicie o copilot e use caminhos relativos +copilot + +> Review @samples/book-app-project/books.py +``` + +**"Permissão negada"** - Adicione o diretório à sua lista de permitidos: + +```bash +copilot --add-dir /caminho/para/diretório + +# Ou em uma sessão: +> /add-dir /caminho/para/diretório +``` + +**O contexto se preenche muito rápido**: +- Seja mais específico com referências de arquivo +- Use `/clear` entre diferentes assuntos +- Divida o trabalho em múltiplas sessões + +
+ +--- + +# Resumo + +## 🔑 Principais Aprendizados + +1. **A sintaxe `@`** fornece ao Copilot CLI contexto sobre arquivos, diretórios e imagens +2. **As conversas com múltiplas trocas** se baseiam umas nas outras à medida que o contexto se acumula +3. **As sessões são salvas automaticamente**: nomeie-as na inicialização com `--name`, retome pelo nome com `--resume=`, ou use `--continue` para pegar a sessão mais recente +4. **As janelas de contexto** têm limites: gerencie-as com `/clear`, `/compact`, `/context`, `/new` e `/rewind` +5. **Os flags de permissão** (`--add-dir`, `--allow-all`) controlam o acesso a múltiplos diretórios. Use-os sabiamente! +6. **As referências de imagem** (`@screenshot.png`) ajudam a depurar problemas de UI visualmente + +> 📚 **Documentação oficial**: [Usar o Copilot CLI](https://docs.github.com/copilot/how-tos/copilot-cli/use-copilot-cli) para a referência completa sobre contexto, sessões e trabalho com arquivos. + +> 📋 **Referência rápida**: Veja a [referência de comandos do GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para uma lista completa de comandos e atalhos. + +--- + +## ➡️ O Que Vem a Seguir + +Agora que você pode fornecer contexto ao Copilot CLI, vamos colocá-lo para trabalhar em tarefas reais de desenvolvimento. As técnicas de contexto que você acabou de aprender (referências de arquivo, análise entre arquivos e gerenciamento de sessões) são a base para os fluxos de trabalho poderosos do próximo capítulo. + +No **[Capítulo 03: Fluxos de Trabalho de Desenvolvimento](../03-development-workflows/README.md)**, você aprenderá: + +- Fluxos de trabalho de revisão de código +- Padrões de refatoração +- Assistência na depuração +- Geração de testes +- Integração com Git + +--- + +**[← Voltar ao Capítulo 01](../01-setup-and-first-steps/README.md)** | **[Continuar para o Capítulo 03 →](../03-development-workflows/README.md)** diff --git a/localization/pt-br/03-development-workflows/README.md b/localization/pt-br/03-development-workflows/README.md new file mode 100644 index 00000000..04fd456b --- /dev/null +++ b/localization/pt-br/03-development-workflows/README.md @@ -0,0 +1,972 @@ +![Capítulo 03: Fluxos de Trabalho de Desenvolvimento](../../../03-development-workflows/images/chapter-header.png) + +> **E se a IA pudesse encontrar bugs que você nem sequer sabia que devia procurar?** + +Neste capítulo, o GitHub Copilot CLI se torna seu companheiro diário de trabalho. Você vai usá-lo dentro dos fluxos de trabalho com os quais você já conta todos os dias: testes, refatoração, depuração e Git. + +## 🎯 Objetivos de aprendizado + +Ao final deste capítulo, você será capaz de: + +- Executar revisões de código abrangentes com o Copilot CLI +- Refatorar código legado com segurança +- Depurar problemas com assistência de IA +- Gerar testes automaticamente +- Integrar o Copilot CLI ao seu fluxo de trabalho com git + +> ⏱️ **Tempo estimado**: ~60 minutos (15 min de leitura + 45 min de prática) + +--- + +## 🧩 Analogia com o Mundo Real: O Fluxo de Trabalho de um Carpinteiro + +Um carpinteiro não apenas sabe usar ferramentas, ele tem *fluxos de trabalho* para diferentes trabalhos: + +Oficina de artesão mostrando três fluxas de trabalho: Fabricar Móveis (Medir, Cortar, Montar, Acabar), Consertar Danos (Avaliar, Remover, Reparar, Igualar) e Controle de Qualidade (Inspecionar, Testar Juntas, Verificar Alinhamento) + +Da mesma forma, os desenvolvedores têm fluxos de trabalho para diferentes tarefas. O GitHub Copilot CLI aprimora cada um desses fluxos de trabalho, tornando você mais eficiente e eficaz nas suas tarefas diárias de codificação. + +--- + +# Os Cinco Fluxos de Trabalho + +Cinco ícones neon brilhantes representando os fluxos de trabalho de revisão de código, testes, depuração, refatoração e integração com git + +Cada fluxo de trabalho abaixo é independente. Escolha os que correspondem às suas necessidades atuais, ou passe por todos eles. + +--- + +## Escolha Seu Próprio Caminho + +Este capítulo cobre cinco fluxos de trabalho que os desenvolvedores normalmente usam. **No entanto, você não precisa ler todos de uma vez!** Cada fluxo de trabalho é independente em uma seção expansível abaixo. Escolha os que melhor correspondem ao que você precisa e ao seu projeto atual. Você pode sempre voltar e explorar os outros mais tarde. + +Cinco Fluxos de Trabalho de Desenvolvimento: Revisão de Código, Refatoração, Depuração, Geração de Testes e Integração com Git mostrados como raias horizontais + +| Quero... | Ir para | +|---|---| +| Revisar código antes de fazer merge | [Fluxo de Trabalho 1: Revisão de Código](#workflow-1-code-review) | +| Limpar código bagunçado ou legado | [Fluxo de Trabalho 2: Refatoração](#workflow-2-refactoring) | +| Rastrear e corrigir um bug | [Fluxo de Trabalho 3: Depuração](#workflow-3-debugging) | +| Gerar testes para meu código | [Fluxo de Trabalho 4: Geração de Testes](#workflow-4-test-generation) | +| Escrever commits e PRs melhores | [Fluxo de Trabalho 5: Integração com Git](#workflow-5-git-integration) | +| Pesquisar antes de codificar | [Dica Rápida: Pesquise Antes de Planejar ou Codificar](#quick-tip-research-before-you-plan-or-code) | +| Ver um fluxo de trabalho completo de correção de bug | [Juntando Tudo](#putting-it-all-together-bug-fix-workflow) | + +**Selecione um fluxo de trabalho abaixo para expandi-lo** e veja como o GitHub Copilot CLI pode aprimorar o seu processo de desenvolvimento nessa área. + +--- + + +
+Fluxo de Trabalho 1: Revisão de Código - Revisar arquivos, usar o agente /review, criar checklists por gravidade + +Fluxo de trabalho de revisão de código: revisar, identificar problemas, priorizar, gerar checklist. + +### Revisão Básica + +Este exemplo usa o símbolo `@` para referenciar um arquivo, dando ao Copilot CLI acesso direto ao seu conteúdo para revisão. + +```bash +copilot + +> Review @samples/book-app-project/book_app.py for code quality +``` + +--- + +
+🎬 Veja em ação! + +![Demo de Revisão de Código](../../../03-development-workflows/images/code-review-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +### Revisão de Validação de Entrada + +Peça ao Copilot CLI para focar sua revisão em uma preocupação específica (aqui, validação de entrada) listando as categorias que você se importa no prompt. + +```text +copilot + +> Review @samples/book-app-project/utils.py for input validation issues. Check for: missing validation, error handling gaps, and edge cases +``` + + +### Revisão de Projeto com Múltiplos Arquivos + +Referencie um diretório inteiro com `@` para deixar o Copilot CLI analisar cada arquivo no projeto de uma vez. + +```bash +copilot + +> @samples/book-app-project/ Review this entire project. Create a markdown checklist of issues found, categorized by severity +``` + +### Revisão de Código Interativa + +Use uma conversa com múltiplas trocas para aprofundar. Comece com uma revisão ampla, depois faça perguntas de acompanhamento sem reiniciar. + +```bash +copilot + +> @samples/book-app-project/book_app.py Review this file for: +> - Input validation +> - Error handling +> - Code style and best practices + +# O Copilot CLI fornece revisão detalhada + +> The user input handling - are there any edge cases I'm missing? + +# O Copilot CLI mostra problemas potenciais com strings vazias e caracteres especiais + +> Create a checklist of all issues found, prioritized by severity + +# O Copilot CLI gera itens de ação priorizados +``` + +### Modelo de Checklist de Revisão + +Peça ao Copilot CLI para estruturar sua saída em um formato específico (aqui, um checklist markdown categorizado por gravidade que você pode colar em uma 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) +``` + +### Entendendo as Alterações do Git (Importante para /review) + +Antes de usar o comando `/review`, você precisa entender dois tipos de alterações no git: + +| Tipo de Alteração | O que Significa | Como Ver | +|-------------------|-----------------|----------| +| **Alterações staged** | Arquivos que você marcou para o próximo commit com `git add` | `git diff --staged` | +| **Alterações unstaged** | Arquivos que você modificou mas ainda não adicionou | `git diff` | + +```bash +# Referência rápida +git status # Mostra tanto staged quanto unstaged +git add file.py # Fazer stage de um arquivo para commit +git diff # Mostra alterações unstaged +git diff --staged # Mostra alterações staged +``` + +### Usando o Comando /review + +O comando `/review` invoca o **agente de revisão de código** integrado, que é otimizado para analisar alterações staged e unstaged com saída de alto sinal-ruído. Use um slash command para acionar um agente integrado especializado em vez de escrever um prompt livre. + +```bash +copilot + +> /review +# Invoca o agente de revisão de código em alterações staged/unstaged +# Fornece feedback focado e acionável + +> /review Check for security issues in authentication +# Execute a revisão com área de foco específica +``` + +> 💡 **Dica**: O agente de revisão de código funciona melhor quando você tem alterações pendentes. Faça stage dos seus arquivos com `git add` para revisões mais focadas. + +
+ +--- + + +
+Fluxo de Trabalho 2: Refatoração - Reestruturar código, separar responsabilidades, melhorar o tratamento de erros + +Fluxo de trabalho de refatoração: avaliar código, planejar alterações, implementar, verificar comportamento. + +### Refatoração Simples + +> **Experimente primeiro:** `@samples/book-app-project/book_app.py The command handling uses if/elif chains. Refactor it to use a dictionary dispatch pattern.` + +Comece com melhorias simples. Experimente no aplicativo de livros. Cada prompt usa uma referência de arquivo com `@` combinada com uma instrução de refatoração específica para que o Copilot CLI saiba exatamente o que mudar. + +```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 +``` + +> 💡 **Novo em refatoração?** Comece com solicitações simples como adicionar dicas de tipo ou melhorar nomes de variáveis antes de lidar com transformações complexas. + +--- + +
+🎬 Veja em ação! + +![Demo de Refatoração](../../../03-development-workflows/images/refactor-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +### Separar Responsabilidades + +Referencie múltiplos arquivos com `@` em um único prompt para que o Copilot CLI possa mover código entre eles como parte da refatoração. + +```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. +``` + +### Melhorar o Tratamento de Erros + +Forneça dois arquivos relacionados e descreva a preocupação transversal para que o Copilot CLI possa sugerir uma correção consistente em ambos. + +```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. +``` + +### Adicionar Documentação + +Use uma lista detalhada de bullets para especificar exatamente o que cada docstring deve conter. + +```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 +``` + +### Refatoração Segura com Testes + +Encadeie dois pedidos relacionados em uma conversa com múltiplas trocas. Primeiro gere testes, depois refatore com esses testes como rede de segurança. + +```bash +copilot + +> @samples/book-app-project/books.py Before refactoring, generate tests for current behavior + +# Obtenha os testes primeiro + +> Now refactor the BookCollection class to use a context manager for file operations + +# Refatore com confiança - os testes verificam se o comportamento é preservado +``` + +
+ +--- + + +
+Fluxo de Trabalho 3: Depuração - Rastrear bugs, auditorias de segurança, rastrear problemas entre arquivos + +Fluxo de trabalho de depuração: entender o erro, localizar a causa raiz, corrigir, testar. + +### Depuração Simples + +> **Experimente primeiro:** `@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.` + +Comece descrevendo o que está errado. Aqui estão padrões comuns de depuração que você pode experimentar com o aplicativo de livros com bugs. Cada prompt combina uma referência de arquivo com `@` e uma descrição clara do sintoma para que o Copilot CLI possa localizar e diagnosticar o bug. + +```bash +copilot + +# Padrão: "Esperava X mas obtive 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. + +# Padrão: "Comportamento inesperado" +> @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. + +# Padrão: "Resultados errados" +> @samples/book-app-buggy/books_buggy.py When I mark one book as read, ALL books get marked. What's the bug? +``` + +> 💡 **Dica de depuração**: Descreva o *sintoma* (o que você vê) e a *expectativa* (o que deveria acontecer). O Copilot CLI cuida do resto. + +--- + +
+🎬 Veja em ação! + +![Demo de Correção de Bug](../../../03-development-workflows/images/fix-bug-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +### O "Detetive de Bugs" - A IA Encontra Bugs RELACIONADOS + +É aqui que a depuração consciente do contexto brilha. Experimente este cenário com o aplicativo de livros com bugs. Forneça o arquivo inteiro via `@` e descreva apenas o sintoma reportado pelo usuário. O Copilot CLI vai rastrear a causa raiz e pode identificar bugs adicionais nas proximidades. + +```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 +``` + +**O que o Copilot CLI faz**: +``` +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()] +``` + +**Por que isso importa**: O Copilot CLI lê o arquivo inteiro, entende o contexto do seu relatório de bug e fornece uma correção específica com uma explicação clara. + +> 💡 **Bônus**: Como o Copilot CLI analisa o arquivo inteiro, ele frequentemente descobre *outros* problemas que você não perguntou. Por exemplo, enquanto corrige a busca por autor, o Copilot CLI pode também notar o bug de sensibilidade a maiúsculas e minúsculas em `find_book_by_title`! + +### Exemplo Real de Segurança + +Embora depurar seu próprio código seja importante, entender vulnerabilidades de segurança em aplicações de produção é crítico. Experimente este exemplo: Aponte o Copilot CLI para um arquivo desconhecido e peça para auditar por problemas de segurança. + +```bash +copilot + +> @samples/buggy-code/python/user_service.py Find all security vulnerabilities in this Python user service +``` + +Este arquivo demonstra padrões reais de segurança que você encontrará em apps de produção. + +> 💡 **Termos comuns de segurança que você encontrará:** +> - **SQL Injection**: Quando a entrada do usuário é colocada diretamente em uma consulta de banco de dados, permitindo que atacantes executem comandos maliciosos +> - **Parameterized queries (consultas parametrizadas)**: A alternativa segura - espaços reservados (`?`) separam os dados do usuário dos comandos SQL +> - **Race condition (condição de corrida)**: Quando duas operações acontecem ao mesmo tempo e interferem uma na outra +> - **XSS (Cross-Site Scripting)**: Quando atacantes injetam scripts maliciosos em páginas web + +--- + +### Entendendo um Erro + +Cole um rastreamento de pilha diretamente no seu prompt junto com uma referência de arquivo `@` para que o Copilot CLI possa mapear o erro para o código-fonte. + +```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 +``` + +### Depuração com Caso de Teste + +Descreva a entrada exata e a saída observada para dar ao Copilot CLI um caso de teste concreto e reproduzível para raciocinar. + +```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. +``` + +### Rastrear um Problema pelo Código + +Referencie múltiplos arquivos e peça ao Copilot CLI para seguir o fluxo de dados entre eles para localizar onde o problema se origina. + +```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 +``` + +### Entendendo Problemas de Dados + +Inclua um arquivo de dados junto com o código que o lê para que o Copilot CLI entenda o quadro completo ao sugerir melhorias no tratamento de erros. + +```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? +``` + +
+ +--- + + +
+Fluxo de Trabalho 4: Geração de Testes - Gerar testes abrangentes e casos extremos automaticamente + +Fluxo de trabalho de geração de testes: analisar função, gerar testes, incluir casos extremos, executar. + +> **Experimente primeiro:** `@samples/book-app-project/books.py Generate pytest tests for all functions including edge cases` + +### A "Explosão de Testes" - 2 Testes versus 15+ Testes + +Ao escrever testes manualmente, os desenvolvedores tipicamente criam 2-3 testes básicos: +- Testar entrada válida +- Testar entrada inválida +- Testar um caso extremo + +Veja o que acontece quando você pede ao Copilot CLI para gerar testes abrangentes! Este prompt usa uma lista de bullets estruturada com uma referência de arquivo `@` para guiar o Copilot CLI para uma cobertura de teste completa: + +```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 +``` + +--- + +
+🎬 Veja em ação! + +![Demo de Geração de Testes](../../../03-development-workflows/images/test-gen-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +**O que você obtém**: 15+ testes abrangentes incluindo: + +```python +class TestBookCollection: + # Caminho feliz + def test_add_book_creates_new_book(self): + ... + def test_list_books_returns_all_books(self): + ... + + # Operações de busca + 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): + ... + + # Casos extremos + def test_add_book_with_empty_title(self): + ... + def test_remove_nonexistent_book(self): + ... + def test_mark_as_read_nonexistent_book(self): + ... + + # Persistência de dados + def test_save_books_persists_to_json(self): + ... + def test_load_books_handles_missing_file(self): + ... + def test_load_books_handles_corrupted_json(self): + ... + + # Caracteres especiais + def test_add_book_with_unicode_characters(self): + ... + def test_find_by_author_with_special_characters(self): + ... +``` + +**Resultado**: Em 30 segundos, você obtém testes de casos extremos que levariam uma hora para pensar e escrever. + +--- + +### Testes Unitários + +Direcione para uma única função e enumere as categorias de entrada que você quer testar para que o Copilot CLI gere testes unitários focados e completos. + +```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 +``` + +### Executando Testes + +Faça ao Copilot CLI uma pergunta em linguagem natural sobre seu conjunto de ferramentas. Ele pode gerar o comando de shell correto para você. + +```bash +copilot + +> How do I run the tests? Show me the pytest command. + +# O Copilot CLI responde: +# cd samples/book-app-project && python -m pytest tests/ +# Ou para saída detalhada: python -m pytest tests/ -v +# Para ver instruções de print: python -m pytest tests/ -s +``` + +### Testar Cenários Específicos + +Liste cenários avançados ou complicados que você quer cobertos para que o Copilot CLI vá além do caminho feliz. + +```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 +``` + +### Adicionar Testes a um Arquivo Existente + +Peça testes *adicionais* para uma única função para que o Copilot CLI gere novos casos que complementem o que você já tem. + +```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 +``` + +
+ +--- + + +
+Fluxo de Trabalho 5: Integração com Git - Mensagens de commit, descrições de PR, /pr, /delegate e /diff + +Fluxo de trabalho de integração com git: fazer stage das alterações, gerar mensagem, fazer commit, criar PR. + +> 💡 **Este fluxo de trabalho pressupõe familiaridade básica com git** (staging, commit, branches). Se git é novo para você, experimente os outros quatro fluxos de trabalho primeiro. + +### Gerar Mensagens de Commit + +> **Experimente primeiro:** `copilot -p "Generate a conventional commit message for: $(git diff --staged)"` — faça stage de algumas alterações, depois execute isso para ver o Copilot CLI escrever sua mensagem de commit. + +Este exemplo usa o flag de prompt inline `-p` com substituição de comando de shell para canalizar a saída do `git diff` diretamente para o Copilot CLI para uma mensagem de commit em uma única execução. A sintaxe `$(...)` executa o comando dentro dos parênteses e insere sua saída no comando externo. + +```bash + +# Veja o que mudou +git diff --staged + +# Gerar mensagem de commit usando o formato de [Commit Convencional](../../../GLOSSARY.md#conventional-commit) +# (mensagens estruturadas como "feat(books): add search" ou "fix(data): handle empty input") +copilot -p "Generate a conventional commit message for: $(git diff --staged)" + +# Saída: "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" +``` + +--- + +
+🎬 Veja em ação! + +![Demo de Integração com Git](../../../03-development-workflows/images/git-integration-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +### Explicar Alterações + +Canalize a saída do `git show` para um prompt `-p` para obter um resumo em linguagem natural do último commit. + +```bash +# O que este commit mudou? +copilot -p "Explain what this commit does: $(git show HEAD --stat)" +``` + +### Descrição de PR + +Combine a saída do `git log` com um modelo de prompt estruturado para gerar automaticamente uma descrição completa de pull request. + +```bash +# Gerar descrição de PR a partir das alterações da branch +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)" +``` + +### Usando /pr no Modo Interativo para a Branch Atual + +Se você está trabalhando com uma branch no modo interativo do Copilot CLI, pode usar o comando `/pr` para trabalhar com pull requests. Use `/pr` para ver um PR, criar um novo PR, corrigir um PR existente, ou deixar o Copilot CLI decidir automaticamente com base no estado da branch. + +```bash +copilot + +> /pr [view|create|fix|auto] +``` + +### Revisar Antes de Enviar + +Use `git diff main..HEAD` dentro de um prompt `-p` para uma verificação rápida antes do envio em todas as alterações da branch. + +```bash +# Última verificação antes de enviar +copilot -p "Review these changes for issues before I push: +$(git diff main..HEAD)" +``` + +### Usando /delegate para Tarefas em Segundo Plano + +O comando `/delegate` passa o trabalho para o agente de nuvem do GitHub Copilot. Use o slash command `/delegate` (ou o atalho `&`) para delegar uma tarefa bem definida a um agente em segundo plano. + +```bash +copilot + +> /delegate Add input validation to the login form + +# Ou use o atalho com prefixo &: +> & Fix the typo in the README header + +# O Copilot CLI: +# 1. Faz commit das suas alterações em uma nova branch +# 2. Abre um pull request rascunho +# 3. Trabalha em segundo plano no GitHub +# 4. Solicita a sua revisão quando terminar +``` + +Isso é ótimo para tarefas bem definidas que você quer completadas enquanto se concentra em outro trabalho. + +### Usando /diff para Revisar as Alterações da Sessão + +O comando `/diff` mostra todas as alterações feitas durante a sua sessão atual. Use este slash command para ver um diff visual de tudo que o Copilot CLI modificou antes de fazer commit. + +```bash +copilot + +# Após fazer algumas alterações... +> /diff + +# Mostra um diff visual de todos os arquivos modificados nesta sessão +# Ótimo para revisar antes de fazer commit +``` + +
+ +--- + +## Dica Rápida: Pesquise Antes de Planejar ou Codificar + +Quando você precisar investigar uma biblioteca, entender melhores práticas ou explorar um tópico desconhecido, use `/research` para executar uma investigação de pesquisa profunda antes de escrever qualquer código: + +```bash +copilot + +> /research What are the best Python libraries for validating user input in CLI apps? +``` + +O Copilot pesquisa repositórios do GitHub e fontes da web, depois retorna um resumo com referências. Isso é útil quando você está prestes a iniciar uma nova funcionalidade e quer tomar decisões informadas primeiro. Você pode compartilhar os resultados usando `/share`. + +> 💡 **Dica**: `/research` funciona bem *antes* de `/plan`. Pesquise a abordagem, depois planeje a implementação. + +--- + +## Juntando Tudo: Fluxo de Trabalho de Correção de Bug + +Aqui está um fluxo de trabalho completo para corrigir um bug reportado: + +```bash + +# 1. Entender o relatório de bug +copilot + +> Users report: 'Finding books by author name doesn't work for partial names' +> @samples/book-app-project/books.py Analyze and identify the likely cause + +# 2. Depurar o problema e corrigir (continuando na mesma sessão) +> Based on the analysis, show me the find_by_author function and explain the issue + +> Fix the find_by_author function to handle partial name matches + +# 3. Gerar testes para a correção +> @samples/book-app-project/books.py Generate pytest tests specifically for: +> - Full author name match +> - Partial author name match +> - Case-insensitive matching +> - Author name not found + +# Sair da sessão interativa + +> /exit + +# 4. Executar git add + +# Fazer stage das alterações para que git diff --staged tenha algo para trabalhar +git add . + +# 5. Gerar mensagem de commit +copilot -p "Generate commit message for: $(git diff --staged)" + +# Exemplo de saída: "fix(books): support partial author name search" + +# 6. Fazer commit das alterações (opcional) + +git commit -m "" +``` + +### Resumo do Fluxo de Trabalho de Correção de Bug + +| Etapa | Ação | Comando Copilot | +|-------|------|-----------------| +| 1 | Entender o bug | `> [descrever o bug] @arquivo-relevante.py Analyze the likely cause` | +| 2 | Análise e correção | `> Show me the function and fix the issue` | +| 3 | Gerar testes | `> Generate tests for [cenários específicos]` | +| 4 | Fazer stage das alterações | `git add .` | +| 5 | Gerar mensagem de commit | `copilot -p "Generate commit message for: $(git diff --staged)"` | +| 6 | Fazer commit das alterações | `git commit -m ""` | + +--- + +# Prática + +Mesa de trabalho aconchegante com monitor mostrando código, abajur, xícara de café e fones de ouvido prontos para a prática + +Agora é a sua vez de aplicar esses fluxos de trabalho. + +--- + +## ▶️ Experimente Você Mesmo + +Após concluir as demos, experimente estas variações: + +1. **Desafio do Detetive de Bugs**: Peça ao Copilot CLI para depurar a função `mark_as_read` em `samples/book-app-buggy/books_buggy.py`. Ele explicou por que a função marca TODOS os livros como lidos em vez de apenas um? + +2. **Desafio de Testes**: Gere testes para a função `add_book` no aplicativo de livros. Conte quantos casos extremos o Copilot CLI inclui que você não teria pensado. + +3. **Desafio de Mensagem de Commit**: Faça qualquer pequena alteração em um arquivo do aplicativo de livros, faça stage com (`git add .`), depois execute: + ```bash + copilot -p "Generate a conventional commit message for: $(git diff --staged)" + ``` + A mensagem é melhor do que o que você teria escrito rapidamente? + +**Autoavaliação**: Você entende os fluxos de trabalho de desenvolvimento quando consegue explicar por que "depurar este bug" é mais poderoso do que "encontrar bugs" (o contexto importa!). + +--- + +## 📝 Atividade + +### Desafio Principal: Refatorar, Testar e Publicar + +Os exemplos práticos focaram em `find_book_by_title` e revisões de código. Agora pratique as mesmas habilidades de fluxo de trabalho em funções diferentes do `book-app-project`: + +1. **Revisar**: Peça ao Copilot CLI para revisar `remove_book()` em `books.py` para casos extremos e problemas potenciais: + `@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. **Refatorar**: Peça ao Copilot CLI para melhorar `remove_book()` para lidar com casos extremos como correspondência sem distinção de maiúsculas e minúsculas e retornar feedback útil quando um livro não for encontrado +3. **Testar**: Gere testes pytest especificamente para a função `remove_book()` melhorada, cobrindo: + - Remover um livro que existe + - Correspondência de título sem distinção de maiúsculas e minúsculas + - Um livro que não existe retorna feedback apropriado + - Remover de uma coleção vazia +4. **Revisar**: Faça stage das suas alterações e execute `/review` para verificar quaisquer problemas restantes +5. **Fazer Commit**: Gere uma mensagem de commit convencional: + `copilot -p "Generate a conventional commit message for: $(git diff --staged)"` + +
+💡 Dicas (clique para expandir) + +**Prompts de exemplo para cada etapa:** + +```bash +copilot + +# Etapa 1: Revisar +> @samples/book-app-project/books.py Review the remove_book() function. What edge cases are not handled? + +# Etapa 2: Refatorar +> 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. + +# Etapa 3: Testar +> 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 + +# Etapa 4: Revisar +> /review + +# Etapa 5: Fazer Commit +> Generate a conventional commit message for this refactor +``` + +**Dica:** Após melhorar `remove_book()`, tente perguntar ao Copilot CLI: "Are there any other functions in this file that could benefit from the same improvements?". Ele pode sugerir alterações semelhantes para `find_book_by_title()` ou `find_by_author()`. + +
+ +### Desafio Bônus: Criar uma aplicação com o Copilot CLI + +> 💡 **Observação**: Este exercício do GitHub Skills usa **Node.js** em vez de Python. As técnicas do GitHub Copilot CLI que você vai praticar — criar issues, gerar código e colaborar pelo terminal — se aplicam a qualquer linguagem. + +O exercício mostra aos desenvolvedores como usar o GitHub Copilot CLI para criar issues, gerar código e colaborar pelo terminal enquanto constroem um aplicativo calculadora em Node.js. Você vai instalar o CLI, usar templates e agentes, e praticar o desenvolvimento iterativo orientado pela linha de comando. + +##### [Iniciar o Exercício Skills "Criar aplicações com o Copilot CLI"](https://github.com/skills/create-applications-with-the-copilot-cli) + +--- + +
+🔧 Erros Comuns e Solução de Problemas (clique para expandir) + +### Erros Comuns + +| Erro | O que Acontece | Solução | +|------|----------------|---------| +| Usar prompts vagos como "Review this code" | Feedback genérico que perde problemas específicos | Seja específico: "Review for SQL injection, XSS, and auth issues" | +| Não usar `/review` para revisões de código | Perdendo o agente de revisão de código otimizado | Use `/review` que é ajustado para saída de alto sinal-ruído | +| Pedir para "encontrar bugs" sem contexto | O Copilot CLI não sabe qual bug você está experimentando | Descreva o sintoma: "Users report X happens when Y" | +| Gerar testes sem especificar o framework | Os testes podem usar sintaxe ou biblioteca de asserção errada | Especifique: "Generate tests using Jest" ou "using pytest" | + +### Solução de Problemas + +**A revisão parece incompleta** - Seja mais específico sobre o que procurar: + +```bash +copilot + +# Em vez de: +> Review @samples/book-app-project/book_app.py + +# Tente: +> Review @samples/book-app-project/book_app.py for input validation, error handling, and edge cases +``` + +**Os testes não correspondem ao meu framework** - Especifique o framework: + +```bash +copilot + +> @samples/book-app-project/books.py Generate tests using pytest (not unittest) +``` + +**A refatoração muda o comportamento** - Peça ao Copilot CLI para preservar o comportamento: + +```bash +copilot + +> @samples/book-app-project/book_app.py Refactor command handling to use dictionary dispatch. IMPORTANT: Maintain identical external behavior - no breaking changes +``` + +
+ +--- + +# Resumo + +## 🔑 Principais Aprendizados + +Fluxos de Trabalho Especializados para Cada Tarefa: Revisão de Código, Refatoração, Depuração, Testes e Integração com Git + +1. **A revisão de código** se torna abrangente com prompts específicos +2. **A refatoração** é mais segura quando você gera testes primeiro +3. **A depuração** se beneficia de mostrar ao Copilot CLI o erro E o código +4. **A geração de testes** deve incluir casos extremos e cenários de erro +5. **A integração com Git** automatiza mensagens de commit e descrições de PR + +> 📋 **Referência rápida**: Veja a [referência de comandos do GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para uma lista completa de comandos e atalhos. + +--- + +## ✅ Ponto de Verificação: Você Dominou os Fundamentos + +**Parabéns!** Agora você tem todas as habilidades essenciais para ser produtivo com o GitHub Copilot CLI: + +| Habilidade | Capítulo | Você Agora Pode... | +|------------|---------|-------------------| +| Comandos Básicos | Cap 01 | Usar o modo interativo, modo plan, modo programático (-p) e slash commands | +| Contexto | Cap 02 | Referenciar arquivos com `@`, gerenciar sessões, entender janelas de contexto | +| Fluxos de Trabalho | Cap 03 | Revisar código, refatorar, depurar, gerar testes, integrar com git | + +Os Capítulos 04-06 cobrem funcionalidades adicionais que adicionam ainda mais poder e valem a pena aprender. + +--- + +## 🛠️ Construindo Seu Fluxo de Trabalho Pessoal + +Não há uma única forma "certa" de usar o GitHub Copilot CLI. Aqui estão algumas dicas enquanto você desenvolve seus próprios padrões: + +> 📚 **Documentação oficial**: [Melhores práticas do Copilot CLI](https://docs.github.com/copilot/how-tos/copilot-cli/cli-best-practices) para fluxos de trabalho recomendados e dicas do GitHub. + +- **Comece com `/plan`** para qualquer coisa não trivial. Refine o plano antes da execução — um bom plano leva a melhores resultados. +- **Salve prompts que funcionam bem.** Quando o Copilot CLI cometer um erro, anote o que deu errado. Com o tempo, isso se torna o seu manual pessoal. +- **Experimente livremente.** Alguns desenvolvedores preferem prompts longos e detalhados. Outros preferem prompts curtos com acompanhamentos. Experimente diferentes abordagens e observe o que parece natural. + +> 💡 **Em breve**: Nos Capítulos 04 e 05, você aprenderá como codificar suas melhores práticas em instruções personalizadas e skills que o Copilot CLI carrega automaticamente. + +--- + +## ➡️ O Que Vem a Seguir + +Os capítulos restantes cobrem funcionalidades adicionais que estendem as capacidades do Copilot CLI: + +| Capítulo | O que Abrange | Quando Você vai Querer | +|----------|---------------|------------------------| +| Cap 04: Agentes | Criar personas de IA especializadas | Quando você quiser especialistas de domínio (frontend, segurança) | +| Cap 05: Skills | Carregar instruções automaticamente para tarefas | Quando você repetir os mesmos prompts com frequência | +| Cap 06: MCP | Conectar serviços externos | Quando você precisar de dados ao vivo do GitHub, bancos de dados | + +**Recomendação**: Experimente os fluxos de trabalho essenciais por uma semana, depois volte aos Capítulos 04-06 quando tiver necessidades específicas. + +--- + +## Continuar para Tópicos Adicionais + +No **[Capítulo 04: Agentes e Instruções Personalizadas](../04-agents-custom-instructions/README.md)**, você aprenderá: + +- Usar agentes integrados (`/plan`, `/review`) +- Criar agentes especializados (especialista em frontend, auditor de segurança) com arquivos `.agent.md` +- Padrões de colaboração entre múltiplos agentes +- Arquivos de instruções personalizadas para padrões de projeto + +--- + +**[← Voltar ao Capítulo 02](../02-context-conversations/README.md)** | **[Continuar para o Capítulo 04 →](../04-agents-custom-instructions/README.md)** diff --git a/localization/pt-br/04-agents-custom-instructions/README.md b/localization/pt-br/04-agents-custom-instructions/README.md new file mode 100644 index 00000000..7990700f --- /dev/null +++ b/localization/pt-br/04-agents-custom-instructions/README.md @@ -0,0 +1,783 @@ +![Capítulo 04: Agentes e Instruções Personalizadas](../../../04-agents-custom-instructions/images/chapter-header.png) + +> **E se você pudesse contratar um revisor de código Python, um especialista em testes e um revisor de segurança... tudo em uma única ferramenta?** + +No Capítulo 03, você dominou os fluxos de trabalho essenciais: revisão de código, refatoração, depuração, geração de testes e integração com git. Esses recursos tornam você altamente produtivo com o GitHub Copilot CLI. Agora, vamos ir além. + +Até agora, você usou o Copilot CLI como um assistente de uso geral. Os agentes permitem que você lhe dê uma persona específica com padrões integrados, como um revisor de código que aplica dicas de tipo e PEP 8, ou um assistente de testes que escreve casos pytest. Você verá como o mesmo prompt obtém resultados visivelmente melhores quando tratado por um agente com instruções direcionadas. + +## 🎯 Objetivos de aprendizado + +Ao final deste capítulo, você será capaz de: + +- Usar agentes integrados: Plan (`/plan`), Code-review (`/review`) e entender agentes automáticos (Explore, Task) +- Criar agentes especializados usando arquivos de agente (`.agent.md`) +- Usar agentes para tarefas específicas de domínio +- Alternar entre agentes usando `/agent` e `--agent` +- Escrever arquivos de instruções personalizadas para padrões específicos do projeto + +> ⏱️ **Tempo estimado**: ~55 minutos (20 min de leitura + 35 min de prática) + +--- + +## 🧩 Analogia com o Mundo Real: Contratar Especialistas + +Quando você precisa de ajuda com a sua casa, você não chama um "ajudante geral". Você chama especialistas: + +| Problema | Especialista | Por quê | +|----------|-------------|---------| +| Cano com vazamento | Encanador | Conhece os códigos de encanamento, tem ferramentas especializadas | +| Fiação elétrica | Eletricista | Entende os requisitos de segurança, dentro das normas | +| Telhado novo | Técnico de telhados | Conhece os materiais, considerações climáticas locais | + +Os agentes funcionam da mesma forma. Em vez de uma IA genérica, use agentes que se concentram em tarefas específicas e conhecem o processo certo a seguir. Configure as instruções uma vez e reutilize sempre que precisar dessa especialidade: revisão de código, testes, segurança, documentação. + +Analogia de Contratar Especialistas - Assim como você chama profissionais especializados para reparos domésticos, os agentes de IA são especializados para tarefas específicas como revisão de código, testes, segurança e documentação + +--- + +# Usando Agentes + +Comece com agentes integrados e personalizados agora mesmo. + +--- + +## *Novo em Agentes?* Comece Aqui! +Nunca usou ou criou um agente? Aqui está tudo que você precisa saber para começar neste curso. + +1. **Experimente um agente *integrado* agora:** + ```bash + copilot + > /plan Add input validation for book year in the book app + ``` + Isso invoca o agente Plan para criar um plano de implementação passo a passo. + +2. **Veja um de nossos exemplos de agente personalizado:** É simples definir as instruções de um agente, veja nosso arquivo [python-reviewer.agent.md](../../../.github/agents/python-reviewer.agent.md) fornecido para ver o padrão. + +3. **Entenda o conceito central:** Agentes são como consultar um especialista em vez de um generalista. Um "agente frontend" se concentrará em acessibilidade e padrões de componentes automaticamente, você não precisa lembrá-lo porque já está especificado nas instruções do agente. + + +## Agentes Integrados + +**Você já usou alguns agentes integrados no Capítulo 03: Fluxos de Trabalho de Desenvolvimento!** +
`/plan` e `/review` são na verdade agentes integrados. Agora você sabe o que está acontecendo por baixo dos panos. Aqui está a lista completa: + +| Agente | Como Invocar | O que Faz | +|--------|-------------|-----------| +| **Plan** | `/plan` ou `Shift+Tab` (alternar modos) | Cria planos de implementação passo a passo antes de codificar | +| **Code-review** | `/review` | Revisa alterações staged/unstaged com feedback focado e acionável | +| **Init** | `/init` | Gera arquivos de configuração do projeto (instruções, agentes) | +| **Explore** | *Automático* | Usado internamente quando você pede ao Copilot para explorar ou analisar a base de código | +| **Task** | *Automático* | Executa comandos como testes, builds, lints e instalações de dependências | + +
+ +**Agentes integrados em ação** - Exemplos de invocação de Plan, Code-review, Explore e Task + +```bash +copilot + +# Invocar o agente Plan para criar um plano de implementação +> /plan Add input validation for book year in the book app + +# Invocar o agente Code-review nas suas alterações +> /review + +# Os agentes Explore e Task são invocados automaticamente quando relevante: +> Run the test suite # Usa o agente Task + +> Explore how book data is loaded # Usa o agente Explore +``` + +E o Agente Task? Ele funciona nos bastidores para gerenciar e rastrear o que está acontecendo e relatar de volta em um formato limpo e claro: + +| Resultado | O que Você Vê | +|-----------|---------------| +| ✅ **Sucesso** | Resumo breve (ex.: "All 247 tests passed", "Build succeeded") | +| ❌ **Falha** | Saída completa com rastreamentos de pilha, erros de compilador e logs detalhados | + + +> 📚 **Documentação oficial**: [Agentes GitHub Copilot CLI](https://docs.github.com/copilot/how-tos/use-copilot-agents/use-copilot-cli#use-custom-agents) + +--- + +# Adicionando Agentes ao Copilot CLI + +Você pode simplesmente definir seus próprios agentes para fazer parte do seu fluxo de trabalho! Defina uma vez, depois dirija! + +Quatro robôs de IA coloridos juntos, cada um com ferramentas diferentes representando capacidades especializadas de agentes + +## 🗂️ Adicione seus agentes + +Os arquivos de agente são arquivos markdown com a extensão `.agent.md`. Eles têm duas partes: frontmatter YAML (metadados) e instruções em markdown. + +> 💡 **Novo em frontmatter YAML?** É um pequeno bloco de configurações no topo do arquivo, cercado por marcadores `---`. YAML são apenas pares `chave: valor`. O resto do arquivo é markdown regular. + +Aqui está um agente mínimo: + +```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 +``` + +> 💡 **Obrigatório vs Opcional**: O campo `description` é obrigatório. Outros campos como `name`, `tools` e `model` são opcionais. + +## Onde colocar os arquivos de agente + +| Local | Escopo | Melhor Para | +|-------|--------|------------| +| `.github/agents/` | Específico do projeto | Agentes compartilhados pela equipe com convenções do projeto | +| `~/.copilot/agents/` | Global (todos os projetos) | Agentes pessoais que você usa em todo lugar | + +**Este projeto inclui arquivos de agente de exemplo na pasta [.github/agents/](../../../.github/agents/)**. Você pode escrever os seus próprios ou personalizar os que já foram fornecidos. + +
+📂 Veja os agentes de exemplo neste curso + +| Arquivo | Descrição | +|---------|-----------| +| `hello-world.agent.md` | Exemplo mínimo - comece aqui | +| `python-reviewer.agent.md` | Revisor de qualidade de código Python | +| `pytest-helper.agent.md` | Especialista em testes com pytest | + +```bash +# Ou copie um para a sua pasta de agentes pessoais (disponível em todos os projetos) +cp .github/agents/python-reviewer.agent.md ~/.copilot/agents/ +``` + +Para mais agentes da comunidade, veja [github/awesome-copilot](https://github.com/github/awesome-copilot) + +
+ + +## 🚀 Duas formas de usar agentes personalizados + +### Modo interativo +No modo interativo, liste os agentes usando `/agent` e selecione o agente com o qual você quer trabalhar. +Selecione um agente para continuar a sua conversa. + +```bash +copilot +> /agent +``` + +Para mudar para um agente diferente, ou para retornar ao modo padrão, use o comando `/agent` novamente. + +### Modo programático + +Lance diretamente para uma nova sessão com um agente. + +```bash +copilot --agent python-reviewer +> Review @samples/book-app-project/books.py +``` + +> 💡 **Trocando agentes**: Você pode mudar para um agente diferente a qualquer momento usando `/agent` ou `--agent` novamente. Para retornar à experiência padrão do Copilot CLI, use `/agent` e selecione **sem agente**. + +--- + +# Indo Mais Fundo com Agentes + +Robô sendo montado numa bancada cercada de componentes e ferramentas representando a criação de agentes personalizados + +> 💡 **Esta seção é opcional.** Os agentes integrados (`/plan`, `/review`) são poderosos o suficiente para a maioria dos fluxos de trabalho. Crie agentes personalizados quando precisar de expertise especializada que seja consistentemente aplicada em todo o seu trabalho. + +Cada tópico abaixo é independente. **Escolha o que lhe interessa - você não precisa ler todos de uma vez.** + +| Quero... | Ir para | +|---|---| +| Ver por que agentes superam prompts genéricos | [Especialista vs Genérico](#specialist-vs-generic-see-the-difference) | +| Combinar agentes em uma funcionalidade | [Trabalhando com Múltiplos Agentes](#working-with-multiple-agents) | +| Organizar, nomear e compartilhar agentes | [Organizando & Compartilhando Agentes](#organizing--sharing-agents) | +| Configurar contexto sempre ativo do projeto | [Configurando Seu Projeto para o Copilot](#configuring-your-project-for-copilot) | +| Consultar propriedades YAML e ferramentas | [Referência de Arquivo de Agente](#agent-file-reference) | + +Selecione um cenário abaixo para expandi-lo. + +--- + + +
+Especialista vs Genérico: Veja a Diferença - Por que agentes produzem saída melhor do que prompts genéricos + +## Especialista vs Genérico: Veja a Diferença + +É aqui que os agentes provam seu valor. Veja a diferença: + +### Sem um Agente (Copilot Genérico) + +```bash +copilot + +> Add a function to search books by year range in the book app +``` + +**Saída genérica**: +```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 +``` + +Básico. Funciona. Mas faltando muita coisa. + +--- + +### Com o Agente de Revisão Python + +```bash +copilot + +> /agent +# Selecione "python-reviewer" + +> Add a function to search books by year range in the book app +``` + +**Saída especializada**: +```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 + ] +``` + +**O que o agente python-reviewer inclui automaticamente**: +- ✅ Dicas de tipo em todos os parâmetros e valores de retorno +- ✅ Docstring abrangente com Args/Returns/Raises +- ✅ Validação de entrada com tratamento de erros adequado +- ✅ Compreensão de lista para melhor performance +- ✅ Tratamento de casos extremos (valores de ano ausentes/inválidos) +- ✅ Formatação conforme PEP 8 +- ✅ Práticas de programação defensiva + +**A diferença**: O mesmo prompt, saída dramaticamente melhor. O agente traz expertise que você esqueceria de solicitar. + +
+ +--- + + +
+Trabalhando com Múltiplos Agentes - Combinar especialistas, alternar no meio da sessão, agentes como ferramentas + +## Trabalhando com Múltiplos Agentes + +O verdadeiro poder vem quando especialistas trabalham juntos em uma funcionalidade. + +### Exemplo: Construindo uma Funcionalidade Simples + +```bash +copilot + +> I want to add a "search by year range" feature to the book app + +# Usar python-reviewer para o design +> /agent +# Selecione "python-reviewer" + +> @samples/book-app-project/books.py Design a find_by_year_range method. What's the best approach? + +# Mudar para pytest-helper para o design dos testes +> /agent +# Selecione "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? + +# Sintetizar ambos os designs +> Create an implementation plan that includes the method implementation and comprehensive tests. +``` + +**O ponto-chave**: Você é o arquiteto dirigindo os especialistas. Eles cuidam dos detalhes, você cuida da visão. + +
+🎬 Veja em ação! + +![Demo do Python Reviewer](../../../04-agents-custom-instructions/images/python-reviewer-demo.gif) + +*A saída da demo pode variar — o seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +### Agentes como Ferramentas + +Quando os agentes estão configurados, o Copilot também pode chamá-los como ferramentas durante tarefas complexas. Se você pede uma funcionalidade full-stack, o Copilot pode delegar automaticamente partes para os agentes especialistas apropriados. + +
+ +--- + + +
+Organizando & Compartilhando Agentes - Nomenclatura, posicionamento de arquivos, arquivos de instruções e compartilhamento com equipe + +## Organizando & Compartilhando Agentes + +### Nomeando Seus Agentes + +Quando você cria arquivos de agente, o nome importa. É o que você digitará após `/agent` ou `--agent`, e o que seus colegas de equipe verão na lista de agentes. + +| ✅ Bons Nomes | ❌ Evite | +|--------------|----------| +| `frontend` | `my-agent` | +| `backend-api` | `agent1` | +| `security-reviewer` | `helper` | +| `react-specialist` | `code` | +| `python-backend` | `assistant` | + +**Convenções de nomenclatura:** +- Use letras minúsculas com hifens: `my-agent-name.agent.md` +- Inclua o domínio: `frontend`, `backend`, `devops`, `security` +- Seja específico quando necessário: `react-typescript` vs apenas `frontend` + +--- + +### Compartilhando com Sua Equipe + +Coloque os arquivos de agente em `.github/agents/` e eles ficam com controle de versão. Faça push para o seu repositório e cada membro da equipe os obtém automaticamente. Mas os agentes são apenas um tipo de arquivo que o Copilot lê do seu projeto. Ele também suporta **arquivos de instruções** que se aplicam automaticamente a cada sessão, sem que ninguém precise executar `/agent`. + +Pense desta forma: agentes são especialistas que você chama, e arquivos de instruções são regras de equipe que estão sempre ativas. + +### Onde Colocar Seus Arquivos + +Você já conhece os dois locais principais (veja [Onde colocar os arquivos de agente](#where-to-put-agent-files) acima). Use esta árvore de decisão para escolher: + +Árvore de decisão para onde colocar arquivos de agente: experimentando → pasta atual, uso pela equipe → .github/agents/, em todo lugar → ~/.copilot/agents/ + +**Comece simples:** Crie um único arquivo `*.agent.md` na sua pasta do projeto. Mova-o para um local permanente quando estiver satisfeito com ele. + +Além dos arquivos de agente, o Copilot também lê **arquivos de instruções de nível de projeto** automaticamente, sem necessidade de `/agent`. Veja [Configurando Seu Projeto para o Copilot](#configuring-your-project-for-copilot) abaixo para `AGENTS.md`, `.instructions.md` e `/init`. + +
+ +--- + + +
+Configurando Seu Projeto para o Copilot - AGENTS.md, arquivos de instruções e configuração /init + +## Configurando Seu Projeto para o Copilot + +Agentes são especialistas que você invoca sob demanda. **Arquivos de configuração do projeto** são diferentes: o Copilot os lê automaticamente em cada sessão para entender as convenções, stack tecnológica e regras do seu projeto. Ninguém precisa executar `/agent`; o contexto está sempre ativo para todos que trabalham no repositório. + +### Configuração Rápida com /init + +A forma mais rápida de começar é deixar o Copilot gerar os arquivos de configuração para você: + +```bash +copilot +> /init +``` + +O Copilot vai analisar seu projeto e criar arquivos de instruções personalizados. Você pode editá-los depois. + +### Formatos de Arquivo de Instruções + +| Arquivo | Escopo | Observações | +|---------|--------|-------------| +| `AGENTS.md` | Raiz do projeto ou aninhado | **Padrão entre plataformas** - funciona com Copilot e outros assistentes de IA | +| `.github/copilot-instructions.md` | Projeto | Específico do GitHub Copilot | +| `.github/instructions/*.instructions.md` | Projeto | Instruções granulares e específicas por tópico | +| `CLAUDE.md`, `GEMINI.md` | Raiz do projeto | Suportados para compatibilidade | + +> 🎯 **Apenas começando?** Use `AGENTS.md` para instruções do projeto. Você pode explorar os outros formatos mais tarde conforme necessário. + +### AGENTS.md + +`AGENTS.md` é o formato recomendado. É um [padrão aberto](https://agents.md/) que funciona no Copilot e em outras ferramentas de codificação com IA. Coloque-o na raiz do seu repositório e o Copilot o lê automaticamente. O próprio [AGENTS.md](../../../AGENTS.md) deste projeto é um exemplo funcional. + +Um `AGENTS.md` típico descreve o contexto do seu projeto, estilo de código, requisitos de segurança e padrões de teste. Escreva o seu seguindo o padrão em nosso arquivo de exemplo. + +### Arquivos de Instruções Personalizadas (.instructions.md) + +Para equipes que querem controle mais granular, divida as instruções em arquivos específicos por tópico. Cada arquivo cobre uma preocupação e se aplica automaticamente: + +``` +.github/ +└── instructions/ + ├── python-standards.instructions.md + ├── security-checklist.instructions.md + └── api-design.instructions.md +``` + +> 💡 **Observação**: Arquivos de instruções funcionam com qualquer linguagem. Este exemplo usa Python para corresponder ao projeto do curso, mas você pode criar arquivos similares para TypeScript, Go, Rust ou qualquer tecnologia que sua equipe usa. + +**Encontrando arquivos de instruções da comunidade**: Navegue em [github/awesome-copilot](https://github.com/github/awesome-copilot) para encontrar arquivos de instruções pré-feitos cobrindo .NET, Angular, Azure, Python, Docker e muitas outras tecnologias. + +### Desabilitando Instruções Personalizadas + +Se você precisar que o Copilot ignore todas as configurações específicas do projeto (útil para depuração ou comparação de comportamento): + +```bash +copilot --no-custom-instructions +``` + +
+ +--- + + +
+Referência de Arquivo de Agente - Propriedades YAML, aliases de ferramentas e exemplos completos + +## Referência de Arquivo de Agente + +### Um Exemplo Mais Completo + +Você já viu o [formato de agente mínimo](#-adicione-seus-agentes) acima. Aqui está um agente mais completo que usa a propriedade `tools`. Crie `~/.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 +``` + +### Propriedades YAML + +| Propriedade | Obrigatório | Descrição | +|-------------|-------------|-----------| +| `name` | Não | Nome de exibição (padrão é o nome do arquivo) | +| `description` | **Sim** | O que o agente faz - ajuda o Copilot a entender quando sugeri-lo | +| `tools` | Não | Lista de ferramentas permitidas (omitir = todas as ferramentas disponíveis). Veja aliases de ferramentas abaixo. | +| `target` | Não | Limitar apenas a `vscode` ou `github-copilot` | + +### Aliases de Ferramentas + +Use esses nomes na lista `tools`: +- `read` - Ler conteúdo de arquivo +- `edit` - Editar arquivos +- `search` - Pesquisar arquivos (grep/glob) +- `execute` - Executar comandos shell (também: `shell`, `Bash`) +- `agent` - Invocar outros agentes personalizados + +> 📖 **Documentação oficial**: [Configuração de agentes personalizados](https://docs.github.com/copilot/reference/custom-agents-configuration) +> +> ⚠️ **Somente VS Code**: A propriedade `model` (para selecionar modelos de IA) funciona no VS Code mas não é suportada no GitHub Copilot CLI. Você pode incluí-la com segurança em arquivos de agente multiplataforma. O GitHub Copilot CLI a ignorará. + +### Mais Templates de Agente + +> 💡 **Nota para iniciantes**: Os exemplos abaixo são templates. **Substitua as tecnologias específicas pelo que seu projeto usa.** O importante é a *estrutura* do agente, não as tecnologias específicas mencionadas. + +Este projeto inclui exemplos funcionais na pasta [.github/agents/](../../../.github/agents/): +- [hello-world.agent.md](../../../.github/agents/hello-world.agent.md) - Exemplo mínimo, comece aqui +- [python-reviewer.agent.md](../../../.github/agents/python-reviewer.agent.md) - Revisor de qualidade de código Python +- [pytest-helper.agent.md](../../../.github/agents/pytest-helper.agent.md) - Especialista em testes com pytest + +Para agentes da comunidade, veja [github/awesome-copilot](https://github.com/github/awesome-copilot). + +
+ +--- + +# Prática + +Mesa de trabalho aconchegante com monitor mostrando código, abajur, xícara de café e fones de ouvido prontos para a prática + +Crie seus próprios agentes e veja-os em ação. + +--- + +## ▶️ Experimente Você Mesmo + +```bash + +# Criar o diretório de agentes (se não existir) +mkdir -p .github/agents + +# Criar um agente revisor de código +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 + +# Criar um agente de documentação +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 + +# Agora use-os +copilot --agent reviewer +> Review @samples/book-app-project/books.py + +# Ou troque de agente +copilot +> /agent +# Selecione "documentor" +> Document @samples/book-app-project/books.py +``` + +--- + +## 📝 Atividade + +### Desafio Principal: Construir uma Equipe de Agentes Especializados + +O exemplo prático criou os agentes `reviewer` e `documentor`. Agora pratique criando e usando agentes para uma tarefa diferente - melhorar a validação de dados no aplicativo de livros: + +1. Crie 3 arquivos de agente (`.agent.md`) personalizados para o aplicativo de livros, um por agente, colocados em `.github/agents/` +2. Seus agentes: + - **data-validator**: verifica `data.json` para dados ausentes ou malformados (autores vazios, ano=0, campos ausentes) + - **error-handler**: revisa código Python para tratamento de erros inconsistente e sugere uma abordagem unificada + - **doc-writer**: gera ou atualiza docstrings e conteúdo README +3. Use cada agente no aplicativo de livros: + - `data-validator` → auditar `@samples/book-app-project/data.json` + - `error-handler` → revisar `@samples/book-app-project/books.py` e `@samples/book-app-project/utils.py` + - `doc-writer` → adicionar docstrings a `@samples/book-app-project/books.py` +4. Colabore: use `error-handler` para identificar lacunas no tratamento de erros, depois `doc-writer` para documentar a abordagem melhorada + +**Critérios de sucesso**: Você tem 3 agentes funcionando que produzem saída consistente e de alta qualidade e você pode alternar entre eles com `/agent`. + +
+💡 Dicas (clique para expandir) + +**Templates iniciais**: crie um arquivo por agente em `.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 +``` + +**Testando seus agentes:** + +> 💡 **Observação:** Você já deve ter `samples/book-app-project/data.json` na sua cópia local deste repositório. Se estiver faltando, baixe a versão original do repositório fonte: +> [data.json](https://github.com/github/copilot-cli-for-beginners/blob/main/samples/book-app-project/data.json) + +```bash +copilot +> /agent +# Selecione "data-validator" da lista +> @samples/book-app-project/data.json Check for books with empty author fields or invalid years +``` + +**Dica:** O campo `description` no frontmatter YAML é obrigatório para os agentes funcionarem. + +
+ +### Desafio Bônus: Biblioteca de Instruções + +Você construiu agentes que invoca sob demanda. Agora experimente o outro lado: **arquivos de instruções** que o Copilot lê automaticamente em cada sessão, sem necessidade de `/agent`. + +Crie uma pasta `.github/instructions/` com pelo menos 3 arquivos de instruções: +- `python-style.instructions.md` para aplicar convenções PEP 8 e dicas de tipo +- `test-standards.instructions.md` para aplicar convenções pytest em arquivos de teste +- `data-quality.instructions.md` para validar entradas de dados JSON + +Teste cada arquivo de instruções no código do aplicativo de livros. + +--- + +
+🔧 Erros Comuns e Solução de Problemas (clique para expandir) + +### Erros Comuns + +| Erro | O que Acontece | Solução | +|------|----------------|---------| +| Falta `description` no frontmatter do agente | O agente não vai carregar ou não será descoberto | Sempre inclua `description:` no frontmatter YAML | +| Local errado para arquivos de agente | Agente não encontrado quando você tenta usá-lo | Coloque em `~/.copilot/agents/` (pessoal) ou `.github/agents/` (projeto) | +| Usar `.md` em vez de `.agent.md` | Arquivo pode não ser reconhecido como agente | Nomeie arquivos como `python-reviewer.agent.md` | +| Prompts de agente excessivamente longos | Pode atingir o limite de 30.000 caracteres | Mantenha as definições de agente focadas; use skills para instruções detalhadas | + +### Solução de Problemas + +**Agente não encontrado** - Verifique se o arquivo de agente existe em um destes locais: +- `~/.copilot/agents/` +- `.github/agents/` + +Liste os agentes disponíveis: + +```bash +copilot +> /agent +# Mostra todos os agentes disponíveis +``` + +**Agente não seguindo as instruções** - Seja explícito nos seus prompts e adicione mais detalhes às definições dos agentes: +- Frameworks/bibliotecas específicos com versões +- Convenções da equipe +- Padrões de código de exemplo + +**Instruções personalizadas não carregando** - Execute `/init` no seu projeto para configurar instruções específicas do projeto: + +```bash +copilot +> /init +``` + +Ou verifique se estão desabilitadas: +```bash +# Não use --no-custom-instructions se você quiser que sejam carregadas +copilot # Isso carrega instruções personalizadas por padrão +``` + +
+ +--- + +# Resumo + +## 🔑 Principais Aprendizados + +1. **Agentes integrados**: `/plan` e `/review` são invocados diretamente; Explore e Task funcionam automaticamente +2. **Agentes personalizados** são especialistas definidos em arquivos `.agent.md` +3. **Bons agentes** têm expertise clara, padrões e formatos de saída +4. **Colaboração entre múltiplos agentes** resolve problemas complexos combinando expertise +5. **Arquivos de instruções** (`.instructions.md`) codificam padrões de equipe para aplicação automática +6. **Saída consistente** vem de instruções de agente bem definidas + +> 📋 **Referência rápida**: Veja a [referência de comandos do GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para uma lista completa de comandos e atalhos. + +--- + +## ➡️ O Que Vem a Seguir + +Agentes mudam *como o Copilot aborda e toma ações direcionadas* no seu código. A seguir, você aprenderá sobre **skills** - que mudam *quais etapas* ele segue. Quer saber como agentes e skills diferem? O Capítulo 05 aborda isso diretamente. + +No **[Capítulo 05: Sistema de Skills](../05-skills/README.md)**, você aprenderá: + +- Como as skills são acionadas automaticamente pelos seus prompts (sem slash command necessário) +- Instalar skills da comunidade +- Criar skills personalizadas com arquivos SKILL.md +- A diferença entre agentes, skills e MCP +- Quando usar cada um + +--- + +**[← Voltar ao Capítulo 03](../03-development-workflows/README.md)** | **[Continuar para o Capítulo 05 →](../05-skills/README.md)** diff --git a/localization/pt-br/05-skills/README.md b/localization/pt-br/05-skills/README.md new file mode 100644 index 00000000..d328d218 --- /dev/null +++ b/localization/pt-br/05-skills/README.md @@ -0,0 +1,886 @@ +![Capítulo 05: Sistema de Skills](../../../05-skills/images/chapter-header.png) + +> **E se o Copilot pudesse aplicar automaticamente as melhores práticas da sua equipe sem que você precise explicá-las toda vez?** + +Neste capítulo, você aprenderá sobre Skills de Agente: pastas de instruções que o Copilot carrega automaticamente quando relevantes para a sua tarefa. Enquanto os agentes mudam *como* o Copilot pensa, as skills ensinam ao Copilot *formas específicas de concluir tarefas*. Você criará uma skill de auditoria de segurança que o Copilot aplica sempre que você perguntar sobre segurança, construirá critérios de revisão padrão da equipe que garantem qualidade de código consistente e aprenderá como as skills funcionam no Copilot CLI, VS Code e no agente de nuvem do GitHub Copilot. + + +## 🎯 Objetivos de aprendizado + +Ao final deste capítulo, você será capaz de: + +- Entender como as Skills de Agente funcionam e quando usá-las +- Criar skills personalizadas com arquivos SKILL.md +- Usar skills da comunidade de repositórios compartilhados +- Saber quando usar skills vs agentes vs MCP + +> ⏱️ **Tempo estimado**: ~55 minutos (20 min de leitura + 35 min de prática) + +--- + +## 🧩 Analogia com o Mundo Real: Ferramentas Elétricas + +Uma furadeira de uso geral é útil, mas os acessórios especializados a tornam poderosa. +Ferramentas Elétricas - Skills Ampliam as Capacidades do Copilot + + +As skills funcionam da mesma forma. Assim como você troca brocas para diferentes trabalhos, você pode adicionar skills ao Copilot para diferentes tarefas: + +| Acessório de Skill | Finalidade | +|------------|---------| +| `commit` | Gerar mensagens de commit consistentes | +| `security-audit` | Verificar vulnerabilidades OWASP | +| `generate-tests` | Criar testes pytest abrangentes | +| `code-checklist` | Aplicar padrões de qualidade de código da equipe | + + + +*Skills são acessórios especializados que ampliam o que o Copilot pode fazer* + +--- + +# Como as Skills Funcionam + +Ícones de skill estilo RPG brilhantes conectados por trilhas de luz em um fundo estrelado representando skills do Copilot + +Aprenda o que são skills, por que são importantes e como diferem de agentes e MCP. + +--- + +## *Novo em Skills?* Comece Aqui! + +1. **Veja quais skills já estão disponíveis:** + ```bash + copilot + > /skills list + ``` + Isso mostra todas as skills que o Copilot consegue encontrar, incluindo quaisquer **skills integradas** que vêm com o próprio CLI, além de skills das suas pastas do projeto e pessoais. + + > 💡 **Skills integradas**: O Copilot CLI vem com skills pré-instaladas. Por exemplo, a skill `customizing-copilot-cloud-agents-environment` fornece um guia para personalizar o ambiente do agente de nuvem do Copilot. Você não precisa criar ou instalar nada para usá-las. Execute `/skills list` para ver o que está disponível. + +2. **Veja um arquivo de skill real:** Confira nosso [SKILL.md do code-checklist](../../../.github/skills/code-checklist/SKILL.md) fornecido para ver o padrão. É apenas frontmatter YAML mais instruções em markdown. + +3. **Entenda o conceito central:** Skills são instruções específicas de tarefa que o Copilot carrega *automaticamente* quando o seu prompt corresponde à descrição da skill. Você não precisa ativá-las, basta perguntar naturalmente. + + +## Entendendo as Skills + +Skills de Agente são pastas contendo instruções, scripts e recursos que o Copilot **carrega automaticamente quando relevante** para a sua tarefa. O Copilot lê o seu prompt, verifica se alguma skill corresponde e aplica as instruções relevantes automaticamente. + +```bash +copilot + +> Check books.py against our quality checklist +# O Copilot detecta que isso corresponde à sua skill "code-checklist" +# e aplica automaticamente o checklist de qualidade Python + +> Generate tests for the BookCollection class +# O Copilot carrega a sua skill "pytest-gen" +# e aplica a estrutura de teste preferida + +> What are the code quality issues in this file? +# O Copilot carrega a sua skill "code-checklist" +# e verifica de acordo com os padrões da sua equipe +``` + +> 💡 **Insight Chave**: As skills são **acionadas automaticamente** com base no seu prompt correspondendo à descrição da skill. Basta perguntar naturalmente e o Copilot aplica as skills relevantes nos bastidores. Você também pode invocar skills diretamente, o que você aprenderá a seguir. + +> 🧰 **Templates prontos para usar**: Confira a pasta [.github/skills](../../../.github/skills/) para skills simples de copiar e colar que você pode experimentar. + +### Invocação Direta por Slash Command + +Embora o acionamento automático seja a forma principal como as skills funcionam, você também pode **invocar skills diretamente** usando o nome delas como um slash command: + +```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 +``` + +Isso lhe dá controle explícito quando você quer garantir que uma skill específica seja usada. + +#### Combinando Múltiplas Skills em Uma Mensagem + +Você pode invocar **mais de uma skill em uma única mensagem**, e o slash command da skill pode aparecer em qualquer lugar no seu prompt — não apenas no início. Isso é útil quando você quer dois tipos diferentes de verificação em uma única vez: + +```bash +> Check @samples/book-app-project/book_app.py with /code-checklist and also run /generate-tests for it + +> Review the auth module /security-audit then /code-checklist the result +``` + +O Copilot aplicará cada skill nomeada na mesma resposta, poupando você de enviar múltiplas mensagens separadas. + +> 💡 **Dica**: Coloque os slash commands de skill onde eles se encaixarem mais naturalmente na sua frase. Você pode colocá-los no início, meio ou fim da sua mensagem. + +> 📝 **Invocação de Skills vs Agentes**: Não confunda a invocação de skill com a invocação de agente: +> - **Skills**: `/nome-da-skill `, ex.: `/code-checklist Check this file` +> - **Agentes**: `/agent` (selecionar da lista) ou `copilot --agent ` (linha de comando) +> +> Se você tiver uma skill e um agente com o mesmo nome (ex.: "code-reviewer"), digitar `/code-reviewer` invoca a **skill**, não o agente. + +### Como Sei que uma Skill Foi Usada? + +Você pode perguntar diretamente ao Copilot: + +```bash +> What skills did you use for that response? + +> What skills do you have available for security reviews? +``` + +### Skills vs Agentes vs MCP + +Skills são apenas uma peça do modelo de extensibilidade do GitHub Copilot. Veja como elas se comparam a agentes e servidores MCP. + +> *Não se preocupe com MCP ainda. Vamos abordá-lo no [Capítulo 06](../06-mcp-servers/README.md). Está incluído aqui para que você possa ver como as skills se encaixam na visão geral.* + +Diagrama de comparação mostrando as diferenças entre Agentes, Skills e Servidores MCP e como eles se combinam no seu fluxo de trabalho + +| Recurso | O que Faz | Quando Usar | +|---------|-----------|-------------| +| **Agentes** | Muda como a IA pensa | Precisa de expertise especializada em muitas tarefas | +| **Skills** | Fornece instruções específicas de tarefa | Tarefas específicas e repetíveis com etapas detalhadas | +| **MCP** | Conecta serviços externos | Precisa de dados ao vivo de APIs | + +Use agentes para expertise ampla, skills para instruções específicas de tarefa e MCP para dados externos. Um agente pode usar uma ou mais skills durante uma conversa. Por exemplo, quando você pede a um agente para verificar o seu código, ele pode aplicar tanto uma skill `security-audit` quanto uma skill `code-checklist` automaticamente. + +> 📚 **Saiba Mais**: Veja a documentação oficial [Sobre Skills de Agente](https://docs.github.com/copilot/concepts/agents/about-agent-skills) para a referência completa sobre formatos de skill e melhores práticas. + +--- + +## De Prompts Manuais a Expertise Automática + +Antes de mergulhar em como criar skills, vamos ver *por que* vale a pena aprendê-las. Uma vez que você veja os ganhos de consistência, o "como" fará mais sentido. + +### Antes das Skills: Revisões Inconsistentes + +Em cada revisão de código, você pode esquecer algo: + +```bash +copilot + +> Review this code for issues +# Revisão genérica - pode perder as preocupações específicas da sua equipe +``` + +Ou você escreve um prompt longo toda vez: + +```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... +``` + +Tempo: **30+ segundos** para digitar. Consistência: **varia com a memória**. + +### Depois das Skills: Melhores Práticas Automáticas + +Com uma skill `code-checklist` instalada, basta perguntar naturalmente: + +```bash +copilot + +> Check the book collection code for quality issues +``` + +**O que acontece nos bastidores**: +1. O Copilot vê "qualidade de código" e "problemas" no seu prompt +2. Verifica as descrições das skills, encontra que a sua skill `code-checklist` corresponde +3. Carrega automaticamente o checklist de qualidade da sua equipe +4. Aplica todas as verificações sem você listá-las + +Como as Skills São Acionadas Automaticamente - Fluxo de 4 etapas mostrando como o Copilot corresponde automaticamente o seu prompt à skill certa + +*Basta perguntar naturalmente. O Copilot corresponde o seu prompt à skill certa e a aplica automaticamente.* + +**Saída**: +``` +## 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 +``` + +**A diferença**: Os padrões da sua equipe são aplicados automaticamente, toda vez, sem precisar digitá-los. + +--- + +
+🎬 Veja em ação! + +![Demo de Acionamento de Skill](../../../05-skills/images/skill-trigger-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +## Consistência em Escala: Skill de Revisão de PR da Equipe + +Imagine que a sua equipe tem um checklist de 10 pontos para PRs. Sem uma skill, cada desenvolvedor deve lembrar todos os 10 pontos, e alguém sempre esquece um deles. Com uma skill `pr-review`, toda a equipe recebe revisões consistentes: + +```bash +copilot + +> Can you review this PR? +``` + +O Copilot carrega automaticamente a skill `pr-review` da sua equipe e verifica todos os 10 pontos: + +``` +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 +``` + +**O poder**: Todo membro da equipe aplica os mesmos padrões automaticamente. Novos integrantes não precisam memorizar o checklist porque a skill cuida disso. + +--- + +# Criando Skills Personalizadas + +Mãos humanas e robóticas construindo uma parede de blocos LEGO brilhantes representando a criação e gerenciamento de skills + +Construa suas próprias skills a partir de arquivos SKILL.md. + +--- + +## Locais das Skills + +As skills são armazenadas em `.github/skills/` (específicas do projeto) ou `~/.copilot/skills/` (nível do usuário). + +### Como o Copilot Encontra as Skills + +O Copilot verifica automaticamente esses locais para encontrar skills: + +| Local | Escopo | +|-------|--------| +| `.github/skills/` | Específico do projeto (compartilhado com a equipe via git) | +| `~/.copilot/skills/` | Específico do usuário (suas skills pessoais) | + +### Estrutura da Skill + +Cada skill fica em sua própria pasta com um arquivo `SKILL.md`. Você pode opcionalmente incluir scripts, exemplos ou outros recursos: + +``` +.github/skills/ +└── my-skill/ + ├── SKILL.md # Obrigatório: Definição e instruções da skill + ├── examples/ # Opcional: Arquivos de exemplo que o Copilot pode referenciar + │ └── sample.py + └── scripts/ # Opcional: Scripts que a skill pode usar + └── validate.sh +``` + +> 💡 **Dica**: O nome do diretório deve corresponder ao `name` no frontmatter do seu SKILL.md (letras minúsculas com hifens). + +### Formato do SKILL.md + +As skills usam um formato markdown simples com frontmatter YAML: + +```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 +``` + +**Propriedades YAML:** + +| Propriedade | Obrigatório | Descrição | +|-------------|-------------|-----------| +| `name` | **Sim** | Identificador único (letras minúsculas, hifens no lugar de espaços) | +| `description` | **Sim** | O que a skill faz e quando o Copilot deve usá-la | +| `license` | Não | Licença que se aplica a esta skill | + +> 📖 **Documentação oficial**: [Sobre Skills de Agente](https://docs.github.com/copilot/concepts/agents/about-agent-skills) + +### Criando Sua Primeira Skill + +Vamos construir uma skill de auditoria de segurança que verifica vulnerabilidades OWASP Top 10: + +```bash +# Criar o diretório da skill +mkdir -p .github/skills/security-audit + +# Criar o arquivo 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 + +# Testar a sua skill (skills carregam automaticamente com base no seu prompt) +copilot + +> @samples/book-app-project/ Check this code for security vulnerabilities +# O Copilot detecta "vulnerabilidades de segurança" correspondendo à sua skill +# e aplica automaticamente o checklist OWASP +``` + +**Saída esperada** (seus resultados variarão): + +``` +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 +``` + +--- + +## Escrevendo Boas Descrições de Skill + +O campo `description` no seu SKILL.md é crucial! É como o Copilot decide se vai carregar a sua skill: + +```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 +--- +``` + +> 💡 **Dica**: Inclua palavras-chave que correspondam à forma como você faz perguntas naturalmente. Se você diz "revisão de segurança", inclua "revisão de segurança" na descrição. + +### Combinando Skills com Agentes + +Skills e agentes trabalham juntos. O agente fornece expertise, a skill fornece instruções específicas: + +```bash +# Iniciar com um agente code-reviewer +copilot --agent code-reviewer + +> Check the book app for quality issues +# a expertise do agente code-reviewer se combina +# com o checklist da sua skill code-checklist +``` + +--- + +# Gerenciando e Compartilhando Skills + +Descubra skills instaladas, encontre skills da comunidade e compartilhe as suas. + +Gerenciando e Compartilhando Skills - mostrando o ciclo de descobrir, usar, criar e compartilhar skills do CLI + +--- + +## Gerenciando Skills com o Comando `/skills` + +Use o comando `/skills` para gerenciar as suas skills instaladas: + +| Comando | O que Faz | +|---------|-----------| +| `/skills list` | Mostrar todas as skills instaladas | +| `/skills info ` | Obter detalhes sobre uma skill específica | +| `/skills add ` | Habilitar uma skill (de um repositório ou marketplace) | +| `/skills remove ` | Desabilitar ou desinstalar uma skill | +| `/skills reload` | Recarregar skills após editar arquivos SKILL.md | + +> 💡 **Lembre-se**: Você não precisa "ativar" skills para cada prompt. Uma vez instaladas, as skills são **acionadas automaticamente** quando o seu prompt corresponde à descrição delas. Esses comandos são para gerenciar quais skills estão disponíveis, não para usá-las. + +### Exemplo: Ver Suas Skills + +```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 +``` + +--- + +
+Veja em ação! + +![Demo de Lista de Skills](../../../05-skills/images/list-skills-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +### Quando Usar `/skills reload` + +Após criar ou editar o arquivo SKILL.md de uma skill, execute `/skills reload` para capturar as alterações sem reiniciar o Copilot: + +```bash +# Edite o arquivo da sua skill +# Então no Copilot: +> /skills reload +Skills reloaded successfully. +``` + +> 💡 **Bom saber**: As skills permanecem eficazes mesmo após usar `/compact` para resumir o histórico de conversas. Não é necessário recarregar após compactar. + +--- + +## Encontrando e Usando Skills da Comunidade + +### Usando Plugins para Instalar Skills + +> 💡 **O que são plugins?** Plugins são pacotes instaláveis que podem agrupar skills, agentes e configurações de servidor MCP juntos. Pense neles como extensões de "loja de aplicativos" para o Copilot CLI. + +O comando `/plugin` permite que você navegue e instale esses pacotes: + +```bash +copilot + +> /plugin list +# Mostra plugins instalados + +> /plugin marketplace +# Navegar pelos plugins disponíveis + +> /plugin install +# Instalar um plugin do marketplace +``` + +Para manter o catálogo de plugins local atualizado, atualize-o com: + +```bash +copilot plugin marketplace update +``` + +Plugins podem agrupar múltiplas capacidades juntas. Um único plugin pode incluir skills relacionadas, agentes e configurações de servidor MCP que trabalham juntos. + +### Repositórios de Skills da Comunidade + +Skills pré-prontas também estão disponíveis em repositórios da comunidade: + +- **[Awesome Copilot](https://github.com/github/awesome-copilot)** - Recursos oficiais do GitHub Copilot incluindo documentação e exemplos de skills + +### Instalando uma Skill da Comunidade com o GitHub CLI + +A forma mais fácil de instalar uma skill de um repositório GitHub é usar o comando `gh skill install` (requer [GitHub CLI v2.90.0+](https://github.blog/changelog/2026-04-16-manage-agent-skills-with-github-cli/)): + +```bash +# Navegar e selecionar interativamente uma skill do awesome-copilot +gh skill install github/awesome-copilot + +# Ou instalar uma skill específica diretamente +gh skill install github/awesome-copilot code-checklist + +# Instalar para uso pessoal em todos os projetos (escopo de usuário) +gh skill install github/awesome-copilot code-checklist --scope user +``` + +> ⚠️ **Revise antes de instalar**: Sempre leia o `SKILL.md` de uma skill antes de instalá-la. As skills controlam o que o Copilot faz, e uma skill maliciosa poderia instruí-lo a executar comandos prejudiciais ou modificar código de formas inesperadas. + +--- + +# Prática + +Mesa de trabalho aconchegante com monitor mostrando código, abajur, xícara de café e fones de ouvido prontos para a prática + +Aplique o que aprendeu construindo e testando suas próprias skills. + +--- + +## ▶️ Experimente Você Mesmo + +### Construir Mais Skills + +Aqui estão duas skills mostrando padrões diferentes. Siga o mesmo fluxo de trabalho `mkdir` + `cat` de "Criando Sua Primeira Skill" acima ou copie e cole as skills no local adequado. Mais exemplos estão disponíveis em [.github/skills](../../../.github/skills). + +### Skill de Geração de Testes pytest + +Uma skill que garante estrutura pytest consistente em toda a sua base de código: + +```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 +``` + +### Skill de Revisão de PR da Equipe + +Uma skill que aplica padrões consistentes de revisão de PR em toda a sua equipe: + +```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 +``` + +### Indo Além + +1. **Desafio de Criação de Skill**: Crie uma skill `quick-review` que faz um checklist de 3 pontos: + - Cláusulas bare except + - Dicas de tipo ausentes + - Nomes de variáveis pouco claros + + Teste perguntando: "Do a quick review of books.py" + +2. **Comparação de Skills**: Cronômetro enquanto escreve um prompt detalhado de revisão de segurança manualmente. Depois apenas pergunte "Check for security issues in this file" e deixe a sua skill security-audit carregar automaticamente. Quanto tempo a skill economizou? + +3. **Desafio de Skill da Equipe**: Pense no checklist de revisão de código da sua equipe. Você poderia codificá-lo como uma skill? Anote 3 coisas que a skill deve sempre verificar. + +**Autoavaliação**: Você entende as skills quando consegue explicar por que o campo `description` é importante (é como o Copilot decide se deve carregar a sua skill). + +--- + +## 📝 Atividade + +### Desafio Principal: Construir uma Skill de Resumo de Livros + +Os exemplos acima criaram skills `pytest-gen` e `pr-review`. Agora pratique criando um tipo completamente diferente de skill: uma para gerar saída formatada a partir de dados. + +1. Liste suas skills atuais: Execute o Copilot e passe `/skills list`. Você também pode usar `ls .github/skills/` para ver as skills do projeto ou `ls ~/.copilot/skills/` para skills pessoais. +2. Crie uma skill `book-summary` em `.github/skills/book-summary/SKILL.md` que gera um resumo markdown formatado da coleção de livros +3. Sua skill deve ter: + - Nome e descrição claros (a descrição é crucial para a correspondência!) + - Regras de formatação específicas (ex.: tabela markdown com título, autor, ano, status de leitura) + - Convenções de saída (ex.: use ✅/❌ para status de leitura, ordenar por ano) +4. Teste a skill: `@samples/book-app-project/data.json Summarize the books in this collection` +5. Verifique se a skill é acionada automaticamente verificando `/skills list` +6. Tente invocá-la diretamente com `/book-summary Summarize the books in this collection` + +**Critérios de sucesso**: Você tem uma skill `book-summary` funcionando que o Copilot aplica automaticamente quando você pergunta sobre a coleção de livros. + +
+💡 Dicas (clique para expandir) + +**Template inicial**: Crie `.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)** +``` + +**Teste:** +```bash +copilot +> @samples/book-app-project/data.json Summarize the books in this collection +# A skill deve ser acionada automaticamente com base na correspondência da descrição +``` + +**Se não acionar:** Tente `/skills reload` e pergunte novamente. + +
+ +### Desafio Bônus: Skill de Mensagem de Commit + +1. Crie uma skill `commit-message` que gera mensagens de commit convencionais com um formato consistente +2. Teste fazendo stage de uma alteração e perguntando: "Generate a commit message for my staged changes" +3. Documente a sua skill e compartilhe-a no GitHub com o tópico `copilot-skill` + +--- + +
+🔧 Erros Comuns e Solução de Problemas (clique para expandir) + +### Erros Comuns + +| Erro | O que Acontece | Solução | +|------|----------------|---------| +| Nomear o arquivo com algo diferente de `SKILL.md` | A skill não será reconhecida | O arquivo deve ser nomeado exatamente `SKILL.md` | +| Campo `description` vago | A skill nunca é carregada automaticamente | A descrição é o mecanismo PRINCIPAL de descoberta. Use palavras-chave específicas de gatilho | +| `name` ou `description` ausentes no frontmatter | A skill falha ao carregar | Adicione ambos os campos no frontmatter YAML | +| Local da pasta errado | Skill não encontrada | Use `.github/skills/nome-da-skill/` (projeto) ou `~/.copilot/skills/nome-da-skill/` (pessoal) | + +### Solução de Problemas + +**Skill não sendo usada** - Se o Copilot não está usando a sua skill quando esperado: + +1. **Verifique a descrição**: Ela corresponde à forma como você está perguntando? + ```markdown + # Ruim: Muito vago + description: Reviews code + + # Bom: Inclui palavras-chave de gatilho + description: Use for code reviews, checking code quality, + finding bugs, security issues, and best practice violations + ``` + +2. **Verifique o local do arquivo**: + ```bash + # Skills do projeto + ls .github/skills/ + + # Skills do usuário + ls ~/.copilot/skills/ + ``` + +3. **Verifique o formato do SKILL.md**: O frontmatter é obrigatório: + ```markdown + --- + name: skill-name + description: What the skill does and when to use it + --- + + # Instructions here + ``` + +**Skill não aparecendo** - Verifique a estrutura de pastas: +``` +.github/skills/ +└── my-skill/ # Nome da pasta + └── SKILL.md # Deve ser exatamente SKILL.md (sensível a maiúsculas) +``` + +Execute `/skills reload` após criar ou editar skills para garantir que as alterações sejam capturadas. + +**Testando se uma skill carrega** - Pergunte diretamente ao Copilot: +```bash +> What skills do you have available for checking code quality? +# O Copilot descreverá as skills relevantes que encontrou +``` + +**Como sei que minha skill está realmente funcionando?** + +1. **Verifique o formato de saída**: Se a sua skill especifica um formato de saída (como tags `[CRITICAL]`), procure por isso na resposta +2. **Pergunte diretamente**: Após obter uma resposta, pergunte "Did you use any skills for that?" +3. **Compare com/sem**: Tente o mesmo prompt com `--no-custom-instructions` para ver a diferença: + ```bash + # Com skills + copilot --allow-all -p "Review @file.py for security issues" + + # Sem skills (comparação de referência) + copilot --allow-all -p "Review @file.py for security issues" --no-custom-instructions + ``` +4. **Verifique verificações específicas**: Se a sua skill inclui verificações específicas (como "funções com mais de 50 linhas"), veja se essas aparecem na saída + +
+ +--- + +# Resumo + +## 🔑 Principais Aprendizados + +1. **Skills são automáticas**: O Copilot as carrega quando o seu prompt corresponde à descrição da skill +2. **Invocação direta**: Você também pode invocar skills diretamente com `/nome-da-skill` como um slash command +3. **Formato SKILL.md**: Frontmatter YAML (name, description, license opcional) mais instruções em markdown +4. **A localização importa**: `.github/skills/` para compartilhamento no projeto/equipe, `~/.copilot/skills/` para uso pessoal +5. **A descrição é fundamental**: Escreva descrições que correspondam à forma como você faz perguntas naturalmente + +> 📋 **Referência rápida**: Veja a [referência de comandos do GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para uma lista completa de comandos e atalhos. + +--- + +## ➡️ O Que Vem a Seguir + +Skills ampliam o que o Copilot pode fazer com instruções carregadas automaticamente. Mas e quanto a se conectar a serviços externos? É aí que entra o MCP. + +No **[Capítulo 06: Servidores MCP](../06-mcp-servers/README.md)**, você aprenderá: + +- O que é MCP (Model Context Protocol) +- Conectar ao GitHub, sistema de arquivos e serviços de documentação +- Configurar servidores MCP +- Fluxos de trabalho com múltiplos servidores + +--- + +**[← Voltar ao Capítulo 04](../04-agents-custom-instructions/README.md)** | **[Continuar para o Capítulo 06 →](../06-mcp-servers/README.md)** diff --git a/localization/pt-br/06-mcp-servers/README.md b/localization/pt-br/06-mcp-servers/README.md new file mode 100644 index 00000000..420cd815 --- /dev/null +++ b/localization/pt-br/06-mcp-servers/README.md @@ -0,0 +1,974 @@ +![Capítulo 06: Servidores MCP](../../../06-mcp-servers/images/chapter-header.png) + +> **E se o Copilot pudesse ler seus issues do GitHub, verificar seu banco de dados e criar PRs... tudo pelo terminal?** + +Até agora, o Copilot só pode trabalhar com o que você lhe dá diretamente: arquivos que você referencia com `@`, histórico de conversas e seus próprios dados de treinamento. Mas e se ele pudesse acessar por conta própria o seu repositório do GitHub, navegar pelos arquivos do projeto ou buscar a documentação mais recente de uma biblioteca? + +É isso que o MCP (Model Context Protocol) faz. É uma forma de conectar o Copilot a serviços externos para que ele tenha acesso a dados ao vivo do mundo real. Cada serviço ao qual o Copilot se conecta é chamado de "servidor MCP". Neste capítulo, você configurará algumas dessas conexões e verá como elas tornam o Copilot dramaticamente mais útil. + +> 💡 **Já familiarizado com MCP?** [Vá direto para o início rápido](#-use-the-built-in-github-mcp) para confirmar que está funcionando e comece a configurar servidores. + +## 🎯 Objetivos de aprendizado + +Ao final deste capítulo, você será capaz de: + +- Entender o que é MCP e por que é importante +- Gerenciar servidores MCP usando comandos `/mcp` +- Configurar servidores MCP para GitHub, sistema de arquivos e documentação +- Usar fluxos de trabalho com MCP no projeto do aplicativo de livros +- Saber quando e como construir um servidor MCP personalizado (opcional) + +> ⏱️ **Tempo estimado**: ~50 minutos (15 min de leitura + 35 min de prática) + +--- + +## 🧩 Analogia com o Mundo Real: Extensões de Navegador + +Servidores MCP são como Extensões de Navegador + +Pense nos servidores MCP como extensões de navegador. Seu navegador por si só pode exibir páginas web, mas as extensões o conectam a serviços extras: + +| Extensão de Navegador | Com o que se Conecta | Equivalente MCP | +|----------------------|---------------------|-----------------| +| Gerenciador de senhas | Seu cofre de senhas | **GitHub MCP** → seus repositórios, issues, PRs | +| Grammarly | Serviço de análise de escrita | **Context7 MCP** → documentação de bibliotecas | +| Gerenciador de arquivos | Armazenamento na nuvem | **Filesystem MCP** → arquivos do projeto local | + +Sem extensões, seu navegador ainda é útil, mas com elas ele se torna uma ferramenta poderosa. Os servidores MCP fazem o mesmo pelo Copilot. Eles o conectam a fontes de dados reais e ao vivo para que ele possa ler seus issues do GitHub, explorar seu sistema de arquivos, buscar documentação atualizada e muito mais. + +***Servidores MCP conectam o Copilot ao mundo externo: GitHub, repositórios, documentação e mais*** + +> 💡 **Insight chave**: Sem MCP, o Copilot só consegue ver arquivos que você compartilha explicitamente com `@`. Com MCP, ele pode explorar proativamente seu projeto, verificar seu repositório GitHub e consultar documentação, tudo automaticamente. + +--- + +Cabo de energia conectando com faísca elétrica brilhante cercado por ícones de tecnologia flutuantes representando conexões de servidor MCP + +# Início Rápido: MCP em 30 Segundos + +## Comece com o servidor GitHub MCP integrado +Vamos ver o MCP em ação agora mesmo, antes de configurar qualquer coisa. +O servidor GitHub MCP está incluído por padrão. Experimente isto: + +```bash +copilot +> List the recent commits in this repository +``` + +Se o Copilot retornar dados reais de commits, você acabou de ver o MCP em ação. É o servidor GitHub MCP acessando o GitHub em seu nome. Mas o GitHub é apenas *um* servidor. Este capítulo mostra como adicionar mais (acesso ao sistema de arquivos, documentação atualizada e outros) para que o Copilot possa fazer ainda mais. + +--- + +## O Comando `/mcp show` + +Use `/mcp show` para ver quais servidores MCP estão configurados e se estão habilitados: + +```bash +copilot + +> /mcp show + +MCP Servers: +✓ github (enabled) - GitHub integration +✓ filesystem (enabled) - File system access +``` + +> 💡 **Vendo apenas o servidor GitHub?** Isso é esperado! Se você ainda não adicionou nenhum servidor MCP adicional, o GitHub é o único listado. Você adicionará mais na próxima seção. + +> 📚 **Quer ver todos os comandos de gerenciamento MCP?** Você pode gerenciar servidores com slash commands `/mcp` dentro do chat, ou com `copilot mcp` diretamente do terminal. Veja a [referência completa de comandos](#-additional-mcp-commands) no final deste capítulo. + +
+🎬 Veja em ação! + +![Demo de Status MCP](../../../06-mcp-servers/images/mcp-status-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +--- + +## O que Muda com MCP? + +Aqui está a diferença que o MCP faz na prática: + +**Sem 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." +``` + +**Com 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... +``` + +O MCP torna o Copilot ciente do seu ambiente de desenvolvimento real. + +> 📚 **Documentação oficial**: [Sobre MCP](https://docs.github.com/copilot/concepts/context/mcp) para uma visão mais profunda de como o MCP funciona com o GitHub Copilot. + +--- + +# Configurando Servidores MCP + +Mãos ajustando botões e deslizadores em uma mesa de mixagem profissional representando a configuração do servidor MCP + +Agora que você viu o MCP em ação, vamos configurar servidores adicionais. Você pode adicionar servidores de duas formas: **do registro integrado** (mais fácil — configuração guiada direto no CLI) ou **editando o arquivo de configuração** manualmente (mais flexível). Comece com a opção do registro se não tiver certeza de qual escolher. + +--- + +## Instalando Servidores MCP do Registro + +O CLI tem um registro de servidores MCP integrado que permite descobrir e instalar servidores populares com uma configuração guiada — sem necessidade de editar JSON. + +```bash +copilot + +> /mcp search +``` + +O Copilot abre um seletor interativo mostrando os servidores disponíveis. Selecione um e o CLI o guiará por qualquer configuração necessária (chaves de API, caminhos, etc.) e o adicionará à sua configuração automaticamente. + +> 💡 **Por que usar o registro?** É a forma mais fácil de começar — você não precisa saber o nome do pacote npm, argumentos de comando ou estrutura JSON. O CLI cuida de tudo isso por você. + +--- + +## Arquivo de Configuração MCP + +Os servidores MCP são configurados em `~/.copilot/mcp-config.json` (nível de usuário, aplica-se a todos os projetos) ou `.mcp.json` (nível do projeto, colocado na raiz do seu projeto). Se você usou `/mcp search` acima, o CLI já criou ou atualizou este arquivo para você, mas é útil entender o formato para personalização. + +> ⚠️ **Nota**: `.vscode/mcp.json` não é mais suportado como fonte de configuração MCP. Se você tiver um `.vscode/mcp.json` existente, migre-o para `.mcp.json` na raiz do projeto. O CLI mostrará uma dica de migração se detectar um arquivo de configuração antigo. + +```json +{ + "mcpServers": { + "server-name": { + "type": "local", + "command": "npx", + "args": ["@package/server-name"], + "tools": ["*"] + } + } +} +``` + +*A maioria dos servidores MCP é distribuída como pacotes npm e executada via comando `npx`.* + +
+💡 Novo em JSON? Clique aqui para aprender o que cada campo significa + +| Campo | O que Significa | +|-------|----------------| +| `"mcpServers"` | Contêiner para todas as suas configurações de servidor MCP | +| `"server-name"` | Um nome que você escolhe (ex.: "github", "filesystem") | +| `"type": "local"` | O servidor é executado na sua máquina | +| `"command": "npx"` | O programa a executar (npx executa pacotes npm) | +| `"args": [...]` | Argumentos passados para o comando | +| `"tools": ["*"]` | Permitir todas as ferramentas deste servidor | + +**Regras importantes de JSON:** +- Use aspas duplas `"` para strings (não aspas simples) +- Sem vírgulas finais após o último item +- O arquivo deve ser JSON válido (use um [validador JSON](https://jsonlint.com/) se não tiver certeza) + +
+ +--- + +## Adicionando Servidores MCP + +O servidor GitHub MCP é integrado e não requer configuração. Abaixo estão servidores adicionais que você pode adicionar. **Escolha o que lhe interessa, ou trabalhe neles em ordem.** + +| Quero... | Ir para | +|---|---| +| Deixar o Copilot navegar pelos arquivos do meu projeto | [Servidor Filesystem](#filesystem-server) | +| Obter documentação atualizada de biblioteca | [Servidor Context7](#context7-server-documentation) | +| Explorar extras opcionais (servidores personalizados, web_fetch) | [Além do Básico](#beyond-the-basics) | + +
+Servidor Filesystem - Deixar o Copilot explorar os arquivos do projeto + + +### Servidor Filesystem + +```json +{ + "mcpServers": { + "filesystem": { + "type": "local", + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], + "tools": ["*"] + } + } +} +``` + +> 💡 **O caminho `.`**: O `.` significa "diretório atual". O Copilot pode acessar arquivos relativos ao local de onde você o iniciou. Em um Codespace, este é a raiz do seu espaço de trabalho. Você também pode usar um caminho absoluto como `/workspaces/copilot-cli-for-beginners` se preferir. + +Adicione isso ao seu `~/.copilot/mcp-config.json` e reinicie o Copilot. + +
+ +
+Servidor Context7 - Obter documentação atualizada de bibliotecas + + +### Servidor Context7 (Documentação) + +O Context7 dá ao Copilot acesso a documentação atualizada de frameworks e bibliotecas populares. Em vez de depender de dados de treinamento que podem estar desatualizados, o Copilot busca a documentação atual real. + +```json +{ + "mcpServers": { + "context7": { + "type": "local", + "command": "npx", + "args": ["-y", "@upstash/context7-mcp"], + "tools": ["*"] + } + } +} +``` + +- ✅ **Sem chave de API necessária** +- ✅ **Sem conta necessária** +- ✅ **Seu código permanece local** + +Adicione isso ao seu `~/.copilot/mcp-config.json` e reinicie o Copilot. + +
+ +
+Além do Básico - Servidores personalizados e acesso web (opcional) + + +Esses são extras opcionais para quando você estiver confortável com os servidores principais acima. + +### Servidor Microsoft Learn MCP + +Todos os servidores MCP que você viu até agora (filesystem, Context7) são executados localmente na sua máquina. Mas os servidores MCP também podem ser executados remotamente, o que significa que você apenas aponta o Copilot CLI para uma URL e ele cuida do resto. Sem `npx` ou `python`, sem processo local, sem dependências para instalar. + +O [Servidor Microsoft Learn MCP](https://github.com/microsoftdocs/mcp) é um bom exemplo. Ele dá ao Copilot CLI acesso direto à documentação oficial da Microsoft (Azure, Microsoft Foundry e outros tópicos de IA, .NET, Microsoft 365 e muito mais) para que ele possa pesquisar documentos, buscar páginas completas e encontrar amostras de código oficiais em vez de depender dos dados de treinamento do modelo. + +- ✅ **Sem chave de API necessária** +- ✅ **Sem conta necessária** +- ✅ **Sem instalação local necessária** + +**Instalação rápida com `/plugin install`:** + +Em vez de editar seu arquivo de configuração JSON manualmente, você pode instalá-lo em um comando: + +```bash +copilot + +> /plugin install microsoftdocs/mcp +``` + +Isso adiciona o servidor e suas skills de agente associadas automaticamente. As skills instaladas incluem: + +- **microsoft-docs**: Conceitos, tutoriais e consultas factuais +- **microsoft-code-reference**: Consultas de API, amostras de código e solução de problemas +- **microsoft-skill-creator**: Uma meta-skill para gerar skills personalizadas sobre tecnologias Microsoft + +**Uso:** +```bash +copilot + +> What's the recommended way to deploy a Python app to Azure App Service? Search Microsoft Learn. +``` + +📚 Saiba mais: [Visão geral do Servidor Microsoft Learn MCP](https://learn.microsoft.com/training/support/mcp-get-started) + +### Acesso Web com `web_fetch` + +O Copilot CLI inclui uma ferramenta `web_fetch` integrada que pode buscar conteúdo de qualquer URL. Isso é útil para trazer READMEs, documentação de API ou notas de versão sem sair do terminal. Sem necessidade de servidor MCP. + +Você pode controlar quais URLs são acessíveis via `~/.copilot/config.json` (configurações gerais do Copilot), que é separado de `~/.copilot/mcp-config.json` (definições de servidor MCP). + +```json +{ + "permissions": { + "allowedUrls": [ + "https://api.github.com/**", + "https://docs.github.com/**", + "https://*.npmjs.org/**" + ], + "blockedUrls": [ + "http://**" + ] + } +} +``` + +**Uso:** +```bash +copilot + +> Fetch and summarize the README from https://github.com/facebook/react +``` + +### Construindo um Servidor MCP Personalizado + +Quer conectar o Copilot às suas próprias APIs, bancos de dados ou ferramentas internas? Você pode construir um servidor MCP personalizado em Python. Isso é completamente opcional, pois os servidores pré-construídos (GitHub, filesystem, Context7) cobrem a maioria dos casos de uso. + +📖 Veja o [Guia de Servidor MCP Personalizado](mcp-custom-server.md) para um passo a passo completo usando o aplicativo de livros como exemplo. + +📚 Para mais contexto, veja o [curso MCP para Iniciantes](https://github.com/microsoft/mcp-for-beginners). + +
+ + + +### Arquivo de Configuração Completo + +Aqui está um `mcp-config.json` completo com servidores filesystem e Context7: + +> 💡 **Nota:** O GitHub MCP é integrado. Você não precisa adicioná-lo ao seu arquivo de configuração. + +```json +{ + "mcpServers": { + "filesystem": { + "type": "local", + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "."], + "tools": ["*"] + }, + "context7": { + "type": "local", + "command": "npx", + "args": ["-y", "@upstash/context7-mcp"], + "tools": ["*"] + } + } +} +``` + +Salve como `~/.copilot/mcp-config.json` para acesso global ou `.mcp.json` na raiz do projeto para configuração específica do projeto. + +--- + +# Usando Servidores MCP + +Agora que você tem servidores MCP configurados, vamos ver o que eles podem fazer. + +Usando Servidores MCP - Diagrama hub-and-spoke mostrando um Developer CLI conectado a servidores GitHub, Filesystem, Context7 e Custom/Web Fetch + +--- + +## Exemplos de Uso dos Servidores + +**Escolha um servidor para explorar, ou trabalhe neles em ordem.** + +| Quero experimentar... | Ir para | +|---|---| +| Repositórios, issues e PRs do GitHub | [Servidor GitHub](#github-server-built-in) | +| Navegação pelos arquivos do projeto | [Uso do Servidor Filesystem](#filesystem-server-usage) | +| Consulta de documentação de biblioteca | [Uso do Servidor Context7](#context7-server-usage) | +| Servidor personalizado, Microsoft Learn MCP e uso do web_fetch | [Uso do Além do Básico](#beyond-the-basics-usage) | + +
+Servidor GitHub (Integrado) - Acessar repositórios, issues, PRs e mais + + +### Servidor GitHub (Integrado) + +O servidor GitHub MCP é **integrado**. Se você fez login no Copilot (o que você fez durante a configuração inicial), ele já funciona. Nenhuma configuração necessária! + +> 💡 **Não está funcionando?** Execute `/login` para se autenticar novamente com o GitHub. + +
+Autenticação em Dev Containers + +- **GitHub Codespaces** (recomendado): A autenticação é automática. O CLI `gh` herda o token do Codespace. Nenhuma ação necessária. +- **Container de desenvolvimento local (Docker)**: Execute `gh auth login` após o container iniciar, depois reinicie o Copilot. + +**Solução de problemas de autenticação:** +```bash +# Verificar se você está autenticado +gh auth status + +# Se não, faça login +gh auth login + +# Verificar se o GitHub MCP está conectado +copilot +> /mcp show +``` + +
+ +| Recurso | Exemplo | +|---------|---------| +| **Informações do repositório** | Ver commits, branches, contribuidores | +| **Issues** | Listar, criar, pesquisar e comentar em issues | +| **Pull requests** | Ver PRs, diffs, criar PRs, verificar status | +| **Pesquisa de código** | Pesquisar código em repositórios | +| **Actions** | Consultar execuções de fluxo de trabalho e status | + +```bash +copilot + +# Ver atividade recente neste repositório +> 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) +... + +# Explorar a estrutura do repositório +> What branches exist in this repository? + +Branches: +- main (default) +- chapter6 (current) + +# Pesquisar padrões de código em todo o repositório +> Search this repository for files that import pytest + +Found 1 file: +- samples/book-app-project/tests/test_books.py +``` + +> 💡 **Trabalhando no seu próprio fork?** Se você fez fork deste repositório do curso, você também pode experimentar operações de escrita como criar issues e pull requests. Vamos praticar isso nos exercícios abaixo. + +> ⚠️ **Não está vendo resultados?** O GitHub MCP opera no remoto do repositório (em github.com), não apenas em arquivos locais. Certifique-se de que seu repositório tem um remoto: execute `git remote -v` para verificar. + +
+ +
+Servidor Filesystem - Navegar e analisar arquivos do projeto + + +### Servidor Filesystem + +Uma vez configurado, o filesystem MCP fornece ferramentas que o Copilot pode usar automaticamente: + +```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() +``` + +
+ +
+Servidor Context7 - Consultar documentação de bibliotecas + + +### Servidor 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? + +# O Copilot agora conhece os padrões oficiais do pytest +# e pode aplicá-los a samples/book-app-project/tests/test_books.py +``` + +
+ +
+Além do Básico - Servidor personalizado e uso do web_fetch + + +### Além do Básico + +**Servidor MCP Personalizado**: Se você construiu o servidor book-lookup do [Guia de Servidor MCP Personalizado](mcp-custom-server.md), você pode consultar sua coleção de livros diretamente: + +```bash +copilot + +> Look up information about "1984" using the book lookup server. Search for books by George Orwell +``` + +**Microsoft Learn MCP**: Se você instalou o [servidor Microsoft Learn MCP](#microsoft-learn-mcp-server), você pode consultar a documentação oficial da Microsoft diretamente: + +```bash +copilot + +> How do I configure managed identity for an Azure Function? Search Microsoft Learn. +``` + +**Web Fetch**: Use a ferramenta `web_fetch` integrada para trazer conteúdo de qualquer URL: + +```bash +copilot + +> Fetch and summarize the README from https://github.com/facebook/react +``` + +
+ +--- + +## Fluxos de Trabalho com Múltiplos Servidores + +Esses fluxos de trabalho mostram por que os desenvolvedores dizem "Nunca mais quero trabalhar sem isso." Cada exemplo combina múltiplos servidores MCP em uma única sessão. + +Fluxo de trabalho de Issue para PR usando MCP - Mostra o fluxo completo desde obter um issue do GitHub até criar um pull request + +*Fluxo de trabalho MCP completo: O GitHub MCP recupera dados do repositório, o Filesystem MCP encontra código, o Context7 MCP fornece melhores práticas e o Copilot cuida da análise* + +Cada exemplo abaixo é independente. **Escolha um que lhe interesse, ou leia todos.** + +| Quero ver... | Ir para | +|---|---| +| Múltiplos servidores trabalhando juntos | [Exploração com Múltiplos Servidores](#multi-server-exploration) | +| Indo de um issue a um PR em uma sessão | [Fluxo de Trabalho Issue-para-PR](#issue-to-pr-workflow) | +| Uma verificação rápida de saúde do projeto | [Painel de Saúde](#health-dashboard) | + +
+Exploração com Múltiplos Servidores - Combinar filesystem, GitHub e Context7 em uma sessão + + +#### Explorando o Aplicativo de Livros com Múltiplos Servidores MCP + +```bash +copilot + +# Etapa 1: Usar filesystem MCP para explorar o aplicativo de livros +> 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 + +# Etapa 2: Usar GitHub MCP para verificar alterações recentes +> 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) + +# Etapa 3: Usar Context7 MCP para melhores práticas +> 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 + +# Etapa 4: Sintetizar uma recomendação +> 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) +``` + +
+🎬 Veja o fluxo de trabalho MCP em ação! + +![Demo do Fluxo de Trabalho MCP](../../../06-mcp-servers/images/mcp-workflow-demo.gif) + +*A saída da demo pode variar. O seu modelo, ferramentas e respostas serão diferentes do que está mostrado aqui.* + +
+ +**O resultado**: Exploração de código → revisão do histórico → consulta de melhores práticas → plano de melhorias. **Tudo em uma única sessão de terminal, usando três servidores MCP juntos.** + +
+ +
+Fluxo de Trabalho Issue-para-PR - Ir de um issue do GitHub a um pull request sem sair do terminal + + +#### O Fluxo de Trabalho Issue-para-PR (No Seu Próprio Repositório) + +Isso funciona melhor no seu próprio fork ou repositório onde você tem acesso de escrita: + +> 💡 **Não se preocupe se não puder tentar isso agora.** Se você estiver em um clone somente leitura, você vai praticar isso na atividade. Por agora, apenas leia para entender o fluxo. + +```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 + +[O Copilot implementa validação de ano em 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 +``` + +**Zero copiar e colar. Zero troca de contexto. Uma sessão de terminal.** + +
+ +
+Painel de Saúde - Obter uma verificação rápida de saúde do projeto usando múltiplos servidores + + +#### Painel de Saúde do Aplicativo de Livros + +```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! +``` + +**O resultado**: Múltiplas fontes de dados agregadas em segundos. Manualmente, isso significaria executar grep, contar linhas, verificar git log e navegar por arquivos de teste. Facilmente 15+ minutos de trabalho. + +
+ +--- + +# Prática + +Mesa de trabalho aconchegante com monitor mostrando código, abajur, xícara de café e fones de ouvido prontos para a prática + +**🎉 Agora você conhece o essencial!** Você entende MCP, viu como configurar servidores e viu fluxos de trabalho reais em ação. Agora é hora de experimentar você mesmo. + +--- + +## ▶️ Experimente Você Mesmo + +Agora é a sua vez! Complete estes exercícios para praticar o uso de servidores MCP com o projeto do aplicativo de livros. + +### Exercício 1: Verificar o Status MCP + +Comece vendo quais servidores MCP estão disponíveis: + +```bash +copilot + +> /mcp show +``` + +Você deve ver o servidor GitHub listado como habilitado. Se não, execute `/login` para se autenticar. + +--- + +### Exercício 2: Explorar o Aplicativo de Livros com Filesystem MCP + +Se você configurou o servidor filesystem, use-o para explorar o aplicativo de livros: + +```bash +copilot + +> How many Python files are in samples/book-app-project/? +> What functions are defined in each file? +``` + +**Resultado esperado**: O Copilot lista `book_app.py`, `books.py` e `utils.py` com suas funções. + +> 💡 **Ainda não tem o filesystem MCP configurado?** Crie o arquivo de configuração da seção [Configuração Completa](#complete-configuration-file) acima. Então reinicie o Copilot. + +--- + +### Exercício 3: Consultar o Histórico do Repositório com GitHub MCP + +Use o GitHub MCP integrado para explorar este repositório do curso: + +```bash +copilot + +> List the last 5 commits in this repository + +> What branches exist in this repository? +``` + +**Resultado esperado**: O Copilot mostra mensagens de commit recentes e nomes de branches do remoto do GitHub. + +> ⚠️ **Em um Codespace?** Isso funciona automaticamente. A autenticação é herdada. Se você estiver em um clone local, certifique-se de que `gh auth status` mostra que você está logado. + +--- + +### Exercício 4: Combinar Múltiplos Servidores MCP + +Agora combine filesystem e GitHub MCP em uma única sessão: + +```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. +``` + +**Resultado esperado**: O Copilot lê o arquivo JSON (filesystem MCP), lista os 5 livros incluindo "The Hobbit", "1984", "Dune", "To Kill a Mockingbird" e "Mysterious Book", então consulta o GitHub para o histórico de commits. + +**Autoavaliação**: Você entende MCP quando consegue explicar por que "Check my repo's commit history" é melhor do que executar manualmente `git log` e colar a saída no seu prompt. + +--- + +## 📝 Atividade + +### Desafio Principal: Exploração MCP do Aplicativo de Livros + +Pratique o uso de servidores MCP juntos no projeto do aplicativo de livros. Complete estas etapas em uma única sessão do Copilot: + +1. **Verificar se o MCP está funcionando**: Execute `/mcp show` e confirme que pelo menos o servidor GitHub está habilitado +2. **Configurar o filesystem MCP** (se ainda não feito): Crie `~/.copilot/mcp-config.json` com a configuração do servidor filesystem +3. **Explorar o código**: Peça ao Copilot para usar o servidor filesystem para: + - Listar todas as funções em `samples/book-app-project/books.py` + - Verificar quais funções em `samples/book-app-project/utils.py` estão faltando dicas de tipo + - Ler `samples/book-app-project/data.json` e identificar quaisquer problemas de qualidade de dados (dica: veja a última entrada) +4. **Verificar a atividade do repositório**: Peça ao Copilot para usar o GitHub MCP para: + - Listar commits recentes que tocaram arquivos em `samples/book-app-project/` + - Verificar se existem issues ou pull requests abertos +5. **Combinar servidores**: Em um único prompt, peça ao Copilot para: + - Ler o arquivo de teste em `samples/book-app-project/tests/test_books.py` + - Comparar as funções testadas com todas as funções em `books.py` + - Resumir qual cobertura de teste está faltando + +**Critérios de sucesso**: Você consegue combinar perfeitamente dados de filesystem e GitHub MCP em uma única sessão do Copilot, e consegue explicar o que cada servidor MCP contribuiu para a resposta. + +
+💡 Dicas (clique para expandir) + +**Etapa 1: Verificar MCP** +```bash +copilot +> /mcp show +# Deve mostrar "github" como habilitado +# Se não, execute: /login +``` + +**Etapa 2: Criar o arquivo de configuração** + +Use o JSON da seção [Configuração Completa](#complete-configuration-file) acima e salve como `~/.copilot/mcp-config.json`. + +**Etapa 3: Problema de qualidade de dados para procurar** + +O último livro em `data.json` é: +```json +{ + "title": "Mysterious Book", + "author": "", + "year": 0, + "read": false +} +``` +Um autor vazio e ano igual a 0. Esse é o problema de qualidade de dados! + +**Etapa 5: Comparação de cobertura de testes** + +Os testes em `test_books.py` cobrem: `add_book`, `mark_as_read`, `remove_book`, `get_unread_books` e `find_book_by_title`. Funções como `load_books`, `save_books` e `list_books` não têm testes diretos. As funções CLI em `book_app.py` e os auxiliares em `utils.py` não têm testes. + +**Se o MCP não estiver funcionando:** Reinicie o Copilot após editar o arquivo de configuração. + +
+ +### Desafio Bônus: Construir um Servidor MCP Personalizado + +Pronto para ir mais fundo? Siga o [Guia de Servidor MCP Personalizado](mcp-custom-server.md) para construir seu próprio servidor MCP em Python que se conecta a qualquer API. + +--- + +
+🔧 Erros Comuns e Solução de Problemas (clique para expandir) + +### Erros Comuns + +| Erro | O que Acontece | Solução | +|------|----------------|---------| +| Não saber que o GitHub MCP é integrado | Tentar instalá-lo/configurá-lo manualmente | O GitHub MCP está incluído por padrão. Apenas tente: "List the recent commits in this repo" | +| Procurar a configuração no local errado | Não consegue encontrar ou editar as configurações MCP | A configuração de nível de usuário está em `~/.copilot/mcp-config.json`, o nível de projeto é `.mcp.json` na raiz do projeto | +| JSON inválido no arquivo de configuração | Servidores MCP falham ao carregar | Use `/mcp show` para verificar a configuração; valide a sintaxe JSON | +| Esquecer de autenticar servidores MCP | Erros de "Authentication failed" | Alguns MCPs precisam de autenticação separada. Verifique os requisitos de cada servidor | + +### Solução de Problemas + +**"Servidor MCP não encontrado"** - Verifique que: +1. O pacote npm existe: `npm view @modelcontextprotocol/server-github` +2. Sua configuração é JSON válido +3. O nome do servidor corresponde à sua configuração + +Use `/mcp show` para ver a configuração atual. + +**"Falha de autenticação do GitHub"** - O GitHub MCP integrado usa suas credenciais de `/login`. Tente: + +```bash +copilot +> /login +``` + +Isso vai autenticá-lo novamente com o GitHub. Se os problemas persistirem, verifique se sua conta do GitHub tem as permissões necessárias para o repositório que você está acessando. + +**"Servidor MCP falhou ao iniciar"** - Verifique os logs do servidor: +```bash +# Execute o comando do servidor manualmente para ver os erros +npx -y @modelcontextprotocol/server-github +``` + +**Ferramentas MCP não disponíveis** - Certifique-se de que o servidor está habilitado: +```bash +copilot + +> /mcp show +# Verificar se o servidor está listado e habilitado +``` + +Se um servidor estiver desabilitado, veja os [comandos `/mcp` adicionais](#-additional-mcp-commands) abaixo para saber como reabilitá-lo. + +
+ +--- + +
+📚 Comandos MCP Adicionais (clique para expandir) + + +Você pode gerenciar servidores MCP de duas formas: usando **slash commands dentro de uma sessão de chat**, ou usando o **comando `copilot mcp` diretamente no seu terminal** (sem necessidade de sessão de chat). + +### Opção 1: Slash commands (dentro de uma sessão de chat) + +Esses funcionam quando você já está dentro do `copilot`: + +| Comando | O que Faz | +|---------|-----------| +| `/mcp show` | Mostrar todos os servidores MCP configurados e seus status | +| `/mcp add` | Configuração interativa para adicionar um novo servidor | +| `/mcp edit ` | Editar uma configuração de servidor existente | +| `/mcp enable ` | Habilitar um servidor desabilitado (persiste entre sessões) | +| `/mcp disable ` | Desabilitar um servidor (persiste entre sessões) | +| `/mcp delete ` | Remover um servidor permanentemente | +| `/mcp auth ` | Re-autenticar com um servidor MCP que usa OAuth (ex.: após trocar de conta) | + +### Opção 2: Comando `copilot mcp` (do seu terminal) + +Você também pode gerenciar servidores MCP diretamente do seu terminal sem iniciar uma sessão de chat primeiro: + +```bash +# Listar todos os servidores MCP configurados +copilot mcp list + +# Habilitar um servidor +copilot mcp enable filesystem + +# Desabilitar um servidor +copilot mcp disable context7 +``` + +> 💡 **Quando usar qual?** Use slash commands `/mcp` quando você já estiver em uma sessão de chat. Use `copilot mcp` do terminal quando quiser verificar ou alterar rapidamente suas configurações de servidor antes de iniciar uma sessão. + +Para a maior parte deste curso, `/mcp show` é tudo que você precisa. Os outros comandos se tornam úteis à medida que você gerencia mais servidores ao longo do tempo. + +
+ +--- + +# Resumo + +## 🔑 Principais Aprendizados + +1. **MCP** conecta o Copilot a serviços externos (GitHub, sistema de arquivos, documentação) +2. **GitHub MCP é integrado** - sem necessidade de configuração, apenas `/login` +3. **Filesystem e Context7** são configurados via `~/.copilot/mcp-config.json` +4. **Fluxos de trabalho com múltiplos servidores** combinam dados de múltiplas fontes em uma única sessão +5. **Gerenciar servidores de duas formas**: use slash commands `/mcp` dentro do chat, ou `copilot mcp` do terminal +6. **Servidores personalizados** permitem conectar qualquer API (opcional, abordado no guia do apêndice) + +> 📋 **Referência rápida**: Veja a [referência de comandos do GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para uma lista completa de comandos e atalhos. + +--- + +## ➡️ O Que Vem a Seguir + +Agora você tem todos os blocos de construção: modos, contexto, fluxos de trabalho, agentes, skills e MCP. Hora de colocá-los todos juntos. + +No **[Capítulo 07: Colocando Tudo Junto](../07-putting-it-together/README.md)**, você aprenderá: + +- Combinar agentes, skills e MCP em fluxos de trabalho unificados +- Desenvolvimento completo de funcionalidades de ideia a PR mesclado +- Automação com hooks +- Melhores práticas para ambientes de equipe + +--- + +**[← Voltar ao Capítulo 05](../05-skills/README.md)** | **[Continuar para o Capítulo 07 →](../07-putting-it-together/README.md)** diff --git a/localization/pt-br/06-mcp-servers/mcp-custom-server.md b/localization/pt-br/06-mcp-servers/mcp-custom-server.md new file mode 100644 index 00000000..6a643009 --- /dev/null +++ b/localization/pt-br/06-mcp-servers/mcp-custom-server.md @@ -0,0 +1,176 @@ +# Construindo um Servidor MCP Personalizado + +> ⚠️ **Este conteúdo é completamente opcional.** Você pode ser altamente produtivo com o Copilot CLI usando apenas os servidores MCP pré-construídos (GitHub, filesystem, Context7). Este guia é para desenvolvedores que desejam conectar o Copilot a APIs internas personalizadas. Veja o [curso MCP para Iniciantes](https://github.com/microsoft/mcp-for-beginners) para mais detalhes. +> +> **Pré-requisitos:** +> - Confortável com Python +> - Entendimento de padrões `async`/`await` +> - `pip` disponível no seu sistema (incluído neste dev container) +> +> **[← Voltar ao Capítulo 06: Servidores MCP](README.md)** + +--- + +Quer conectar o Copilot às suas próprias APIs? Veja como construir um servidor MCP simples em Python que consulta informações de livros, conectando de volta ao projeto do aplicativo de livros que você usou ao longo deste curso. + +## Configuração do Projeto + +```bash +mkdir book-lookup-mcp-server +cd book-lookup-mcp-server +pip install mcp +``` + +> 💡 **O que é o pacote `mcp`?** É o SDK oficial em Python para construir servidores MCP. Ele cuida dos detalhes do protocolo para que você possa focar nas suas ferramentas. + +## Implementação do Servidor + +Crie um arquivo chamado `server.py`: + +```python +# server.py +import json +from mcp.server.fastmcp import FastMCP + +# Criar o servidor MCP +mcp = FastMCP("book-lookup") + +# Banco de dados de livros de exemplo (em um servidor real, isso poderia consultar uma API ou banco de dados) +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() +``` + +**O que está acontecendo aqui:** + +| Parte | O que Faz | +|-------|-----------| +| `FastMCP("book-lookup")` | Cria um servidor chamado "book-lookup" | +| `@mcp.tool()` | Registra uma função como ferramenta que o Copilot pode chamar | +| Dicas de tipo + docstrings | Dizem ao Copilot o que cada ferramenta faz e quais parâmetros ela precisa | +| `mcp.run()` | Inicia o servidor e escuta requisições | + +> 💡 **Por que decoradores?** O decorador `@mcp.tool()` é tudo que você precisa. O SDK do MCP lê automaticamente o nome, dicas de tipo e docstring da sua função para gerar o esquema da ferramenta. Sem necessidade de esquema JSON manual! + +## Configuração + +Adicione ao seu `~/.copilot/mcp-config.json`: + +```json +{ + "mcpServers": { + "book-lookup": { + "type": "local", + "command": "python3", + "args": ["./book-lookup-mcp-server/server.py"], + "tools": ["*"] + } + } +} +``` + +## Uso + +```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 + +[Mostra todos os livros no banco de dados com os ISBNs] +``` + +## Próximos Passos + +Uma vez que você construiu um servidor básico, você pode: + +1. **Adicionar mais ferramentas** - Cada função `@mcp.tool()` se torna uma ferramenta que o Copilot pode chamar +2. **Conectar APIs reais** - Substituir o `BOOKS_DB` simulado por chamadas de API reais ou consultas de banco de dados +3. **Adicionar autenticação** - Manipular chaves de API e tokens de forma segura +4. **Compartilhar seu servidor** - Publicar no PyPI para que outros possam instalá-lo com `pip` + +## Recursos + +- [SDK MCP Python](https://github.com/modelcontextprotocol/python-sdk) +- [SDK MCP TypeScript](https://github.com/modelcontextprotocol/typescript-sdk) +- [Servidores MCP de Exemplo](https://github.com/modelcontextprotocol/servers) +- [Curso MCP para Iniciantes](https://github.com/microsoft/mcp-for-beginners) + +--- + +**[← Voltar ao Capítulo 06: Servidores MCP](README.md)** diff --git a/localization/pt-br/07-putting-it-together/README.md b/localization/pt-br/07-putting-it-together/README.md new file mode 100644 index 00000000..c7c1bae7 --- /dev/null +++ b/localization/pt-br/07-putting-it-together/README.md @@ -0,0 +1,512 @@ +![Capítulo 07: Colocando Tudo Junto](../../../07-putting-it-together/images/chapter-header.png) + +> **Tudo que você aprendeu se combina aqui. Vá de uma ideia a um PR mesclado em uma única sessão.** + +Neste capítulo, você reunirá tudo que aprendeu em fluxos de trabalho completos. Você construirá funcionalidades usando colaboração entre múltiplos agentes, configurará hooks de pré-commit que detectam problemas de segurança antes de serem commitados, integrará o Copilot em pipelines CI/CD e irá de uma ideia de funcionalidade a um PR mesclado em uma única sessão de terminal. É aqui que o GitHub Copilot CLI se torna um verdadeiro multiplicador de força. + +> 💡 **Nota**: Este capítulo mostra como combinar tudo que você aprendeu. **Você não precisa de agentes, skills ou MCP para ser produtivo (embora eles possam ser muito úteis).** O fluxo de trabalho principal — descrever, planejar, implementar, testar, revisar, publicar — funciona apenas com os recursos integrados dos Capítulos 00-03. + +## 🎯 Objetivos de aprendizado + +Ao final deste capítulo, você será capaz de: + +- Combinar agentes, skills e MCP (Model Context Protocol) em fluxos de trabalho unificados +- Construir funcionalidades completas usando abordagens com múltiplas ferramentas +- Configurar automação básica com hooks +- Aplicar melhores práticas para desenvolvimento profissional + +> ⏱️ **Tempo estimado**: ~75 minutos (15 min de leitura + 60 min de prática) + +--- + +## 🧩 Analogia com o Mundo Real: A Orquestra + +Analogia da Orquestra - Fluxo de Trabalho Unificado + +Uma orquestra sinfônica tem muitas seções: +- **Cordas** fornecem a base (como seus fluxos de trabalho principais) +- **Metais** adicionam potência (como agentes com expertise especializada) +- **Madeiras** adicionam cor (como skills que ampliam capacidades) +- **Percussão** mantém o ritmo (como MCP conectando a sistemas externos) + +Individualmente, cada seção soa limitada. Juntas, bem regidas, criam algo magnífico. + +**É isso que este capítulo ensina!**
+*Como um regente com uma orquestra, você orquestra agentes, skills e MCP em fluxos de trabalho unificados* + +Vamos começar percorrendo um cenário que modifica código, gera testes, revisa e cria um PR - tudo em uma sessão. + +--- + +## De Ideia a PR Mesclado em Uma Sessão + +Em vez de alternar entre seu editor, terminal, executor de testes e interface do GitHub perdendo contexto a cada vez, você pode combinar todas as suas ferramentas em uma única sessão de terminal. Vamos detalhar esse padrão na seção [Padrão de Integração](#the-integration-pattern-for-power-users) abaixo. + +```bash +# Iniciar o Copilot no modo interativo +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? + +# O Copilot cria um plano de alto nível... + +# MUDAR PARA O AGENTE PYTHON-REVIEWER +> /agent +# Selecione "python-reviewer" + +> @samples/book-app-project/books.py Design a get_unread_books method. +> What is the best approach? + +# O agente python-reviewer produz: +# - Assinatura do método e tipo de retorno +# - Implementação de filtro usando compreensão de lista +# - Tratamento de casos extremos para coleções vazias + +# MUDAR PARA O AGENTE PYTEST-HELPER +> /agent +# Selecione "pytest-helper" + +> @samples/book-app-project/tests/test_books.py Design test cases for +> filtering unread books. + +# O agente pytest-helper produz: +# - Casos de teste para coleções vazias +# - Casos de teste com livros misturados lidos/não lidos +# - Casos de teste com todos os livros lidos + +# IMPLEMENTAR +> 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 + +# TESTAR +> Generate comprehensive tests for the new feature + +# Múltiplos testes são gerados similares ao seguinte: +# - Caminho feliz (3 testes) — filtra corretamente, exclui lidos, inclui não lidos +# - Casos extremos (4 testes) — coleção vazia, todos lidos, nenhum lido, livro único +# - Parametrizado (5 casos) — variando proporções lidos/não lidos via @pytest.mark.parametrize +# - Integração (4 testes) — interação com mark_as_read, remove_book, add_book e integridade de dados + +# Revisar as alterações +> /review + +# Se a revisão passar, use /pr para operar no pull request da branch atual +> /pr [view|create|fix|auto] + +# Ou pergunte naturalmente se quiser que o Copilot esboce pelo terminal +> Create a pull request titled "Feature: Add list unread books command" +``` + +**Abordagem tradicional**: Alternando entre editor, terminal, executor de testes, documentação e interface do GitHub. Cada troca causa perda de contexto e atrito. + +**O insight chave**: Você direcionou especialistas como um arquiteto. Eles cuidaram dos detalhes. Você cuidou da visão. + +> 💡 **Indo além**: Para planos grandes com múltiplas etapas como este, tente `/fleet` para deixar o Copilot executar subtarefas independentes em paralelo. Veja a [documentação oficial](https://docs.github.com/copilot/concepts/agents/copilot-cli/fleet) para detalhes. + +--- + +# Fluxos de Trabalho Adicionais + +Pessoas montando um grande quebra-cabeça colorido com engrenagens, representando como agentes, skills e MCP se combinam em fluxos de trabalho unificados + +Para usuários avançados que completaram os Capítulos 04-06, esses fluxos de trabalho mostram como agentes, skills e MCP multiplicam sua eficácia. + +## O Padrão de Integração + +Aqui está o modelo mental para combinar tudo: + +O Padrão de Integração - Um fluxo de trabalho de 4 fases: Reunir Contexto (MCP), Analisar e Planejar (Agentes), Executar (Skills + Manual), Concluir (MCP) + +--- + +## Fluxo de Trabalho 1: Investigação e Correção de Bug + +Correção de bug do mundo real com integração completa de ferramentas: + +```bash +copilot + +# FASE 1: Entender o bug do GitHub (MCP fornece isso) +> Get the details of issue #1 + +# Descoberta: "find_by_author doesn't work with partial names" + +# FASE 2: Pesquisar melhores práticas (pesquisa profunda com fontes web + GitHub) +> /research Best practices for Python case-insensitive string matching + +# FASE 3: Encontrar o código relacionado +> @samples/book-app-project/books.py Show me the find_by_author method + +# FASE 4: Obter análise especializada +> /agent +# Selecione "python-reviewer" + +> Analyze this method for issues with partial name matching + +# Agente identifica: Método usa igualdade exata em vez de correspondência de substring + +# FASE 5: Corrigir com orientação do agente +> Implement the fix using lowercase comparison and 'in' operator + +# FASE 6: Gerar testes +> /agent +# Selecione "pytest-helper" + +> Generate pytest tests for find_by_author with partial matches +> Include test cases: partial name, case variations, no matches + +# FASE 7: Commit e PR +> Generate a commit message for this fix + +> Create a pull request linking to issue #1 +``` + +--- + +## Fluxo de Trabalho 2: Automação de Revisão de Código (Opcional) + +> 💡 **Esta seção é opcional.** Hooks de pré-commit são úteis para equipes, mas não são necessários para ser produtivo. Pule isto se você está apenas começando. +> +> ⚠️ **Nota sobre performance**: Este hook chama `copilot -p` para cada arquivo staged, o que leva vários segundos por arquivo. Para commits grandes, considere limitar a arquivos críticos ou executar revisões manualmente com `/review` em vez disso. + +Um **hook do git** é um script que o Git executa automaticamente em certos pontos, por exemplo, logo antes de um commit. Você pode usar isso para executar verificações automáticas no seu código. Veja como configurar uma revisão automática do Copilot nos seus commits: + +```bash +# Criar um hook de pré-commit +cat > .git/hooks/pre-commit << 'EOF' +#!/bin/bash + +# Obter arquivos staged (apenas arquivos Python) +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..." + + # Usar timeout para evitar travamento (60 segundos por arquivo) + # --allow-all aprova automaticamente leituras/escritas de arquivos para que o hook possa executar sem supervisão. + # Use apenas em scripts automatizados. Em sessões interativas, deixe o Copilot pedir permissão. + REVIEW=$(timeout 60 copilot --allow-all -p "Quick security review of @$file - critical issues only" 2>/dev/null) + + # Verificar se ocorreu timeout + 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 +``` + +> ⚠️ **Usuários macOS**: O comando `timeout` não está incluído por padrão no macOS. Instale-o com `brew install coreutils` ou substitua `timeout 60` por uma invocação simples sem guarda de timeout. + +> 📚 **Documentação oficial**: [Usar hooks](https://docs.github.com/copilot/how-tos/copilot-cli/use-hooks) e [Referência de configuração de hooks](https://docs.github.com/copilot/reference/hooks-configuration) para a API completa de hooks. +> +> 💡 **Alternativa integrada**: O Copilot CLI também tem um sistema de hooks integrado (`copilot hooks`) que pode ser executado automaticamente em eventos como pré-commit. O hook manual do git acima oferece controle total, enquanto o sistema integrado é mais simples de configurar. Veja a documentação acima para decidir qual abordagem se encaixa no seu fluxo de trabalho. + +Agora todo commit recebe uma revisão rápida de segurança: + +```bash +git add samples/book-app-project/books.py +git commit -m "Update book collection methods" + +# Saída: +# 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. +``` + +--- + +## Fluxo de Trabalho 3: Integração a uma Nova Base de Código + +Ao ingressar em um novo projeto, combine contexto, agentes e MCP para se adaptar rapidamente: + +```bash +# Iniciar o Copilot no modo interativo +copilot + +# FASE 1: Obter a visão geral com contexto +> @samples/book-app-project/ Explain the high-level architecture of this codebase + +# FASE 2: Entender um fluxo específico +> @samples/book-app-project/book_app.py Walk me through what happens +> when a user runs "python book_app.py add" + +# FASE 3: Obter análise especializada com um agente +> /agent +# Selecione "python-reviewer" + +> @samples/book-app-project/books.py Are there any design issues, +> missing error handling, or improvements you would recommend? + +# FASE 4: Encontrar algo para trabalhar (MCP fornece acesso ao GitHub) +> List open issues labeled "good first issue" + +# FASE 5: Começar a contribuir +> Pick the simplest open issue and outline a plan to fix it +``` + +Este fluxo de trabalho combina contexto `@`, agentes e MCP em uma única sessão de integração — exatamente o padrão de integração do início deste capítulo. + +--- + +# Melhores Práticas e Automação + +Padrões e hábitos que tornam seus fluxos de trabalho mais eficazes. + +--- + +## Melhores Práticas + +### 1. Comece com Contexto Antes da Análise + +Sempre reúna contexto antes de pedir análise: + +```bash +# Bom +> Get the details of issue #42 +> /agent +# Selecione python-reviewer +> Analyze this issue + +# Menos eficaz +> /agent +# Selecione python-reviewer +> Fix login bug +# O agente não tem o contexto do issue +``` + +### 2. Conheça a Diferença: Agentes, Skills e Instruções Personalizadas + +Cada ferramenta tem seu ponto forte: + +```bash +# Agentes: Personas especializadas que você ativa explicitamente +> /agent +# Selecione python-reviewer +> Review this authentication code for security issues + +# Skills: Capacidades modulares que se ativam automaticamente quando seu prompt +# corresponde à descrição da skill (você deve criá-las primeiro — veja o Cap. 05) +> Generate comprehensive tests for this code +# Se você tiver uma skill de teste configurada, ela se ativa automaticamente + +# Instruções personalizadas (.github/copilot-instructions.md): Sempre ativas +# orientação que se aplica a cada sessão sem alternância ou acionamento +``` + +> 💡 **Ponto-chave**: Agentes e skills podem tanto analisar QUANTO gerar código. A diferença real é **como eles se ativam** — agentes são explícitos (`/agent`), skills são automáticas (correspondência por prompt), e instruções personalizadas estão sempre ativas. + +### 3. Mantenha as Sessões Focadas + +Use `/rename` para rotular sua sessão (facilita encontrar no histórico) e `/exit` para encerrá-la adequadamente: + +```bash +# Bom: Uma funcionalidade por sessão +> /rename list-unread-feature +# Trabalhar em listar não lidos +> /exit + +copilot +> /rename export-csv-feature +# Trabalhar na exportação CSV +> /exit + +# Menos eficaz: Tudo em uma sessão longa +``` + +### 4. Tornar os Fluxos de Trabalho Reutilizáveis com o Copilot + +Em vez de apenas documentar fluxos de trabalho em uma wiki, codifique-os diretamente no repositório onde o Copilot pode usá-los: + +- **Instruções personalizadas** (`.github/copilot-instructions.md`): Orientação sempre ativa para padrões de codificação, regras de arquitetura e etapas de build/test/deploy. Cada sessão as segue automaticamente. +- **Arquivos de prompt** (`.github/prompts/`): Prompts reutilizáveis e parametrizados que sua equipe pode compartilhar — como templates para revisões de código, geração de componentes ou descrições de PR. +- **Agentes personalizados** (`.github/agents/`): Codifique personas especializadas (ex.: um revisor de segurança ou um escritor de documentação) que qualquer pessoa da equipe pode ativar com `/agent`. +- **Skills personalizadas** (`.github/skills/`): Empacote instruções de fluxo de trabalho passo a passo que se ativam automaticamente quando relevante. + +> 💡 **A recompensa**: Novos membros da equipe obtêm seus fluxos de trabalho de graça — eles estão integrados ao repositório, não trancados na cabeça de alguém. + +--- + +## Bônus: Padrões de Produção + +Esses padrões são opcionais, mas valiosos para ambientes profissionais. + +### Gerador de Descrição de PR + +```bash +# Gerar descrições abrangentes de PR +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" +``` + +### Integração CI/CD + +Para equipes com pipelines CI/CD existentes, você pode automatizar revisões do Copilot em cada pull request usando GitHub Actions. Isso inclui postar comentários de revisão automaticamente e filtrar por problemas críticos. + +> 📖 **Saiba mais**: Veja [Integração CI/CD](../appendices/ci-cd-integration.md) para fluxos de trabalho completos do GitHub Actions, opções de configuração e dicas de solução de problemas. + +--- + +# Prática + +Mesa de trabalho aconchegante com monitor mostrando código, abajur, xícara de café e fones de ouvido prontos para a prática + +Coloque o fluxo de trabalho completo em prática. + +--- + +## ▶️ Experimente Você Mesmo + +Após completar as demos, tente estas variações: + +1. **Desafio de Ponta a Ponta**: Escolha uma pequena funcionalidade (ex.: "listar livros não lidos" ou "exportar para CSV"). Use o fluxo de trabalho completo: + - Planejar com `/plan` + - Projetar com agentes (python-reviewer, pytest-helper) + - Implementar + - Gerar testes + - Criar PR + +2. **Desafio de Automação**: Configure o hook de pré-commit do fluxo de trabalho de Automação de Revisão de Código. Faça um commit com uma vulnerabilidade intencional de caminho de arquivo. Ele é bloqueado? + +3. **Seu Fluxo de Trabalho de Produção**: Projete seu próprio fluxo de trabalho para uma tarefa comum que você faz. Escreva como um checklist. Que partes poderiam ser automatizadas com skills, agentes ou hooks? + +**Autoavaliação**: Você completou o curso quando consegue explicar a um colega como agentes, skills e MCP funcionam juntos - e quando usar cada um. + +--- + +## 📝 Atividade + +### Desafio Principal: Funcionalidade de Ponta a Ponta + +Os exemplos práticos percorreram a construção de uma funcionalidade "listar livros não lidos". Agora pratique o fluxo de trabalho completo em uma funcionalidade diferente: **pesquisar livros por faixa de ano**: + +1. Inicie o Copilot e reúna contexto: `@samples/book-app-project/books.py` +2. Planeje com `/plan Add a "search by year" command that lets users find books published between two years` +3. Implemente um método `find_by_year_range(start_year, end_year)` em `BookCollection` +4. Adicione uma função `handle_search_year()` em `book_app.py` que solicita ao usuário os anos inicial e final +5. Gere testes: `@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. Revise com `/review` +7. Atualize o README: `@samples/book-app-project/README.md Add documentation for the new "search by year" command.` +8. Gere uma mensagem de commit + +Documente seu fluxo de trabalho conforme avança. + +**Critérios de sucesso**: Você completou a funcionalidade de ideia a commit usando o Copilot CLI, incluindo planejamento, implementação, testes, documentação e revisão. + +> 💡 **Bônus**: Se você tem agentes configurados do Capítulo 04, tente criar e usar agentes personalizados. Por exemplo, um agente error-handler para revisão de implementação e um agente doc-writer para a atualização do README. + +
+💡 Dicas (clique para expandir) + +**Siga o padrão do exemplo ["De Ideia a PR Mesclado"](#idea-to-merged-pr-in-one-session)** no início deste capítulo. Os passos principais são: + +1. Reunir contexto com `@samples/book-app-project/books.py` +2. Planejar com `/plan Add a "search by year" command` +3. Implementar o método e o manipulador de comando +4. Gerar testes com casos extremos (entrada inválida, resultados vazios, faixa invertida) +5. Revisar com `/review` +6. Atualizar README com `@samples/book-app-project/README.md` +7. Gerar mensagem de commit com `-p` + +**Casos extremos para pensar:** +- E se o usuário inserir "2000" e "1990" (faixa invertida)? +- E se nenhum livro corresponder à faixa? +- E se o usuário inserir entrada não numérica? + +**O importante é praticar o fluxo de trabalho completo** de ideia → contexto → plano → implementar → testar → documentar → commit. + +
+ +--- + +
+🔧 Erros Comuns (clique para expandir) + +| Erro | O que Acontece | Solução | +|------|----------------|---------| +| Pular direto para a implementação | Perder problemas de design que são custosos para corrigir depois | Use `/plan` primeiro para pensar sobre a abordagem | +| Usar uma ferramenta quando múltiplas ajudariam | Resultados mais lentos e menos completos | Combine: Agente para análise → Skill para execução → MCP para integração | +| Não revisar antes de commitar | Problemas de segurança ou bugs passam despercebidos | Sempre execute `/review` ou use um [hook de pré-commit](#workflow-2-code-review-automation-optional) | +| Esquecer de compartilhar fluxos de trabalho com a equipe | Cada pessoa reinventa a roda | Documente padrões em agentes, skills e instruções compartilhadas | + +
+ +--- + +# Resumo + +## 🔑 Principais Aprendizados + +1. **Integração > Isolamento**: Combine ferramentas para máximo impacto +2. **Contexto primeiro**: Sempre reúna o contexto necessário antes da análise +3. **Agentes analisam, Skills executam**: Use a ferramenta certa para o trabalho +4. **Automatize a repetição**: Hooks e scripts multiplicam sua eficácia +5. **Documente fluxos de trabalho**: Padrões compartilháveis beneficiam toda a equipe + +> 📋 **Referência rápida**: Veja a [referência de comandos do GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference) para uma lista completa de comandos e atalhos. + +--- + +## 🎓 Curso Concluído! + +Parabéns! Você aprendeu: + +| Capítulo | O que Você Aprendeu | +|----------|---------------------| +| 00 | Instalação do Copilot CLI e Início Rápido | +| 01 | Três modos de interação | +| 02 | Gerenciamento de contexto com sintaxe @ | +| 03 | Fluxos de trabalho de desenvolvimento | +| 04 | Agentes especializados | +| 05 | Skills extensíveis | +| 06 | Conexões externas com MCP | +| 07 | Fluxos de trabalho de produção unificados | + +Você agora está equipado para usar o GitHub Copilot CLI como um verdadeiro multiplicador de força no seu fluxo de trabalho de desenvolvimento. + +## ➡️ O Que Vem a Seguir + +Seu aprendizado não para aqui: + +1. **Pratique diariamente**: Use o Copilot CLI para trabalho real +2. **Construa ferramentas personalizadas**: Crie agentes e skills para suas necessidades específicas +3. **Compartilhe conhecimento**: Ajude sua equipe a adotar esses fluxos de trabalho +4. **Mantenha-se atualizado**: Acompanhe as atualizações do GitHub Copilot para novos recursos + +### Recursos + +- [Documentação do GitHub Copilot CLI](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) +- [Registro de Servidores MCP](https://github.com/modelcontextprotocol/servers) +- [Skills da Comunidade](https://github.com/topics/copilot-skill) + +--- + +**Ótimo trabalho! Agora vá construir algo incrível.** + +**[← Voltar ao Capítulo 06](../06-mcp-servers/README.md)** | **[Retornar ao Início do Curso →](../README.md)** diff --git a/localization/pt-br/README.md b/localization/pt-br/README.md new file mode 100644 index 00000000..5977fcb7 --- /dev/null +++ b/localization/pt-br/README.md @@ -0,0 +1,110 @@ +![GitHub Copilot CLI for Beginners](../../images/copilot-banner.png) + +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](../../LICENSE)  +[![Abrir projeto no 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)  +[![Documentação oficial do 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)  +[![Entre na comunidade AI Foundry no Discord](https://img.shields.io/badge/Discord-AI_Community-blue?style=flat-square&logo=discord&color=5865f2&logoColor=fff)](https://aka.ms/foundry/discord) + +🎯 [O que você vai aprender](#o-que-você-vai-aprender)   ✅ [Pré-requisitos](#pré-requisitos)   🤖 [Família Copilot](#entendendo-a-família-github-copilot)   📚 [Estrutura do curso](#estrutura-do-curso)   📋 [Referência de comandos](#-referência-de-comandos-do-github-copilot-cli) + +# GitHub Copilot CLI para Iniciantes + +> **✨ Aprenda a turbinar seu fluxo de trabalho de desenvolvimento com assistência de linha de comando movida por IA.** + +O GitHub Copilot CLI traz a assistência de IA diretamente para o seu terminal. Em vez de alternar para um navegador ou editor de código, você pode fazer perguntas, gerar aplicações completas, revisar código, gerar testes e depurar problemas sem sair da linha de comando. + +Pense nisso como ter um colega experiente disponível 24 horas por dia, 7 dias por semana, que pode ler o seu código, explicar padrões confusos e ajudar você a trabalhar mais rápido! + +> 📘 **Prefere uma experiência web?** Você pode seguir este curso aqui mesmo no GitHub, ou visualizá-lo no [Awesome Copilot](https://awesome-copilot.github.com/learning-hub/cli-for-beginners/) para uma experiência de navegação mais tradicional. + +Este curso é indicado para: + +- **Desenvolvedores de software** que querem usar IA a partir da linha de comando +- **Usuários de terminal** que preferem fluxos de trabalho orientados ao teclado em vez de integrações com IDEs +- **Equipes que desejam padronizar** práticas de revisão de código e desenvolvimento assistido por IA + + + + GitHub Copilot Dev Days - Encontre ou organize um evento + + + +## 🎯 O que você vai aprender + +Este curso prático leva você do zero à produtividade com o GitHub Copilot CLI. Você trabalhará com um único aplicativo Python de coleção de livros ao longo de todos os capítulos, melhorando-o progressivamente com fluxos de trabalho assistidos por IA. Ao final, você usará IA com confiança para revisar código, gerar testes, depurar problemas e automatizar fluxos de trabalho — tudo pelo seu terminal. + +**Nenhuma experiência com IA é necessária.** Se você sabe usar um terminal, você pode aprender isso. + +**Ideal para:** Desenvolvedores, estudantes e qualquer pessoa com experiência em desenvolvimento de software. + +## ✅ Pré-requisitos + +Antes de começar, certifique-se de ter: + +- **Conta no GitHub**: [Crie uma gratuitamente](https://github.com/signup)
+- **Acesso ao GitHub Copilot**: [Plano gratuito](https://github.com/features/copilot/plans), [Assinatura mensal](https://github.com/features/copilot/plans) ou [Gratuito para estudantes/professores](https://education.github.com/pack)
+- **Noções básicas de terminal**: Familiaridade com `cd`, `ls` e execução de comandos + +## 🤖 Entendendo a família GitHub Copilot + +O GitHub Copilot evoluiu para uma família de ferramentas com IA. Veja onde cada uma delas opera: + +| Produto | Onde é executado | Descrição | +|---------|-----------------|-----------| +| [**GitHub Copilot CLI**](https://docs.github.com/copilot/how-tos/copilot-cli/cli-getting-started)
(este curso) | Seu terminal | Assistente de codificação com IA nativo do terminal | +| [**GitHub Copilot**](https://docs.github.com/copilot) | VS Code, Visual Studio, JetBrains, etc. | Modo agente, chat, sugestões inline | +| [**Copilot no GitHub.com**](https://github.com/copilot) | GitHub | Chat imersivo sobre seus repositórios, criação de agentes e muito mais | +| [**Agente de nuvem GitHub Copilot**](https://docs.github.com/copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks) | GitHub | Atribua issues a agentes e receba PRs de volta | + +Este curso tem foco no **GitHub Copilot CLI**, levando a assistência de IA diretamente para o seu terminal. + +## 📚 Estrutura do curso + +![Trilha de aprendizado do GitHub Copilot CLI](../../images/learning-path.png) + +| Capítulo | Título | O que você vai construir | +|:--------:|--------|--------------------------| +| 00 | 🚀 [Início Rápido](./00-quick-start/README.md) | Instalação e verificação | +| 01 | 👋 [Primeiros Passos](./01-setup-and-first-steps/README.md) | Demos ao vivo + três modos de interação | +| 02 | 🔍 [Contexto e Conversas](./02-context-conversations/README.md) | Análise de projetos com múltiplos arquivos | +| 03 | ⚡ [Fluxos de Trabalho de Desenvolvimento](./03-development-workflows/README.md) | Revisão de código, depuração, geração de testes | +| 04 | 🤖 [Crie Assistentes de IA Especializados](./04-agents-custom-instructions/README.md) | Agentes personalizados para o seu fluxo de trabalho | +| 05 | 🛠️ [Automatize Tarefas Repetitivas](./05-skills/README.md) | Skills que carregam automaticamente | +| 06 | 🔌 [Conecte ao GitHub, Bancos de Dados e APIs](./06-mcp-servers/README.md) | Integração com servidores MCP | +| 07 | 🎯 [Juntando Tudo](./07-putting-it-together/README.md) | Fluxos de trabalho completos de funcionalidades | + +## 📖 Como este curso funciona + +Cada capítulo segue o mesmo padrão: + +1. **Analogia com o mundo real**: Entenda o conceito por meio de comparações familiares +2. **Conceitos fundamentais**: Aprenda o conhecimento essencial +3. **Exemplos práticos**: Execute comandos reais e veja os resultados +4. **Atividade**: Pratique o que aprendeu +5. **O que vem a seguir**: Prévia do próximo capítulo + +**Os exemplos de código são executáveis.** Todos os blocos de código de copilot neste curso podem ser copiados e executados no seu terminal. + +## 📋 Referência de comandos do GitHub Copilot CLI + +A **[referência de comandos do GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference)** ajuda você a encontrar comandos e atalhos de teclado para usar o Copilot CLI com eficiência. + +## 🙋 Obtendo ajuda + +- 🐛 **Encontrou um bug?** [Abra uma issue](https://github.com/github/copilot-cli-for-beginners/issues) +- 📚 **Documentação oficial:** [Documentação do GitHub Copilot CLI](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) + +## Contribuindo + +> **Observação**: O código usado no curso foi projetado para gerar tipos específicos de saída durante revisões, explicações e depuração, portanto não podemos aceitar PRs que alterem o código existente. + +**Como contribuir:** + +1. Faça um fork deste repositório e clone-o na sua máquina +2. Crie uma branch de funcionalidade (`git checkout -b minha-melhoria`) +3. Faça suas alterações +4. Envie um pull request + +## Licença + +Este projeto está licenciado nos termos da licença MIT de código aberto. Consulte o arquivo [LICENSE](../../LICENSE) para ver os termos completos. diff --git a/localization/pt-br/appendices/README.md b/localization/pt-br/appendices/README.md new file mode 100644 index 00000000..19214ad7 --- /dev/null +++ b/localization/pt-br/appendices/README.md @@ -0,0 +1,12 @@ +# Apêndices + +Esses apêndices cobrem tópicos adicionais que ampliam o conteúdo principal do curso. São leituras opcionais para quando você precisar dessas capacidades específicas. + +| Apêndice | Descrição | Pré-requisito | +|----------|-----------|---------------| +| [Recursos Adicionais de Contexto](additional-context.md) | Trabalhando com imagens e permissões em múltiplos diretórios | Capítulo 02 | +| [Integração CI/CD](ci-cd-integration.md) | Fluxos de trabalho do GitHub Actions para revisões automatizadas | Capítulo 07 | + +--- + +**[← Retornar ao Início do Curso](../README.md)** diff --git a/localization/pt-br/appendices/additional-context.md b/localization/pt-br/appendices/additional-context.md new file mode 100644 index 00000000..d0d51744 --- /dev/null +++ b/localization/pt-br/appendices/additional-context.md @@ -0,0 +1,140 @@ +# Recursos Adicionais de Contexto + +> 📖 **Pré-requisito**: Complete o [Capítulo 02: Contexto e Conversas](../02-context-conversations/README.md) antes de ler este apêndice. + +Este apêndice cobre dois recursos adicionais de contexto: trabalho com imagens e gerenciamento de permissões em múltiplos diretórios. + +--- + +## Trabalhando com Imagens + +Você pode incluir imagens nas suas conversas usando a sintaxe `@`. O Copilot pode analisar capturas de tela, mockups, diagramas e outros conteúdos visuais. + +### Referência Básica de Imagem + +```bash +copilot + +> @screenshot.png What's happening in this UI? + +# O Copilot analisa a imagem e responde + +> @mockup.png @current-design.png Compare these two designs + +# Você também pode arrastar e soltar imagens ou colar da área de transferência +``` + +### Formatos de Imagem Suportados + +| Formato | Melhor Para | +|---------|------------| +| PNG | Capturas de tela, mockups de UI, diagramas | +| JPG/JPEG | Fotos, imagens complexas | +| GIF | Diagramas simples (apenas primeiro quadro) | +| WebP | Capturas de tela web | + +### Casos de Uso Práticos de Imagem + +**1. Depuração de UI** +```bash +> @bug-screenshot.png The button doesn't align properly. What CSS might cause this? +``` + +**2. Implementação de Design** +```bash +> @figma-export.png Write the HTML and Tailwind CSS to match this design +``` + +**3. Análise de Erros** +```bash +> @error-screenshot.png What does this error mean and how do I fix it? +``` + +**4. Revisão de Arquitetura** +```bash +> @whiteboard-diagram.png Convert this architecture diagram to a Mermaid diagram I can put in docs +``` + +**5. Comparação Antes/Depois** +```bash +> @before.png @after.png What changed between these two versions of the UI? +``` + +### Combinando Imagens com Código + +As imagens se tornam ainda mais poderosas quando combinadas com contexto de código: + +```bash +copilot + +> @screenshot-of-bug.png @src/components/Header.jsx +> The header looks wrong in the screenshot. What's causing it in the code? +``` + +### Dicas para Imagens + +- **Recorte capturas de tela** para mostrar apenas as partes relevantes (economiza tokens de contexto) +- **Use alto contraste** para elementos de UI que você deseja analisar +- **Anote se necessário** - circule ou destaque áreas problemáticas antes de fazer upload +- **Uma imagem por conceito** - múltiplas imagens funcionam, mas seja focado + +--- + +## Padrões de Permissão + +Por padrão, o Copilot pode acessar arquivos no seu diretório atual. Para arquivos em outros locais, você precisa conceder acesso. + +### Adicionar Diretórios + +```bash +# Adicionar um diretório à lista permitida +copilot --add-dir /path/to/other/project + +# Adicionar múltiplos diretórios +copilot --add-dir ~/workspace --add-dir /tmp +``` + +### Permitir Todos os Caminhos + +```bash +# Desabilitar restrições de caminho completamente (use com cautela) +copilot --allow-all-paths +``` + +### Dentro de uma Sessão + +```bash +copilot + +> /add-dir /path/to/other/project +# Agora você pode referenciar arquivos desse diretório + +> /list-dirs +# Ver todos os diretórios permitidos + +> /yolo +# Alias rápido para /allow-all ativado — aprova automaticamente todos os prompts de permissão +``` + +### Para Automação + +```bash +# Permitir todas as permissões para scripts não interativos +copilot -p "Review @src/" --allow-all + +# Ou use o alias memorável +copilot -p "Review @src/" --yolo +``` + +### Quando Você Precisa de Acesso a Múltiplos Diretórios + +Cenários comuns onde você precisará dessas permissões: + +1. **Trabalho em monorepo** - Comparar código entre pacotes +2. **Refatoração entre projetos** - Atualizar bibliotecas compartilhadas +3. **Projetos de documentação** - Referenciar múltiplas bases de código +4. **Trabalho de migração** - Comparar implementações antigas e novas + +--- + +**[← Voltar ao Capítulo 02](../02-context-conversations/README.md)** | **[Retornar aos Apêndices](README.md)** diff --git a/localization/pt-br/appendices/ci-cd-integration.md b/localization/pt-br/appendices/ci-cd-integration.md new file mode 100644 index 00000000..146d5b8d --- /dev/null +++ b/localization/pt-br/appendices/ci-cd-integration.md @@ -0,0 +1,199 @@ +# Integração CI/CD + +> 📖 **Pré-requisito**: Complete o [Capítulo 07: Colocando Tudo Junto](../07-putting-it-together/README.md) antes de ler este apêndice. +> +> ⚠️ **Este apêndice é para equipes com pipelines CI/CD existentes.** Se você é novo em GitHub Actions ou conceitos de CI/CD, comece com a abordagem mais simples de hook de pré-commit na seção [Automação de Revisão de Código](../07-putting-it-together/README.md#workflow-3-code-review-automation-optional) do Capítulo 07. + +Este apêndice mostra como integrar o GitHub Copilot CLI em seus pipelines CI/CD para revisão automatizada de código em pull requests. + +--- + +## Fluxo de Trabalho do GitHub Actions + +Este fluxo de trabalho revisa automaticamente os arquivos alterados quando um pull request é aberto ou atualizado: + +```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 # Necessário para comparar com a branch main + + - name: Install Copilot CLI + run: npm install -g @github/copilot + + - name: Review Changed Files + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Obter lista de arquivos JS/TS alterados + 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 + + # Usar --silent para suprimir saída de progresso + 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'); + + // Só publicar se houver conteúdo significativo + 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'); + } +``` + +--- + +## Opções de Configuração + +### Limitando o Escopo da Revisão + +Você pode focar a revisão em tipos específicos de problemas: + +```yaml +# Revisão apenas de segurança +copilot --allow-all -p "Security review of @$file. Check for: SQL injection, XSS, hardcoded secrets, authentication issues." --silent + +# Revisão apenas de performance +copilot --allow-all -p "Performance review of @$file. Check for: N+1 queries, memory leaks, blocking operations." --silent +``` + +### Tratando PRs Grandes + +Para PRs com muitos arquivos, considere agrupar ou limitar: + +```yaml +# Limitar aos primeiros 10 arquivos +FILES=$(git diff --name-only origin/main...HEAD | grep -E '\.(js|ts)$' | head -10) + +# Ou definir um timeout por arquivo +timeout 60 copilot --allow-all -p "Review @$file" --silent || echo "Review timed out" +``` + +### Configuração da Equipe + +Para revisões consistentes em toda a equipe, crie uma configuração compartilhada: + +```json +// .copilot/config.json (commitado no repositório) +{ + "model": "claude-sonnet-4.5", + "permissions": { + "allowedPaths": ["src/**/*", "tests/**/*"], + "deniedPaths": [".env*", "secrets/**/*", "*.min.js"] + } +} +``` + +--- + +## Alternativa: Bot de Revisão de PR + +Para fluxos de trabalho de revisão mais sofisticados, considere usar o agente de nuvem do GitHub Copilot: + +```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]'] + }); +``` + +--- + +## Melhores Práticas para Integração CI/CD + +1. **Use a flag `--silent`** - Suprime a saída de progresso para logs mais limpos +2. **Defina timeouts** - Evite que revisões travadas bloqueiem seu pipeline +3. **Filtre tipos de arquivo** - Revise apenas arquivos relevantes (ignore código gerado, dependências) +4. **Consciência sobre limites de taxa** - Espaçe as revisões para PRs grandes +5. **Falhe graciosamente** - Não bloqueie merges em falhas de revisão; registre e continue + +--- + +## Solução de Problemas + +### "Authentication failed" no CI + +Certifique-se de que seu fluxo de trabalho tem as permissões corretas: + +```yaml +permissions: + contents: read + pull-requests: write + issues: write +``` + +### Revisões com timeout + +Aumente o timeout ou reduza o escopo: + +```bash +timeout 120 copilot --allow-all -p "Quick review of @$file - critical issues only" --silent +``` + +### Limites de token em arquivos grandes + +Ignore arquivos muito grandes: + +```bash +if [ $(wc -l < "$file") -lt 500 ]; then + copilot --allow-all -p "Review @$file" --silent +else + echo "Skipping $file (too large)" +fi +``` + +--- + +**[← Voltar ao Capítulo 07](../07-putting-it-together/README.md)** | **[Retornar aos Apêndices](README.md)** diff --git a/localization/zh-cn/00-quick-start/README.md b/localization/zh-cn/00-quick-start/README.md new file mode 100644 index 00000000..c5539094 --- /dev/null +++ b/localization/zh-cn/00-quick-start/README.md @@ -0,0 +1,290 @@ +![第 00 章:快速开始](../../../00-quick-start/images/chapter-header.png) + +欢迎!在本章中,你将完成 GitHub Copilot CLI(命令行界面)的安装、使用 GitHub 账号登录,并验证一切是否正常工作。这是一个快速安装章节。一旦你准备就绪,真正的演示将从第 01 章开始! + +## 🎯 学习目标 + +学完本章后,你将完成: + +- 安装 GitHub Copilot CLI +- 使用 GitHub 账号登录 +- 通过一个简单的测试验证它可以正常工作 + +> ⏱️ **预计耗时**:约 10 分钟(5 分钟阅读 + 5 分钟实操) + +--- + +## ✅ 先决条件 + +- **GitHub 账号** 并具有 Copilot 访问权限。[查看订阅选项](https://github.com/features/copilot/plans)。学生/教师可通过 [GitHub Education 免费访问 Copilot Pro](https://education.github.com/pack)。 +- **终端基础**:能够熟练使用 `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”,则需要使用免费方案、订阅一个套餐,或者加入一个为你提供访问权限的组织。 + +--- + +## 安装 + +> ⏱️ **预计耗时**:安装大约需要 2-5 分钟,认证再额外花费 1-2 分钟。 + +### GitHub Codespaces(无需任何配置) + +如果你不想在本机安装任何先决条件,可以使用 GitHub Codespaces,其中已经为你准备好了 GitHub Copilot CLI(仍需登录),并预装了 Python 和 pytest。 + +1. [Fork 本仓库](https://github.com/github/copilot-cli-for-beginners/fork) 到你的 GitHub 账号 +2. 选择 **Code** > **Codespaces** > **Create codespace on main** +3. 等待几分钟让容器构建完成 +4. 万事俱备!终端会在 Codespace 环境中自动打开。 + +> 💡 **在 Codespace 中验证**:运行 `cd samples/book-app-project && python book_app.py help`,确认 Python 与示例应用都能正常工作。 + +### 本地安装 + +如果你想在本机运行 Copilot CLI 并使用课程示例,请按以下步骤操作。 + +1. 克隆仓库以获取课程示例: + + ```bash + git clone https://github.com/github/copilot-cli-for-beginners + cd copilot-cli-for-beginners + ``` + +2. 选择以下任一方式安装 Copilot CLI。 + + > 💡 **不知道选哪个?** 如果你已经安装了 Node.js,使用 `npm` 是最快的方式。否则,请选择适合你系统的安装方式。 + + ### 全平台(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(安装脚本) + + ```bash + curl -fsSL https://gh.io/copilot-install | bash + ``` + +
+可选:启用 shell tab 自动补全 + +Shell tab 自动补全可以让你按下 **Tab** 键来补全 `copilot` 子命令、命令选项以及部分选项的取值。这是可选项,但当你熟悉 CLI 后会非常方便。 + +Copilot CLI 目前支持 Bash、Zsh 和 Fish 的补全脚本: + +```shell +# Bash, current session only +source <(copilot completion bash) + +# Bash, persistent on Linux +copilot completion bash | sudo tee /etc/bash_completion.d/copilot + +# Zsh +copilot completion zsh > "${fpath[1]}/_copilot" + +# Fish +copilot completion fish > ~/.config/fish/completions/copilot.fish +``` + +添加持久化补全后,请重启你的 shell。在 Windows 上可以使用 PowerShell 来运行 Copilot CLI,但 `copilot completion` 目前仅支持 Bash、Zsh 和 Fish。 + +
+ +--- + +## 认证 + +在 `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 即完成认证。* + +**提示**:登录状态会跨会话保留。除非令牌过期或你显式登出,否则你只需要登录一次。 + +--- + +## 验证它是否可用 + +### 步骤 1:测试 Copilot CLI + +既然你已经登录,让我们来验证 Copilot CLI 是否正常工作。在终端中,如果你尚未启动 CLI,请先启动它: + +```bash +> Say hello and tell me what you can help with +``` + +收到响应后,你可以退出 CLI: + +```bash +> /exit +``` + +--- + +
+🎬 看看实际效果! + +![Hello 演示](../../../00-quick-start/images/hello-demo.gif) + +*演示输出会有所不同。你的模型、工具和响应可能会与此处展示的内容不一样。* + +
+ +--- + +**预期输出**:一个友好的回复,列出 Copilot CLI 的能力。 + +### 步骤 2:运行示例图书应用 + +本课程提供了一个示例应用,你将在整个课程中通过 CLI 不断探索并改进它(你可以在 /samples/book-app-project 中查看代码)。在开始之前,先确认这个 *Python 图书收藏终端应用* 能正常运行。请根据你的系统使用 `python` 或 `python3`。 + +> **注意:** 课程中展示的主要示例使用的是 Python(`samples/book-app-project`),因此如果你选择本地方式,需要确保本机已安装 [Python 3.10+](https://www.python.org/downloads/)(Codespace 已经预装好了)。如果你更习惯使用其他语言,也可以使用 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”。 + +### 步骤 3:在图书应用上试用 Copilot CLI + +如果你刚执行完步骤 2,先回到仓库根目录: + +```bash +cd ../.. # Back to the repository root if needed +copilot +> What does @samples/book-app-project/book_app.py do? +``` + +**预期输出**:一段对该图书应用主要函数与命令的总结。 + +如果出现错误,请查看下方的 [故障排查部分](#troubleshooting)。 + +完成后,你可以退出 Copilot CLI: + +```bash +> /exit +``` + +--- + +## ✅ 你已准备就绪! + +安装部分到此结束。真正的乐趣从第 01 章开始,在那里你将: + +- 看着 AI 审查图书应用,瞬间发现代码质量问题 +- 学习使用 Copilot CLI 的三种不同方式 +- 用普通英语生成可运行的代码 + +**[继续学习第 01 章:初步上手 →](../01-setup-and-first-steps/README.md)** + +--- + +## 故障排查 + +### “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),并输入终端中显示的验证码。 + +### 令牌过期 + +只需再次运行 `/login`: + +```bash +copilot +> /login +``` + +### 仍然卡住? + +- 查阅 [GitHub Copilot CLI 文档](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) +- 在 [GitHub Issues](https://github.com/github/copilot-cli/issues) 中搜索 + +--- + +## 🔑 关键要点 + +1. **GitHub Codespace 是快速上手的好方式** —— Python、pytest 和 GitHub Copilot CLI 都已预装好,你可以直接进入演示 +2. **多种安装方式** —— 选择适合你系统的方式(Homebrew、WinGet、npm 或安装脚本) +3. **一次性认证** —— 登录会一直保留,直到令牌过期 +4. **图书应用可以正常运行** —— 你将在整个课程中使用 `samples/book-app-project` + +> 📚 **官方文档**:[安装 Copilot CLI](https://docs.github.com/copilot/how-tos/copilot-cli/cli-getting-started),了解安装选项和系统要求。 + +> 📋 **快速参考**:参见 [GitHub Copilot CLI 命令参考文档](https://docs.github.com/en/copilot/reference/cli-command-reference),获取完整的命令与快捷键列表。 + +--- + +**[继续学习第 01 章:初步上手 →](../01-setup-and-first-steps/README.md)** diff --git a/localization/zh-cn/01-setup-and-first-steps/README.md b/localization/zh-cn/01-setup-and-first-steps/README.md new file mode 100644 index 00000000..7809c544 --- /dev/null +++ b/localization/zh-cn/01-setup-and-first-steps/README.md @@ -0,0 +1,690 @@ +![第 01 章:第一步](../../../01-setup-and-first-steps/images/chapter-header.png) + +> **看看 AI 如何瞬间发现 bug、解释令人困惑的代码、生成可用的脚本。然后学习使用 GitHub Copilot CLI 的三种不同方式。** + +本章是魔法开始的地方!你将亲身体验为什么开发者把 GitHub Copilot CLI 形容为「随时能拨通的资深工程师」。你将看到 AI 在几秒钟内找出安全漏洞,用通俗的语言解释复杂的代码,并即时生成可用的脚本。然后你将掌握三种交互模式(Interactive、Plan 和 Programmatic),让你清楚地知道任何任务该使用哪一种。 + +> ⚠️ **前置条件**:请确保你已经完成了 **[第 00 章:快速入门](../00-quick-start/README.md)**。在运行下面的演示之前,你需要先安装并完成 GitHub Copilot CLI 的身份认证。 + +## 🎯 学习目标 + +学完本章后,你将能够: + +- 通过实操演示亲身感受 GitHub Copilot CLI 带来的生产力提升 +- 为任何任务选择正确的模式(Interactive、Plan 或 Programmatic) +- 使用斜杠命令来控制你的会话 + +> ⏱️ **预计时间**:约 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:几秒钟完成代码评审 + +本课程包含了一些有意保留代码质量问题的示例文件。如果你在本地机器上工作并且尚未克隆仓库,请运行下面的 `git clone` 命令,进入 `copilot-cli-for-beginners` 文件夹,然后运行 `copilot` 命令。 + +```bash +# Clone the course repository if you're working locally and haven't already +git clone https://github.com/github/copilot-cli-for-beginners +cd copilot-cli-for-beginners + +# Start Copilot +copilot +``` + +进入 Copilot CLI 交互式会话后,运行以下命令: + +``` +> Review @samples/book-app-project/book_app.py for code quality issues and suggest improvements +``` + +> 💡 **`@` 符号是干什么用的?** `@` 符号告诉 Copilot CLI 去读取一个文件。你将在第 02 章详细学习它。现在,只需完全照抄上面的命令即可。 + +--- + +
+🎬 看看实际效果! + +![代码评审演示](../../../01-setup-and-first-steps/images/code-review-demo.gif) + +*演示输出会有所不同。你的模型、工具和回复都会与此处展示的不同。* + +
+ +--- + +**收获**:几秒钟就完成了一次专业的代码评审。手动评审会花费……嗯……远比这多得多的时间! + +--- + +### 演示 2:解释令人困惑的代码 + +有没有盯着代码搞不懂它到底在做什么的经历?在你的 Copilot CLI 会话中试试这个: + +``` +> Explain what @samples/book-app-project/books.py does in simple terms +``` + +--- + +
+🎬 看看实际效果! + +![解释代码演示](../../../01-setup-and-first-steps/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 +``` + +--- + +
+🎬 看看实际效果! + +![生成代码演示](../../../01-setup-and-first-steps/images/generate-code-demo.gif) + +*演示输出会有所不同。你的模型、工具和回复都会与此处展示的不同。* + +
+ +--- + +**会发生什么**:几秒钟内就得到一个完整、可用的函数,可以直接复制粘贴运行。 + +探索完毕后,退出会话: + +``` +> /exit +``` + +**收获**:即时获得满足感,而且整个过程你都在同一个连续的会话中。 + +--- + +# 模式与命令 + +未来感十足的控制面板,有发光的屏幕、旋钮和均衡器,代表 Copilot CLI 的模式和命令 + +你已经看到了 Copilot CLI 能做什么。现在让我们了解*如何*高效地使用这些能力。关键是要知道在不同情境下应该使用三种交互模式中的哪一种。 + +> 💡 **注意**:Copilot CLI 还有一个 **Autopilot** 模式,它会自动完成任务而无需等待你的输入。它很强大,但需要授予完整的权限,并会自动消耗 premium 请求额度。本课程聚焦于下面的三种模式。等你熟悉了基础知识后,我们会指引你了解 Autopilot。 + +--- + +## 🧩 现实类比:外出就餐 + +把使用 GitHub Copilot CLI 想象成一次外出就餐。从规划行程到点单,不同的情境需要不同的方式: + +| 模式 | 就餐类比 | 何时使用 | +|------|----------------|-------------| +| **Plan** | 去餐厅的 GPS 路线 | 复杂任务——先规划路线、检查每一站、达成共识,然后再开车 | +| **Interactive** | 与服务员交谈 | 探索和迭代——提问、定制、获得实时反馈 | +| **Programmatic** | 得来速点单 | 快速、明确的任务——留在你的环境里,快速拿到结果 | + +就像外出就餐一样,你会自然而然地学会什么时候用哪种方式最合适。 + +使用 GitHub Copilot CLI 的三种方式 - Plan 模式(去餐厅的 GPS 路线)、Interactive 模式(与服务员交谈)、Programmatic 模式(得来速) + +*根据任务选择你的模式:Plan 用于先规划,Interactive 用于来回协作,Programmatic 用于快速一次性结果* + +### 我应该从哪种模式开始? + +**从 Interactive 模式开始。** +- 你可以做实验、提出后续问题 +- 上下文通过对话自然地积累 +- 出错时使用 `/clear` 就能轻松纠正 + +熟悉之后,再尝试: +- **Programmatic 模式**(`copilot -p ""`)用于快速的一次性问题 +- **Plan 模式**(`/plan`)当你在编码前需要更详细地规划事情时 + +--- + +## 三种模式 + +### 模式 1:Interactive 模式(从这里开始) + +Interactive 模式 - 就像和能回答问题、调整订单的服务员交谈 + +**最适合**:探索、迭代、多轮对话。就像和一个能回答问题、接受反馈、随时调整订单的服务员交谈。 + +启动一个交互式会话: + +```bash +copilot +``` + +正如你目前所看到的,你会看到一个提示符,可以在那里自然地输入。要查看可用命令的帮助,只需输入: + +``` +> /help +``` + +**关键洞察**:Interactive 模式会保持上下文。每条消息都建立在前面的内容之上,就像真实的对话一样。 + +#### Interactive 模式示例 + +```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:Plan 模式 + +Plan 模式 - 就像出行前用 GPS 规划路线 + +**最适合**:复杂任务,你希望在执行前先审视一下方案。类似于出行前用 GPS 规划路线。 + +Plan 模式帮助你在编写任何代码之前先制定一个分步计划。使用 `/plan` 命令,按 **Shift+Tab** 切换进入 Plan 模式: + +```bash +copilot + +> /plan Add a "mark as read" command to the book app +``` + +> 💡 **小技巧**:**Shift+Tab** 在以下模式之间循环切换:Interactive → Plan → Autopilot。在交互式会话中按下它即可切换模式,无需输入命令。 + +你也可以使用 `--plan` 标志直接以 Plan 模式启动 Copilot CLI: + +```bash +copilot --plan +``` + +**Plan 模式输出:**(你的输出可能会有所不同) + +``` +📋 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] +``` + +**关键洞察**:Plan 模式让你在编写任何代码之前都能审阅并修改方案。计划完成后,你甚至可以让 Copilot CLI 把它保存到一个文件中以备后用。例如,「Save this plan to `mark_as_read_plan.md`」会创建一个包含计划详情的 markdown 文件。 + +> 💡 **想试更复杂的?** 试试:`/plan Add search and filter capabilities to the book app`。Plan 模式可以从简单功能扩展到完整应用。 + +> 📚 **Autopilot 模式**:你可能已经注意到 Shift+Tab 会切换到第三种模式 **Autopilot**。在 autopilot 模式下,Copilot 会自动完成整个计划,每一步之后都不需要等待你的输入——就像把一个任务交给同事说「完成后告诉我」。典型的工作流是 plan → 接受 → autopilot,这意味着你需要先擅长写计划。你也可以用 `copilot --autopilot` 直接启动到 autopilot。先熟悉 Interactive 和 Plan 模式,准备好后再查看[官方文档](https://docs.github.com/copilot/concepts/agents/copilot-cli/autopilot)。 + +--- + +### 模式 3:Programmatic 模式 + +Programmatic 模式 - 就像使用得来速进行快速点单 + +**最适合**:自动化、脚本、CI/CD、单次执行的命令。就像使用得来速进行快速点单,无需与服务员交谈。 + +使用 `-p` 标志执行不需要交互的一次性命令: + +```bash +# Generate code +copilot -p "Write a function that checks if a number is even or odd" + +# Get quick help +copilot -p "How do I read a JSON file in Python?" +``` + +**关键洞察**:Programmatic 模式给你一个快速的答案然后退出。没有对话,只有输入 → 输出。 + +
+📚 更进一步:在脚本中使用 Programmatic 模式(点击展开) + +熟悉后,你可以在 shell 脚本中使用 `-p`: + +```bash +#!/bin/bash + +# Generate commit messages automatically +COMMIT_MSG=$(copilot -p "Generate a commit message for: $(git diff --staged)") +git commit -m "$COMMIT_MSG" + +# Review a file +copilot --allow-all -p "Review @myfile.py for issues" +``` +> ⚠️ **关于 `--allow-all`**:这个标志会跳过所有权限提示,让 Copilot CLI 在不询问的情况下读取文件、运行命令并访问 URL。这对 programmatic 模式(`-p`)是必需的,因为没有交互式会话来批准操作。只在你自己编写的提示词、并且在你信任的目录下使用 `--allow-all`。绝不要将其用于不可信的输入或敏感目录。 + +
+ +--- + +## 必备的斜杠命令 + +这些命令很适合在你刚开始使用 Copilot CLI 时学习: + +| 命令 | 作用 | 何时使用 | +|---------|--------------|-------------| +| `/ask` | 提一个不影响对话历史的快速问题 | 当你想要一个快速答案而不打断当前任务时 | +| `/clear` | 清除对话并重新开始 | 切换话题时 | +| `/help` | 显示所有可用的命令 | 当你忘记某个命令时 | +| `/model` | 显示或切换 AI 模型 | 当你想更换 AI 模型时 | +| `/plan` | 在编码之前规划你的工作 | 用于更复杂的功能 | +| `/research` | 使用 GitHub 和网络资源进行深入研究 | 当你在编码前需要调研某个主题时 | +| `/exit` | 结束会话 | 当你完成时 | + +> 💡 **`/ask` 与常规聊天的区别**:通常你发送的每条消息都会成为正在进行的对话的一部分,并影响后续的回复。`/ask` 是一个「不记录」的快捷方式——非常适合像 `/ask What does YAML mean?` 这样的快速一次性问题,不会污染你的会话上下文。 + +> 💡 **Tab 自动补全**:输入斜杠命令时,按 **Tab** 可以自动补全命令名,或在可用的子命令和参数之间循环。当你记不住命令的确切名称时尤其方便。 + +入门的部分就到这里!等你熟悉之后,可以再探索其他命令。 + +> 📚 **官方文档**:完整的命令和标志列表请见 [CLI command reference](https://docs.github.com/copilot/reference/cli-command-reference)。 + +
+📚 更多命令(点击展开) + +> 💡 上面的必备命令涵盖了你日常使用的大部分场景。这份参考是供你准备好探索更多内容时使用的。 + +### Agent 环境 + +| 命令 | 作用 | +|---------|--------------| +| `/agent` | 浏览并从可用的 agent 中选择 | +| `/env` | 显示已加载的环境详情——哪些指令、MCP 服务器、skills、agents 和插件处于活动状态 | +| `/init` | 为你的仓库初始化 Copilot 指令 | +| `/mcp` | 管理 MCP 服务器配置 | +| `/skills` | 管理用于增强能力的 skills | + +> 💡 Agents 在[第 04 章](../04-agents-custom-instructions/README.md)中介绍,skills 在[第 05 章](../05-skills/README.md)中介绍,MCP 服务器在[第 06 章](../06-mcp-servers/README.md)中介绍。 + +### 模型与子 agent + +| 命令 | 作用 | +|---------|--------------| +| `/delegate` | 把任务交给 GitHub Copilot 云端 agent | +| `/fleet` | 把一个复杂任务拆分为并行子任务以更快完成 | +| `/model` | 显示或切换 AI 模型 | +| `/tasks` | 查看后台子 agent 和分离的 shell 会话 | + +### 代码 + +| 命令 | 作用 | +|---------|--------------| +| `/diff` | 查看当前目录中所做的更改 | +| `/pr` | 对当前分支的 pull request 进行操作 | +| `/research` | 使用 GitHub 和网络资源进行深度研究调查 | +| `/review` | 运行 code-review agent 来分析改动 | +| `/terminal-setup` | 启用多行输入支持(shift+enter 和 ctrl+enter) | + +### 权限 + +| 命令 | 作用 | +|---------|--------------| +| `/add-dir ` | 把一个目录添加到允许列表 | +| `/allow-all [on\|off\|show]` | 自动批准所有权限提示;用 `on` 启用,`off` 禁用,`show` 查看当前状态 | +| `/yolo` | `/allow-all on` 的快捷别名——自动批准所有权限提示。 | +| `/cwd`, `/cd [directory]` | 查看或更改工作目录 | +| `/list-dirs` | 显示所有允许的目录 | + +> ⚠️ **谨慎使用**:`/allow-all` 和 `/yolo` 会跳过确认提示。对受信任的项目很方便,但对不可信的代码要小心。 + +### 会话 + +| 命令 | 作用 | +|---------|--------------| +| `/clear` | 放弃当前会话(不保存历史)并开始一个新对话 | +| `/compact` | 总结对话以减少上下文占用 | +| `/context` | 显示上下文窗口的 token 使用情况和可视化 | +| `/keep-alive` | 在 Copilot CLI 处于活动状态时阻止系统进入睡眠——对在笔记本上运行长时间任务很方便 | +| `/new` | 结束当前会话(保存到历史以供搜索/恢复)并开始一个新对话。 | +| `/resume` | 切换到另一个会话(可选地指定会话 ID 或名称) | +| `/rename` | 重命名当前会话(省略名称即可自动生成一个) | +| `/rewind` | 打开时间线选择器以回滚到对话中较早的任意一个时间点 | +| `/usage` | 显示会话使用指标和统计信息 | +| `/session` | 显示会话信息和工作区摘要;使用 `/session delete`、`/session delete ` 或 `/session delete-all` 来移除会话 | +| `/share` | 把会话导出为 markdown 文件、GitHub gist 或自包含的 HTML 文件 | + +### 显示 + +| 命令 | 作用 | +|---------|--------------| +| `/statusline`(或 `/footer`) | 自定义会话底部状态栏中显示的项目(目录、分支、effort、上下文窗口、配额) | +| `/theme` | 查看或设置终端主题 | + +### 帮助与反馈 + +| 命令 | 作用 | +|---------|--------------| +| `/changelog` | 显示 CLI 版本的更新日志 | +| `/feedback` | 向 GitHub 提交反馈 | +| `/help` | 显示所有可用的命令 | + +### 快速 shell 命令 + +通过以 `!` 为前缀,可以直接运行 shell 命令而不经过 AI: + +```bash +copilot + +> !git status +# Runs git status directly, bypassing the AI + +> !python -m pytest tests/ +# Runs pytest directly +``` + +### 切换模型 + +Copilot CLI 支持来自 OpenAI、Anthropic、Google 等的多个 AI 模型。你可以使用的模型取决于你的订阅级别和所在地区。使用 `/model` 查看你的选择并在它们之间切换: + +```bash +copilot +> /model + +# Shows available models and lets you pick one. Select Sonnet 4.5. +``` + +> 💡 **小技巧**:有些模型比其他模型消耗更多的「premium 请求」。标记为 **1x** 的模型(如 Claude Sonnet 4.5)是非常好的默认选择。它们既能干又高效。倍率更高的模型会更快地消耗你的 premium 请求配额,所以请把它们留给真正需要的时候。 + +> 💡 **不知道该选哪个模型?** 在模型选择器中选择 **`Auto`**,让 Copilot 为每个会话自动选择最佳的可用模型。如果你刚刚开始且不想费心选择模型,这是一个很好的默认选项。 + +
+ +--- + +# 实践 + +温馨的工作桌面,显示器上是代码,台灯、咖啡杯和耳机已就位,准备开始动手实践 + +是时候把你学到的内容付诸行动了。 + +--- + +## ▶️ 自己动手试试 + +### 交互式探索 + +启动 Copilot 并使用后续提示词来迭代地改进 book app: + +```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 + +# Review the plan +# Approve or modify +# Watch it implement step by step +``` + +### 用 Programmatic 模式实现自动化 + +`-p` 标志让你可以直接从终端运行 Copilot CLI,而不必进入交互模式。从仓库根目录将下面的脚本复制粘贴到你的终端(不要在 Copilot 内部执行),以评审 book app 中的所有 Python 文件。 + +```bash +# Review all Python files in the book app +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 +# Review all Python files in the book app +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` 并探索 book app。围绕 `@samples/book-app-project/books.py` 提问,并连续 3 次请求改进。 + +2. **Plan 模式挑战**:运行 `/plan Add rating and review features to the book app`。仔细阅读这个计划。它合理吗? + +3. **Programmatic 挑战**:运行 `copilot --allow-all -p "List all functions in @samples/book-app-project/book_app.py and describe what each does"`。它第一次运行就成功了吗? + +--- + +## 💡 小技巧:从 Web 或手机控制你的 CLI 会话 + +GitHub Copilot CLI 支持**远程会话**,让你可以从 Web 浏览器(桌面或手机)或 GitHub Mobile app 监控并与正在运行的 CLI 会话交互,而无需亲自坐在终端前。 + +使用 `--remote` 标志启动一个远程会话: + +```bash +copilot --remote +``` + +Copilot CLI 会显示一个链接并提供一个 QR 码。在你的手机上或桌面浏览器标签页中打开该链接,即可实时观看会话、发送后续提示词、审阅计划并远程引导 agent。会话是用户专属的,所以你只能访问自己的 Copilot CLI 会话。 + +你也可以在活动会话内随时启用远程访问: + +``` +> /remote +``` + +关于远程会话的更多详情可在 [Copilot CLI docs](https://docs.github.com/copilot/how-tos/copilot-cli/steer-remotely) 中找到。 + +--- + +## 📝 作业 + +### 主挑战:改进 Book App 工具函数 + +实操示例聚焦于评审和重构 `book_app.py`。现在在另一个文件 `utils.py` 上练习相同的技能: + +1. 启动一个交互式会话:`copilot` +2. 让 Copilot CLI 对该文件做摘要:「Summarize @samples/book-app-project/utils.py and explain what each function in this file does」 +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. **Interactive**:`copilot` → 让它一步步设计和实现该方法 +2. **Plan**:`/plan Add a list_by_year(start, end) method to BookCollection that filters books by publication year range` +3. **Programmatic**:`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?"` | +| 按一次 Esc 来取消正在运行的任务 | 单次 Esc 不再取消正在进行的工作(为防止误操作) | 在 Copilot CLI 处理时按 **两次 Esc** 来取消 | + +### 故障排查 + +**「Model not available」** —— 你的订阅可能不包含所有模型。使用 `/model` 查看可用的模型。 + +**「Context too long」** —— 你的对话已经用满了上下文窗口。使用 `/clear` 重置,或开始一个新会话。 + +**「Rate limit exceeded」** —— 等几分钟后重试。可以考虑使用 programmatic 模式进行带延迟的批量操作。 + +
+ +--- + +# 总结 + +## 🔑 核心要点 + +1. **Interactive 模式**用于探索和迭代——上下文会向前延续。它就像和一个能记住你之前说过什么的人对话。 +2. **Plan 模式**通常用于更复杂的任务。在实现之前先审阅。 +3. **Programmatic 模式**用于自动化。无需交互。 +4. **必备命令**(`/ask`、`/help`、`/clear`、`/plan`、`/research`、`/model`、`/exit`)涵盖了日常使用的大部分场景。 + +> 📋 **快速参考**:完整的命令和快捷键列表请见 [GitHub Copilot CLI command reference](https://docs.github.com/en/copilot/reference/cli-command-reference)。 + +--- + +## ➡️ 下一步 + +现在你已经理解了三种模式,让我们来学习如何向 Copilot CLI 提供关于你代码的上下文。 + +在 **[第 02 章:上下文与对话](../02-context-conversations/README.md)** 中,你将学习: + +- 用于引用文件和目录的 `@` 语法 +- 使用 `--resume` 和 `--continue` 进行会话管理 +- 上下文管理如何让 Copilot CLI 真正变得强大 + +--- + +**[← 返回课程主页](../README.md)** | **[继续到第 02 章 →](../02-context-conversations/README.md)** diff --git a/localization/zh-cn/02-context-conversations/README.md b/localization/zh-cn/02-context-conversations/README.md new file mode 100644 index 00000000..f5f0d318 --- /dev/null +++ b/localization/zh-cn/02-context-conversations/README.md @@ -0,0 +1,908 @@ +![第 02 章:上下文与对话](../../../02-context-conversations/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 +``` + +--- + +
+🎬 看看实际效果! + +![文件上下文演示](../../../02-context-conversations/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 +> ``` + +--- + +
+🎬 看看实际效果! + +![多文件演示](../../../02-context-conversations/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 小时 vs 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 可以基于已经读过的代码进行追踪 +``` + +
+🎬 看看多轮对话的实际效果! + +![多轮对话演示](../../../02-context-conversations/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 + +# 或按你给会话起的名字来恢复 +copilot --resume="my book app review" +``` + +> 💡 **怎么找到会话 ID?** 你不必记住它们。运行 `copilot --resume` 而不带 ID 时,会显示一个交互式列表,列出你之前的会话、它们的名字、ID 以及最近活跃时间。挑一个就行了。 +> +> **多个终端怎么办?** 每个终端窗口都是独立的会话,拥有自己的上下文。如果你在三个终端里打开了 Copilot CLI,那就是三个独立的会话。从任意一个终端运行 `--resume` 都可以浏览全部会话。`--continue` 标志会先抓取当前工作目录下的会话;如果当前目录没有,则选取最近活跃的那个会话。 +> +> **能在不重启的情况下切换会话吗?** 可以。在已激活的会话内使用 `/resume` 斜杠命令: +> ``` +> > /resume +> # 显示可切换到的会话列表 +> ``` + +### 整理你的会话 + +给会话起一个有意义的名字,方便你之后查找。你可以在启动时给会话命名,也可以在会话内随时重命名: + +```bash +# 启动时直接给会话命名 +copilot --name book-app-review + +# 或者在会话内部重命名当前会话 +copilot + +> /rename book-app-review +# 会话已重命名,便于识别 +``` + +会话被命名后,你就可以直接按名字恢复,而无需在列表中翻找: + +```bash +copilot --resume=book-app-review +``` + +要清理你不再需要的会话,请在会话内使用 `/session delete`: + +```bash +copilot + +> /session delete # 删除当前会话 +> /session delete abc123 # 按 ID 删除指定会话 +> /session delete-all # 删除所有会话(请谨慎使用!) +``` + +### 检查并管理上下文 + +随着你不断添加文件和对话,Copilot CLI 的[上下文窗口](../../../GLOSSARY.md#context-window)会逐渐被占满。有几个命令可以帮助你保持掌控: + +```bash +copilot + +> /context +Context usage: 62k/200k tokens (31%) + +> /clear +# 放弃当前会话(不保存历史)并开始一个全新的对话 + +> /new +# 结束当前会话(保存到历史中以便搜索/恢复)并开始一个全新的对话 + +> /rewind +# 打开时间线选择器,让你回滚到对话中的更早某个节点 +``` + +> 💡 **何时使用 `/clear` 或 `/new`**:如果你一直在审查 books.py,想切换到讨论 utils.py,请先运行 /new(如果不需要保留会话历史就用 /clear)。否则旧话题留下的过时上下文可能干扰回答。 + +> 💡 **走错路或想换种方式?** 使用 `/rewind`(或按两次 Esc)打开 **时间线选择器**,让你回滚到对话中的任意更早节点,而不仅仅是最近一次。当你顺着错误的思路走了很远,又不想完全从头开始时,这非常有用。 + +--- + +### 从离开的地方继续 + +时间线展示 GitHub Copilot CLI 会话如何跨天保留 —— 周一开始,周三恢复,全部上下文都已还原 + +*会话在你退出时会自动保存。几天之后恢复时,文件、问题和进度都会被记住。* + +想象一下跨多天的工作流: + +```bash +# 周一:开启一次图书应用审查,并从一开始就给会话命名 +copilot --name 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 --resume=book-app-review + +> 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 仍然记得: +- 你正在处理的具体文件 +- 编号过的问题列表 +- 你已经处理过哪些问题 +- 你们对话的上下文 + +无需重新解释。无需重新读取文件。直接接着干就行。 + +--- + +**🎉 你已经掌握了精华内容!** `@` 语法、会话管理(`--name`/`--continue`/`--resume`/`/rename`)以及上下文命令(`/context`/`/clear`),就足以让你高效地工作。下面的内容都是可选的。等你准备好时再回来看也不迟。 + +--- + +# 可选:深入了解 + +蓝紫色调的抽象水晶洞窟,象征对上下文概念的更深入探索 + +这些主题建立在上文的基础知识之上。**挑你感兴趣的看,或者直接跳到 [实践](#practice)。** + +| 我想了解…… | 跳转到 | +|---|---| +| 通配符模式与高级会话命令 | [更多 @ 模式与会话命令](#additional-patterns) | +| 在多个提示词之间叠加上下文 | [上下文感知对话](#context-aware-conversations) | +| Token 限制与 `/compact` | [理解上下文窗口](#understanding-context-windows) | +| 如何挑选要引用的文件 | [选择要引用的内容](#choosing-what-to-reference) | +| 分析截图和原型图 | [处理图片](#working-with-images) | + +
+更多 @ 模式与会话命令 + + +### 更多 @ 模式 + +对进阶用户,Copilot CLI 支持通配符模式和图片引用: + +| 模式 | 作用 | +|---------|--------------| +| `@folder/*.py` | folder 中所有的 .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 + +> /share html +# 将会话导出为自包含的交互式 HTML 文件 +# 适合把精修过的会话报告分享给同事,或留作日后参考 +``` + +
+ +
+上下文感知对话 + + +### 上下文感知对话 + +当你进行层层叠加的多轮对话时,魔法才真正发生。 + +#### 示例:渐进式增强 + +```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..." +[Shows typed version] + +> Now improve error handling + +Copilot CLI: "Building on the typed version, here's improved error handling..." +[Adds validation and proper exceptions] + +> Generate tests for this final version + +Copilot CLI: "Based on the class with types and error handling..." +[Generates comprehensive tests] +``` + +注意每个提示词是如何在前一步工作的基础上构建的。这就是上下文的力量。 + +
+ +
+理解上下文窗口 + + +### 理解上下文窗口 + +你已经从基础部分了解了 `/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` 会汇总你的历史以释放 token: + +```bash +copilot + +> /compact +# 汇总对话历史,释放上下文空间 +# 你的关键发现和决策会被保留 +``` + +#### 上下文效率小贴士 + +| 场景 | 操作 | 原因 | +|-----------|--------|-----| +| 开启新话题 | `/clear` | 清除无关上下文 | +| 走错了路 | `/rewind` | 回滚到任意更早节点 | +| 长对话 | `/compact` | 汇总历史,释放 token | +| 需要特定文件 | `@file.py` 而非 `@folder/` | 仅加载所需内容 | +| 即将达到上限 | `/new` 或 `/clear` | 全新上下文 | +| 多个话题 | 每个话题用 `/rename` 命名 | 易于恢复到正确的会话 | + +#### 大型代码库的最佳实践 + +1. **要具体**:用 `@samples/book-app-project/books.py` 而不是 `@samples/book-app-project/` +2. **在话题之间清理上下文**:切换关注点时使用 `/new` 或 `/clear` +3. **使用 `/compact`**:汇总对话以释放上下文 +4. **使用多个会话**:每个功能或话题一个会话 + +
+ +
+选择要引用的内容 + + +### 选择要引用的内容 + +谈到上下文时,并非所有文件都同等重要。这里教你如何明智地选择: + +#### 文件大小的考量 + +| 文件大小 | 大致 [Token](../../../GLOSSARY.md#token) 数 | 策略 | +|-----------|-------------------|----------| +| 小(少于 100 行) | 约 500-1,500 个 token | 可以随意引用 | +| 中(100-500 行) | 约 1,500-7,500 个 token | 引用具体文件 | +| 大(500 行以上) | 7,500+ 个 token | 有所取舍,引用特定文件 | +| 非常大(1000 行以上) | 15,000+ 个 token | 考虑拆分或只针对其中某些段落 | + +**具体示例:** +- 图书应用的 4 个 Python 文件加起来约 2,000-3,000 个 token +- 一个典型的 Python 模块(200 行)约 3,000 个 token +- 一个 Flask API 文件(400 行)约 6,000 个 token +- 你的 package.json 约 200-500 个 token +- 一次简短的提示词 + 响应约 500-1,500 个 token + +> 💡 **代码 token 数的快速估算法:** 把代码行数乘以约 15,就能得到大致的 token 数。请记住这只是一个估算。 + +#### 该包含什么 vs 该排除什么 + +**高价值**(建议包含): +- 入口文件(`book_app.py`、`main.py`、`app.py`) +- 你正在询问的具体文件 +- 被目标文件直接 import 的文件 +- 配置文件(`requirements.txt`、`pyproject.toml`) +- 数据模型或 dataclass + +**低价值**(可考虑排除): +- 生成的文件(编译输出、打包后的资源) +- node modules 或 vendor 目录 +- 大型数据文件或测试夹具 +- 与你的问题无关的文件 + +#### 具体程度光谱 + +``` +Less specific ────────────────────────► More specific +@samples/book-app-project/ @samples/book-app-project/books.py:47-52 + │ │ + └─ Scans everything └─ Just what you need + (uses more context) (preserves context) +``` + +**何时放宽范围**(`@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.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`。你用了多少 token?再尝试 `/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. **会话自动保存**:用 `--name` 在启动时命名,用 `--resume=` 按名字恢复,或用 `--continue` 接着最近一次会话继续 +4. **上下文窗口** 是有上限的:用 `/clear`、`/compact`、`/context`、`/new` 和 `/rewind` 来管理它们 +5. **权限标志**(`--add-dir`、`--allow-all`)控制对多个目录的访问。请明智使用! +6. **图片引用**(`@screenshot.png`)有助于以可视方式调试 UI 问题 + +> 📚 **官方文档**:完整的上下文、会话与文件操作参考,请参见 [Use 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.md)** 中,你将学习: + +- 代码审查工作流 +- 重构模式 +- 调试辅助 +- 测试生成 +- Git 集成 + +--- + +**[← 返回第 01 章](../01-setup-and-first-steps/README.md)** | **[继续到第 03 章 →](../03-development-workflows/README.md)** diff --git a/localization/zh-cn/03-development-workflows/README.md b/localization/zh-cn/03-development-workflows/README.md new file mode 100644 index 00000000..af6035ad --- /dev/null +++ b/localization/zh-cn/03-development-workflows/README.md @@ -0,0 +1,972 @@ +![第 03 章:开发工作流](../../../03-development-workflows/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 +``` + +--- + +
+🎬 看看实际效果! + +![代码评审演示](../../../03-development-workflows/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 provides detailed review + +> The user input handling - are there any edge cases I'm missing? + +# Copilot CLI shows potential issues with empty strings, special characters + +> Create a checklist of all issues found, prioritized by severity + +# Copilot CLI generates prioritized action items +``` + +### 评审清单模板 + +让 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 +# Quick reference +git status # Shows both staged and unstaged +git add file.py # Stage a file for commit +git diff # Shows unstaged changes +git diff --staged # Shows staged changes +``` + +### 使用 /review 命令 + +`/review` 命令会调用内置的 **code-review 智能体**,它专为分析已暂存和未暂存的变更而优化,输出信噪比很高。使用斜杠命令可以触发一个专门的内置智能体,而不必自己写自由形式的提示词。 + +```bash +copilot + +> /review +# Invokes the code-review agent on staged/unstaged changes +# Provides focused, actionable feedback + +> /review Check for security issues in authentication +# Run review with specific focus area +``` + +> 💡 **小贴士**:code-review 智能体在你有待处理变更时效果最好。先用 `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.` + +从直截了当的小改进开始。下面这些都可以在 book app 上试一试。每条提示都把 `@` 文件引用与一条具体的重构指令配对,这样 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 +``` + +> 💡 **第一次接触重构?** 在挑战复杂转换之前,先从简单的请求入手,例如添加类型提示或改进变量名。 + +--- + +
+🎬 看看实际效果! + +![重构演示](../../../03-development-workflows/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 + +# Get tests first + +> Now refactor the BookCollection class to use a context manager for file operations + +# Refactor with confidence - tests verify behavior is preserved +``` + +
+ +--- + + +
+工作流 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 的 book app 上尝试的常见调试模式。每条提示都把 `@` 文件引用与清晰的症状描述配对,让 Copilot CLI 能定位并诊断 Bug。 + +```bash +copilot + +# Pattern: "Expected X but got 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. + +# Pattern: "Unexpected behavior" +> @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. + +# Pattern: "Wrong results" +> @samples/book-app-buggy/books_buggy.py When I mark one book as read, ALL books get marked. What's the bug? +``` + +> 💡 **调试小贴士**:描述*症状*(你看到了什么)和*预期*(应该发生什么)。其余的交给 Copilot CLI。 + +--- + +
+🎬 看看实际效果! + +![修复 Bug 演示](../../../03-development-workflows/images/fix-bug-demo.gif) + +*演示输出会有所不同。你的模型、工具和回复会与此处展示的不一样。* + +
+ +--- + +### "Bug 侦探" —— AI 找出相关的 Bug + +这正是上下文感知调试的闪光点。在带 Bug 的 book app 上尝试这个场景:用 `@` 提供整个文件,只描述用户报告的症状。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 +``` + +--- + +
+🎬 看看实际效果! + +![测试生成演示](../../../03-development-workflows/images/test-gen-demo.gif) + +*演示输出会有所不同。你的模型、工具和回复会与此处展示的不一样。* + +
+ +--- + +**你会得到**:15+ 个全面的测试,包括: + +```python +class TestBookCollection: + # Happy path + def test_add_book_creates_new_book(self): + ... + def test_list_books_returns_all_books(self): + ... + + # Find operations + 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): + ... + + # Edge cases + def test_add_book_with_empty_title(self): + ... + def test_remove_nonexistent_book(self): + ... + def test_mark_as_read_nonexistent_book(self): + ... + + # Data persistence + def test_save_books_persists_to_json(self): + ... + def test_load_books_handles_missing_file(self): + ... + def test_load_books_handles_corrupted_json(self): + ... + + # Special characters + 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 responds: +# cd samples/book-app-project && python -m pytest tests/ +# Or for verbose output: python -m pytest tests/ -v +# To see print statements: 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 描述、/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 + +# See what changed +git diff --staged + +# Generate commit message using [Conventional Commit](../../../GLOSSARY.md#conventional-commit) format +# (structured messages like "feat(books): add search" or "fix(data): handle empty input") +copilot -p "Generate a conventional commit message for: $(git diff --staged)" + +# Output: "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 集成演示](../../../03-development-workflows/images/git-integration-demo.gif) + +*演示输出会有所不同。你的模型、工具和回复会与此处展示的不一样。* + +
+ +--- + +### 解释变更 + +把 `git show` 的输出通过管道喂给 `-p` 提示词,得到对上一次提交的大白话总结。 + +```bash +# What did this commit change? +copilot -p "Explain what this commit does: $(git show HEAD --stat)" +``` + +### PR 描述 + +把 `git log` 输出与一个结构化提示词模板结合,自动生成完整的 pull request 描述。 + +```bash +# Generate PR description from branch changes +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)" +``` + +### 在交互模式下对当前分支使用 /pr + +如果你正在 Copilot CLI 的交互模式下处理一个分支,可以使用 `/pr` 命令操作 pull request。用 `/pr` 来查看 PR、创建新 PR、修复现有 PR,或者让 Copilot CLI 根据分支状态自动判断。 + +```bash +copilot + +> /pr [view|create|fix|auto] +``` + +### 推送前评审 + +在 `-p` 提示词中使用 `git diff main..HEAD`,可以对分支的全部变更进行一次推送前的快速复核。 + +```bash +# Last check before pushing +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 + +# Or use the & prefix shortcut: +> & Fix the typo in the README header + +# Copilot CLI: +# 1. Commits your changes to a new branch +# 2. Opens a draft pull request +# 3. Works in the background on GitHub +# 4. Requests your review when done +``` + +对于那些定义清晰、希望在你专注于其他事情时被完成的任务,这非常合适。 + +### 使用 /diff 评审会话变更 + +`/diff` 命令展示当前会话期间所做的全部变更。在提交之前,用这个斜杠命令以可视化的 diff 形式查看 Copilot CLI 修改过的所有内容。 + +```bash +copilot + +# After making some changes... +> /diff + +# Shows a visual diff of all files modified in this session +# Great for reviewing before committing +``` + +
+ +--- + +## 小贴士:在规划或编码前先调研 + +当你需要调研某个库、了解最佳实践或探索一个不熟悉的话题时,可以在写任何代码之前用 `/research` 进行一次深度调研: + +```bash +copilot + +> /research What are the best Python libraries for validating user input in CLI apps? +``` + +Copilot 会搜索 GitHub 仓库和网页资源,然后返回一份带参考资料的总结。当你即将开始一个新功能、想先做出明智的决策时,这一招特别有用。你可以使用 `/share` 把结果分享出去。 + +> 💡 **小贴士**:`/research` 与 `/plan` 配合很好,先调研后规划。先调研方案,再规划如何实现。 + +--- + +## 全部串起来:修 Bug 工作流 + +下面是修复一个上报 Bug 的完整工作流: + +```bash + +# 1. Understand the bug report +copilot + +> Users report: 'Finding books by author name doesn't work for partial names' +> @samples/book-app-project/books.py Analyze and identify the likely cause + +# 2. Debug the issue and fix (continuing in same session) +> Based on the analysis, show me the find_by_author function and explain the issue + +> Fix the find_by_author function to handle partial name matches + +# 3. Generate tests for the fix +> @samples/book-app-project/books.py Generate pytest tests specifically for: +> - Full author name match +> - Partial author name match +> - Case-insensitive matching +> - Author name not found + +# Exit the interactive session + +> /exit + +# 4. Run git add + +# Stage the changes so git diff --staged has something to work with +git add . + +# 5. Generate commit message +copilot -p "Generate commit message for: $(git diff --staged)" + +# Example Output: "fix(books): support partial author name search" + +# 6. Commit changes (optional) + +git commit -m "" +``` + +### 修 Bug 工作流总结 + +| 步骤 | 操作 | Copilot 命令 | +|------|--------|-----------------| +| 1 | 理解 Bug | `> [describe bug] @relevant-file.py Analyze the likely cause` | +| 2 | 分析并修复 | `> Show me the function and fix the issue` | +| 3 | 生成测试 | `> Generate tests for [specific scenarios]` | +| 4 | 暂存变更 | `git add .` | +| 5 | 生成提交信息 | `copilot -p "Generate commit message for: $(git diff --staged)"` | +| 6 | 提交变更 | `git commit -m ""` | + +--- + +# 实战练习 + +温馨的桌面布置:显示器上展示着代码,台灯、咖啡杯和耳机一应俱全,准备开始动手实践 + +现在轮到你应用这些工作流了。 + +--- + +## ▶️ 自己来试试 + +完成这些演示后,再尝试以下变体: + +1. **Bug 侦探挑战**:让 Copilot CLI 调试 `samples/book-app-buggy/books_buggy.py` 中的 `mark_as_read` 函数。它有没有解释为什么这个函数会把*所有*书都标为已读,而不是只标记一本? + +2. **测试挑战**:为 book app 里的 `add_book` 函数生成测试。数一数 Copilot CLI 包含了多少个你自己想不到的边界用例。 + +3. **提交信息挑战**:在 book app 的某个文件里做一点小改动,暂存它(`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. **提交**:生成符合 Conventional Commit 规范的提交信息: + `copilot -p "Generate a conventional commit message for: $(git diff --staged)"` + +
+💡 提示(点击展开) + +**每一步的示例提示词:** + +```bash +copilot + +# Step 1: Review +> @samples/book-app-project/books.py Review the remove_book() function. What edge cases are not handled? + +# Step 2: Refactor +> 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. + +# Step 3: Test +> 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 + +# Step 4: Review +> /review + +# Step 5: Commit +> Generate a conventional commit message for this refactor +``` + +**小贴士:** 改进 `remove_book()` 之后,可以试着问 Copilot CLI:"这个文件里还有哪些函数可以做类似的改进?"它可能会建议对 `find_book_by_title()` 或 `find_by_author()` 做类似的改动。 + +
+ +### 加分挑战:用 Copilot CLI 创建一个应用 + +> 💡 **注意**:这个 GitHub Skills 练习使用的是 **Node.js**,而非 Python。但你将练到的 GitHub Copilot CLI 技巧 —— 创建 issue、生成代码、在终端中协作 —— 适用于任何语言。 + +该练习展示开发者如何使用 GitHub Copilot CLI 创建 issue、生成代码,并在终端中协作完成一个 Node.js 计算器应用。你将安装 CLI、使用模板和智能体,并实践迭代式、命令行驱动的开发。 + +##### [开始 "Create applications with the Copilot CLI" Skills 练习](https://github.com/skills/create-applications-with-the-copilot-cli) + +--- + +
+🔧 常见错误与故障排查(点击展开) + +### 常见错误 + +| 错误 | 会发生什么 | 怎么解决 | +|---------|--------------|-----| +| 使用模糊的提示词,例如 "Review this code" | 只能得到泛泛的反馈,错过具体问题 | 写具体一点:"Review for SQL injection, XSS, and auth issues" | +| 代码评审时没有使用 `/review` | 错过了优化过的 code-review 智能体 | 使用 `/review`,它专为高信噪比输出而调校 | +| 没有上下文就让其 "find bugs" | Copilot CLI 不知道你遇到的是哪个 Bug | 描述症状:"Users report X happens when Y" | +| 生成测试时没有指定框架 | 测试可能用错语法或断言库 | 指定:"Generate tests using Jest" 或 "using pytest" | + +### 故障排查 + +**评审显得不完整** —— 把要找的内容写得更具体: + +```bash +copilot + +# Instead of: +> Review @samples/book-app-project/book_app.py + +# Try: +> 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.md)** 中,你将学到: + +- 使用内置智能体(`/plan`、`/review`) +- 用 `.agent.md` 文件创建专门的智能体(前端专家、安全审计员) +- 多智能体协作模式 +- 用于项目规范的自定义指令文件 + +--- + +**[← 返回第 02 章](../02-context-conversations/README.md)** | **[继续到第 04 章 →](../04-agents-custom-instructions/README.md)** diff --git a/localization/zh-cn/04-agents-custom-instructions/README.md b/localization/zh-cn/04-agents-custom-instructions/README.md new file mode 100644 index 00000000..65ab3d34 --- /dev/null +++ b/localization/zh-cn/04-agents-custom-instructions/README.md @@ -0,0 +1,783 @@ +![第 04 章:智能体与自定义指令](../../../04-agents-custom-instructions/images/chapter-header.png) + +> **如果你能一次性"雇佣"一位 Python 代码审查员、一位测试专家和一位安全审查员……而且全都集成在同一个工具里,会怎么样?** + +在第 03 章中,你掌握了几项核心工作流:代码审查、重构、调试、测试生成和 Git 集成。这些工作流让你能够借助 GitHub Copilot CLI 极大地提升生产力。现在,我们再往前走一步。 + +到目前为止,你一直把 Copilot CLI 当作一个通用助手来使用。智能体(Agent)则可以赋予它一个具体的"身份",并自带一套既定标准——比如一位强制要求类型注解和 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** | *自动调用* | 执行测试、构建、Lint、依赖安装等命令 | + +
+ +**内置智能体实战** —— 调用 Plan、Code-review、Explore 与 Task 的示例 + +```bash +copilot + +# Invoke the Plan agent to create an implementation plan +> /plan Add input validation for book year in the book app + +# Invoke the Code-review agent on your changes +> /review + +# Explore and Task agents are invoked automatically when relevant: +> Run the test suite # Uses Task agent + +> Explore how book data is loaded # Uses Explore agent +``` + +那么 Task 智能体呢?它会在幕后管理与跟踪正在发生的事情,并以清晰、整洁的格式向你汇报: + +| 结果 | 你会看到什么 | +|---------|--------------| +| ✅ **成功** | 简短摘要(例如:"All 247 tests passed"、"Build succeeded") | +| ❌ **失败** | 完整输出,包括堆栈跟踪、编译器错误和详细日志 | + + +> 📚 **官方文档**:[GitHub Copilot CLI Agents](https://docs.github.com/copilot/how-tos/use-copilot-agents/use-copilot-cli#use-custom-agents) + +--- + +# 为 Copilot CLI 添加智能体 + +你完全可以定义自己的智能体,把它们融入到日常工作流中!一次定义,随时调用! + +四个色彩缤纷的 AI 机器人并肩而立,每个都拿着不同的工具,象征着各自专长的智能体能力 + +## 🗂️ 添加你的智能体 + +智能体文件就是后缀为 `.agent.md` 的 Markdown 文件。它由两部分组成:YAML 前置信息(元数据)和 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 +``` + +> 💡 **必填项与可选项**:`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 +# Or copy one to your personal agents folder (available in every project) +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` 并选择 **no 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 Reviewer 智能体 + +```bash +copilot + +> /agent +# Select "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 智能体自动包含了哪些内容**: +- ✅ 所有参数和返回值都带有类型注解 +- ✅ 完整的 docstring,包含 Args/Returns/Raises +- ✅ 输入校验,并配套合适的错误处理 +- ✅ 使用列表推导式以获得更好的性能 +- ✅ 处理了边界情况(缺失或无效的 year 值) +- ✅ 符合 PEP 8 的格式规范 +- ✅ 防御式编程实践 + +**差异之处**:同一个提示,输出却好得多。智能体会自动带上那些你可能忘了要求的专业实践。 + +
+ +--- + + +
+使用多个智能体协作 —— 组合专家、会话中切换、把智能体当作工具 + +## 使用多个智能体协作 + +当多个专家围绕同一个功能协同工作时,真正的威力才会显现。 + +### 示例:构建一个简单功能 + +```bash +copilot + +> I want to add a "search by year range" feature to the book app + +# Use python-reviewer for design +> /agent +# Select "python-reviewer" + +> @samples/book-app-project/books.py Design a find_by_year_range method. What's the best approach? + +# Switch to pytest-helper for test design +> /agent +# Select "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? + +# Synthesize both designs +> Create an implementation plan that includes the method implementation and comprehensive tests. +``` + +**关键洞察**:你是指挥专家的架构师。他们负责具体细节,你负责整体愿景。 + +
+🎬 看看实际效果! + +![Python Reviewer 演示](../../../04-agents-custom-instructions/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` 优于笼统的 `frontend` + +--- + +### 与团队共享 + +将智能体文件放在 `.github/agents/` 中,它们就会被纳入版本控制。推送到仓库后,每位团队成员都能自动获取。但智能体只是 Copilot 从你的项目中读取的文件类型之一,它还支持 **指令文件**——这些文件会自动应用到每一次会话,无需任何人执行 `/agent`。 + +可以这样理解:智能体是你按需调用的专家,而指令文件则是团队中始终生效的规则。 + +### 文件应放在哪里 + +你已经了解了两个主要位置(参见上文 [智能体文件应当放在哪里](#where-to-put-agent-files))。可以使用下面这棵决策树来决定: + +智能体文件位置决策树:试验阶段 → 当前文件夹;团队使用 → .github/agents/;到处使用 → ~/.copilot/agents/ + +**从简单开始:** 先在你的项目目录里创建一个 `*.agent.md` 文件。等你对它满意了,再把它移到一个长期位置。 + +除了智能体文件,Copilot 还会自动读取 **项目级别的指令文件**,无需 `/agent`。详情见下文的 [为 Copilot 配置你的项目](#configuring-your-project-for-copilot),其中介绍了 `AGENTS.md`、`.instructions.md` 以及 `/init`。 + +
+ +--- + + +
+为 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` 通常会描述项目背景、代码风格、安全要求和测试标准。你可以参照我们的示例文件来编写自己的版本。 + +### 自定义指令文件(.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` —— 调用其他自定义智能体 + +> 📖 **官方文档**:[Custom agents configuration](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 + +# Create the agents directory (if it doesn't exist) +mkdir -p .github/agents + +# Create a code reviewer agent +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 + +# Create a documentation agent +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 + +# Now use them +copilot --agent reviewer +> Review @samples/book-app-project/books.py + +# Or switch agents +copilot +> /agent +# Select "documentor" +> Document @samples/book-app-project/books.py +``` + +--- + +## 📝 作业 + +### 主挑战:组建一支专门化的智能体团队 + +在前面的动手示例中,你创建了 `reviewer` 和 `documentor` 两个智能体。现在我们换一个任务来练习创建并使用智能体——改进 book app 中的数据校验: + +1. 在 `.github/agents/` 中创建 3 个针对 book app 的智能体文件(`.agent.md`),每个智能体一个文件 +2. 你的智能体: + - **data-validator**:检查 `data.json` 中是否存在缺失或畸形的数据(空作者、year=0、字段缺失) + - **error-handler**:审查 Python 代码中错误处理是否一致,并给出统一方案的建议 + - **doc-writer**:生成或更新 docstring 与 README 内容 +3. 在 book app 上分别使用每个智能体: + - `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 +# Select "data-validator" from the list +> @samples/book-app-project/data.json Check for books with empty author fields or invalid years +``` + +**小贴士:** YAML 前置信息中的 `description` 字段是智能体能正常工作的必填项。 + +
+ +### 加分挑战:指令库 + +你已经构建了按需调用的智能体。现在试试另一面:**指令文件**——Copilot 会在每次会话中自动读取它们,无需 `/agent`。 + +创建一个 `.github/instructions/` 文件夹,并在其中放入至少 3 个指令文件: +- `python-style.instructions.md`,用于强制执行 PEP 8 与类型注解约定 +- `test-standards.instructions.md`,用于在测试文件中强制执行 pytest 约定 +- `data-quality.instructions.md`,用于校验 JSON 数据条目 + +针对 book app 的代码,分别测试每个指令文件。 + +--- + +
+🔧 常见错误与故障排查(点击展开) + +### 常见错误 + +| 错误 | 现象 | 修复方式 | +|---------|--------------|-----| +| 智能体前置信息中缺少 `description` | 智能体无法加载或无法被发现 | 始终在 YAML 前置信息中包含 `description:` | +| 智能体文件位置不正确 | 调用时找不到对应的智能体 | 放置到 `~/.copilot/agents/`(个人)或 `.github/agents/`(项目) | +| 使用 `.md` 而不是 `.agent.md` | 文件可能不会被识别为智能体 | 文件名按 `python-reviewer.agent.md` 这种方式命名 | +| 智能体提示词过长 | 可能超出 30,000 个字符的上限 | 智能体定义保持聚焦;详尽的指令交给 skill 来承载 | + +### 故障排查 + +**找不到智能体** —— 检查智能体文件是否存在于以下位置之一: +- `~/.copilot/agents/` +- `.github/agents/` + +列出可用的智能体: + +```bash +copilot +> /agent +# Shows all available agents +``` + +**智能体不按指令执行** —— 在你的提示词中要更明确,并在智能体定义中补充更多细节: +- 指明具体的框架/库以及版本 +- 团队约定 +- 示例代码模式 + +**自定义指令未加载** —— 在你的项目中执行 `/init` 来设置项目级指令: + +```bash +copilot +> /init +``` + +也可以检查它们是否被禁用: +```bash +# Don't use --no-custom-instructions if you want them loaded +copilot # This loads custom instructions by default +``` + +
+ +--- + +# 小结 + +## 🔑 关键要点 + +1. **内置智能体**:`/plan` 和 `/review` 直接调用即可;Explore 和 Task 会自动工作 +2. **自定义智能体** 是定义在 `.agent.md` 文件中的专家 +3. **优秀的智能体** 拥有清晰的专长、标准与输出格式 +4. **多智能体协作** 通过组合不同专长来解决复杂问题 +5. **指令文件**(`.instructions.md`)将团队标准编码下来,自动生效 +6. **稳定一致的输出** 来自定义良好的智能体指令 + +> 📋 **快速参考**:完整的命令与快捷键列表,请参阅 [GitHub Copilot CLI 命令参考](https://docs.github.com/en/copilot/reference/cli-command-reference)。 + +--- + +## ➡️ 下一步 + +智能体改变的是 *Copilot 在你的代码中如何思考问题、采取有针对性的行动* 的方式。接下来,你将了解 **技能(skills)**——它们改变的是 Copilot 遵循的 *步骤*。想知道智能体和技能到底有什么不同?第 05 章会正面回答这个问题。 + +在 **[第 05 章:Skills 系统](../05-skills/README.md)** 中,你将学到: + +- 技能如何根据你的提示自动触发(无需斜杠命令) +- 安装社区提供的技能 +- 通过 SKILL.md 文件创建自定义技能 +- 智能体、技能与 MCP 之间的区别 +- 何时使用哪一种 + +--- + +**[← 返回第 03 章](../03-development-workflows/README.md)** | **[继续学习第 05 章 →](../05-skills/README.md)** diff --git a/localization/zh-cn/05-skills/README.md b/localization/zh-cn/05-skills/README.md new file mode 100644 index 00000000..b5effeb6 --- /dev/null +++ b/localization/zh-cn/05-skills/README.md @@ -0,0 +1,886 @@ +![第 05 章:技能系统](../../../05-skills/images/chapter-header.png) + +> **如果 Copilot 能自动应用你团队的最佳实践,而你不必每次都向它解释,那会怎样?** + +在本章中,你将学习 Agent Skills(智能体技能):当与你的任务相关时,Copilot 会自动加载这些指令文件夹。智能体改变的是 Copilot 的*思考方式*,而技能则教会 Copilot *完成任务的具体方法*。你将创建一个安全审计技能,每当你询问安全相关的问题时 Copilot 都会应用它;构建团队标准的代码审查准则,确保代码质量的一致性;并了解技能如何在 Copilot CLI、VS Code 以及 GitHub Copilot 云端智能体之间协同工作。 + + +## 🎯 学习目标 + +学完本章后,你将能够: + +- 理解 Agent Skills 的工作原理以及何时使用它们 +- 通过 SKILL.md 文件创建自定义技能 +- 使用来自共享仓库的社区技能 +- 知道何时使用技能、智能体或者 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 能找到的所有技能,包括 CLI 自带的**内置技能**,以及来自项目和个人文件夹的技能。 + + > 💡 **内置技能**:Copilot CLI 开箱即用就附带了一些技能。例如,`customizing-copilot-cloud-agents-environment` 技能就提供了一份关于如何自定义 Copilot 云端智能体环境的指南。你不需要创建或安装任何东西就能使用这些技能。运行 `/skills list` 看看都有哪些。 + +2. **查看一个真实的技能文件:** 看看我们提供的 [code-checklist SKILL.md](../../../.github/skills/code-checklist/SKILL.md),了解一下它的格式。其实就是 YAML frontmatter 加上 Markdown 指令而已。 + +3. **理解核心概念:** 技能是任务专用的指令,当你的提示与某个技能的描述相匹配时,Copilot 会*自动*加载它。你不需要主动激活它们,只需自然地提问即可。 + + +## 理解技能 + +Agent Skills 是包含指令、脚本和资源的文件夹,**当与你的任务相关时**,Copilot 会自动加载它们。Copilot 会读取你的提示,检查是否有匹配的技能,然后自动应用相关指令。 + +```bash +copilot + +> Check books.py against our quality checklist +# Copilot detects this matches your "code-checklist" skill +# and automatically applies its Python quality checklist + +> Generate tests for the BookCollection class +# Copilot loads your "pytest-gen" skill +# and applies your preferred test structure + +> What are the code quality issues in this file? +# Copilot loads your "code-checklist" skill +# and checks against your team's standards +``` + +> 💡 **关键点**:技能会根据你的提示与技能描述的匹配情况**自动触发**。你只需自然地提问,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 +``` + +这样可以让你显式控制,确保使用特定的技能。 + +#### 在一条消息中组合调用多个技能 + +你可以**在一条消息中调用多个技能**,并且技能斜杠命令可以出现在提示的任何位置——不一定要放在开头。当你想一次性完成两种不同的检查时,这非常方便: + +```bash +> Check @samples/book-app-project/book_app.py with /code-checklist and also run /generate-tests for it + +> Review the auth module /security-audit then /code-checklist the result +``` + +Copilot 会在同一次回复中应用每一个被点名的技能,让你不必发送多条独立的消息。 + +> 💡 **小贴士**:把技能斜杠命令放在你句子中最自然的位置即可。可以放在消息的开头、中间或结尾。 + +> 📝 **技能调用 vs 智能体调用**:不要把技能调用和智能体调用搞混了: +> - **技能**:`/skill-name `,例如 `/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/)中介绍它。这里提一下只是为了让你看清技能在整体图景中的位置。* + +对比图,展示智能体、技能与 MCP 服务器之间的差异,以及它们如何组合到你的工作流中 + +| 特性 | 它做什么 | 何时使用 | +|---------|--------------|-------------| +| **智能体(Agents)** | 改变 AI 的思考方式 | 在多种任务中需要专门的专家能力时 | +| **技能(Skills)** | 提供任务专用的指令 | 用于具体、可重复的任务,并附带详细步骤时 | +| **MCP** | 连接外部服务 | 需要从 API 获取实时数据时 | + +智能体用于广泛的专业知识,技能用于特定任务的指令,而 MCP 用于外部数据。一个智能体可以在一次对话中使用一个或多个技能。例如,当你让一个智能体检查代码时,它可能会同时自动应用 `security-audit` 技能和 `code-checklist` 技能。 + +> 📚 **进一步学习**:完整的技能格式和最佳实践请参考官方文档 [About Agent Skills](https://docs.github.com/copilot/concepts/agents/about-agent-skills)。 + +--- + +## 从手动提示到自动专家能力 + +在深入讲解如何创建技能之前,先看看*为什么*它们值得学习。一旦你看到一致性方面的提升,"如何做" 部分就会更容易理解。 + +### 没有技能时:审查不一致 + +每次代码审查,你都可能漏掉某些事情: + +```bash +copilot + +> Review this code for issues +# Generic review - might miss your team's specific concerns +``` + +或者每次都写一段冗长的提示: + +```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. 应用所有检查项,无需你逐项罗列 + +技能如何自动触发——展示 Copilot 如何将你的提示自动匹配到正确技能的 4 步流程 + +*只要自然提问,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 +``` + +**差别在于**:你团队的标准每次都被自动应用,无需你再敲出来。 + +--- + +
+🎬 看看实际效果! + +![技能触发演示](../../../05-skills/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 # Required: Skill definition and instructions + ├── examples/ # Optional: Example files Copilot can reference + │ └── sample.py + └── scripts/ # Optional: Scripts the skill can use + └── 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` | 否 | 适用于该技能的许可证 | + +> 📖 **官方文档**:[About Agent Skills](https://docs.github.com/copilot/concepts/agents/about-agent-skills) + +### 创建你的第一个技能 + +让我们构建一个安全审计技能,用来检查 OWASP Top 10 漏洞: + +```bash +# Create skill directory +mkdir -p .github/skills/security-audit + +# Create the SKILL.md file +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 + +# Test your skill (skills load automatically based on your prompt) +copilot + +> @samples/book-app-project/ Check this code for security vulnerabilities +# Copilot detects "security vulnerabilities" matches your skill +# and automatically applies its OWASP checklist +``` + +**预期输出**(你的结果会有所不同): + +``` +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 +# Start with a code-reviewer agent +copilot --agent code-reviewer + +> Check the book app for quality issues +# code-reviewer agent's expertise combines +# with your code-checklist skill's 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 +``` + +--- + +
+看看实际效果! + +![列出技能演示](../../../05-skills/images/list-skills-demo.gif) + +*演示输出会有所不同。你的模型、工具和回复都会与此处展示的内容有所差别。* + +
+ +--- + +### 何时使用 `/skills reload` + +在创建或编辑技能的 SKILL.md 文件后,运行 `/skills reload` 即可在不重启 Copilot 的情况下让改动生效: + +```bash +# Edit your skill file +# Then in Copilot: +> /skills reload +Skills reloaded successfully. +``` + +> 💡 **小知识**:即使你使用 `/compact` 总结过对话历史,技能仍然有效。压缩后无需重新加载。 + +--- + +## 查找并使用社区技能 + +### 使用插件安装技能 + +> 💡 **什么是插件?** 插件是可安装的包,能够把技能、智能体和 MCP 服务器配置打包在一起。可以把它们看作 Copilot CLI 的 "应用商店" 扩展。 + +`/plugin` 命令可以让你浏览并安装这些包: + +```bash +copilot + +> /plugin list +# Shows installed plugins + +> /plugin marketplace +# Browse available plugins + +> /plugin install +# Install a plugin from the marketplace +``` + +要保持本地插件目录的最新状态,可以用以下命令刷新: + +```bash +copilot plugin marketplace update +``` + +插件可以打包多种能力。一个插件可能包含多个相关的技能、智能体和 MCP 服务器配置,它们协同工作。 + +### 社区技能仓库 + +预制好的技能也可以从社区仓库中获取: + +- **[Awesome Copilot](https://github.com/github/awesome-copilot)** —— GitHub 官方的 Copilot 资源,包含技能文档与示例 + +### 使用 GitHub CLI 安装社区技能 + +从 GitHub 仓库安装技能最简单的方式是使用 `gh skill install` 命令(需要 [GitHub CLI v2.90.0+](https://github.blog/changelog/2026-04-16-manage-agent-skills-with-github-cli/)): + +```bash +# Browse and interactively select a skill from awesome-copilot +gh skill install github/awesome-copilot + +# Or install a specific skill directly +gh skill install github/awesome-copilot code-checklist + +# Install for personal use across all projects (user scope) +gh skill install github/awesome-copilot code-checklist --scope user +``` + +> ⚠️ **安装前务必审阅**:在安装某个技能之前,请先阅读它的 `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 项检查: + - 裸的 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 +# The skill should auto-trigger based on the description match +``` + +**如果没有触发:** 试试 `/skills reload`,然后再问一次。 + +
+ +### 加分挑战:提交信息技能 + +1. 创建一个 `commit-message` 技能,用于以一致的格式生成 conventional commit 提交信息 +2. 通过暂存一个改动并提问 "Generate a commit message for my staged changes" 来测试它 +3. 为你的技能编写文档,并使用 `copilot-skill` 主题在 GitHub 上分享 + +--- + +
+🔧 常见错误与故障排查(点击展开) + +### 常见错误 + +| 错误 | 会发生什么 | 修复方法 | +|---------|--------------|-----| +| 把文件命名为非 `SKILL.md` 的名称 | 技能不会被识别 | 文件必须严格命名为 `SKILL.md` | +| `description` 字段含糊 | 技能永远不会被自动加载 | 描述是首要的发现机制。使用具体的触发词 | +| frontmatter 缺少 `name` 或 `description` | 技能加载失败 | 在 YAML frontmatter 中同时添加这两个字段 | +| 文件夹位置错误 | 找不到技能 | 使用 `.github/skills/skill-name/`(项目级)或 `~/.copilot/skills/skill-name/`(个人级) | + +### 故障排查 + +**技能没被使用** —— 如果 Copilot 没有按预期使用你的技能: + +1. **检查描述**:它是否与你的提问方式相匹配? + ```markdown + # Bad: Too vague + description: Reviews code + + # Good: Includes trigger words + description: Use for code reviews, checking code quality, + finding bugs, security issues, and best practice violations + ``` + +2. **核实文件位置**: + ```bash + # Project skills + ls .github/skills/ + + # User 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/ # Folder name + └── SKILL.md # Must be exactly SKILL.md (case-sensitive) +``` + +在创建或编辑技能后运行 `/skills reload`,确保改动被识别。 + +**测试技能是否加载** —— 直接询问 Copilot: +```bash +> What skills do you have available for checking code quality? +# Copilot will describe relevant skills it found +``` + +**我怎么知道我的技能确实在工作?** + +1. **检查输出格式**:如果你的技能指定了输出格式(比如 `[CRITICAL]` 标签),看看回复中是否有这种标签 +2. **直接询问**:得到回复后问一句 "Did you use any skills for that?" +3. **对比有/无技能**:用同一条提示加上 `--no-custom-instructions` 看看差异: + ```bash + # With skills + copilot --allow-all -p "Review @file.py for security issues" + + # Without skills (baseline comparison) + copilot --allow-all -p "Review @file.py for security issues" --no-custom-instructions + ``` +4. **核对具体检查项**:如果你的技能包含具体检查项(例如 "functions over 50 lines"),看看这些是否出现在输出中 + +
+ +--- + +# 总结 + +## 🔑 核心要点 + +1. **技能是自动的**:当你的提示与技能描述匹配时,Copilot 会自动加载它们 +2. **直接调用**:你也可以使用 `/skill-name` 作为斜杠命令直接调用技能 +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.md)**中,你将学习: + +- 什么是 MCP(Model Context Protocol,模型上下文协议) +- 连接到 GitHub、文件系统和文档服务 +- 配置 MCP 服务器 +- 多服务器工作流 + +--- + +**[← 返回第 04 章](../04-agents-custom-instructions/README.md)** | **[继续到第 06 章 →](../06-mcp-servers/README.md)** diff --git a/localization/zh-cn/06-mcp-servers/README.md b/localization/zh-cn/06-mcp-servers/README.md new file mode 100644 index 00000000..7ce4465a --- /dev/null +++ b/localization/zh-cn/06-mcp-servers/README.md @@ -0,0 +1,974 @@ +![第 06 章:MCP 服务器](../../../06-mcp-servers/images/chapter-header.png) + +> **如果 Copilot 能读取你的 GitHub issue、查询数据库,并创建 PR……而这一切都在终端里完成,会是怎样的体验?** + +到目前为止,Copilot 只能处理你直接提供给它的内容:你用 `@` 引用的文件、对话历史,以及它自身的训练数据。但如果它能主动访问你的 GitHub 仓库、浏览项目文件,或查阅某个库的最新文档,又会怎样呢? + +这正是 MCP(Model Context Protocol,模型上下文协议)所做的事。它是一种将 Copilot 连接到外部服务的方式,让它能够访问实时的真实数据。Copilot 连接的每一项服务都被称为一个"MCP 服务器"。在本章中,你将设置几个这样的连接,并看到它们如何让 Copilot 变得更加强大。 + +> 💡 **已经熟悉 MCP?** [跳转到快速开始](#-use-the-built-in-github-mcp),确认它正在工作并开始配置服务器。 + +## 🎯 学习目标 + +完成本章后,你将能够: + +- 理解 MCP 是什么以及它为什么重要 +- 使用 `/mcp` 命令管理 MCP 服务器 +- 为 GitHub、文件系统和文档配置 MCP 服务器 +- 在 book app 项目中使用基于 MCP 的工作流 +- 知道何时以及如何构建自定义 MCP 服务器(可选) + +> ⏱️ **预计用时**:约 50 分钟(15 分钟阅读 + 35 分钟动手实践) + +--- + +## 🧩 现实类比:浏览器扩展 + +MCP 服务器就像浏览器扩展 + +把 MCP 服务器想象成浏览器扩展。浏览器本身可以显示网页,但扩展能将它连接到额外的服务: + +| 浏览器扩展 | 它连接的对象 | 对应的 MCP | +|-------------------|---------------------|----------------| +| 密码管理器 | 你的密码库 | **GitHub MCP** → 你的仓库、issue、PR | +| Grammarly | 写作分析服务 | **Context7 MCP** → 库的文档 | +| 文件管理器 | 云存储 | **Filesystem MCP** → 本地项目文件 | + +没有扩展的浏览器仍然有用,但有了扩展,它就成了一个强大的工具。MCP 服务器对 Copilot 来说也是如此。它们将 Copilot 连接到真实、实时的数据源,让它可以读取你的 GitHub issue、浏览你的文件系统、获取最新文档等等。 + +***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 管理命令?** 你可以在聊天中通过 `/mcp` 斜杠命令管理服务器,或直接在终端中使用 `copilot mcp`。请参阅本章末尾的[完整命令参考](#-additional-mcp-commands)。 + +
+🎬 看看实际效果! + +![MCP 状态演示](../../../06-mcp-servers/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 的实际效果,那就让我们设置更多服务器吧。你可以通过两种方式添加服务器:**从内置注册表添加**(最简单——CLI 中提供引导式设置)或**手动编辑配置文件**(更灵活)。如果你不确定选哪种,请从注册表选项开始。 + +--- + +## 从注册表安装 MCP 服务器 + +CLI 内置了一个 MCP 服务器注册表,让你可以通过引导式设置发现并安装常用服务器——无需编辑 JSON。 + +```bash +copilot + +> /mcp search +``` + +Copilot 会打开一个交互式选择器,显示可用的服务器。选择一个,CLI 就会引导你完成所需的配置(API 密钥、路径等),并自动将其添加到你的配置中。 + +> 💡 **为什么使用注册表?** 这是最容易上手的方式——你不需要知道 npm 包名、命令参数或 JSON 结构。CLI 会为你处理所有这些。 + +--- + +## MCP 配置文件 + +MCP 服务器配置在 `~/.copilot/mcp-config.json`(用户级,适用于所有项目)或 `.mcp.json`(项目级,放在项目根目录)中。如果你使用了上面的 `/mcp search`,CLI 已经为你创建或更新了此文件,但理解其格式有助于自定义。 + +> ⚠️ **注意**:`.vscode/mcp.json` 不再作为 MCP 配置源支持。如果你有现有的 `.vscode/mcp.json`,请将其迁移到项目根目录下的 `.mcp.json`。CLI 在检测到旧配置文件时会显示迁移提示。 + +```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 服务器](#filesystem-server) | +| 获取最新的库文档 | [Context7 服务器](#context7-server-documentation) | +| 探索可选的进阶功能(自定义服务器、web_fetch) | [进阶内容](#beyond-the-basics) | + +
+Filesystem 服务器 - 让 Copilot 探索你的项目文件 + + +### Filesystem 服务器 + +```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 服务器(filesystem、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 +``` + +这会自动添加该服务器及其相关的 agent skill。安装的 skill 包括: + +- **microsoft-docs**:概念、教程和事实查询 +- **microsoft-code-reference**:API 查询、代码示例和故障排查 +- **microsoft-skill-creator**:用于生成关于 Microsoft 技术的自定义 skill 的元 skill + +**使用方法:** +```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、filesystem、Context7)已经覆盖了大多数使用场景。 + +📖 请参阅[自定义 MCP 服务器指南](mcp-custom-server.md),其中以 book app 为例提供了完整的演练。 + +📚 想了解更多背景,请参阅 [MCP for Beginners 课程](https://github.com/microsoft/mcp-for-beginners)。 + +
+ + + +### 完整的配置文件 + +下面是一个包含 filesystem 和 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` 以全局使用,或保存为项目根目录下的 `.mcp.json` 以进行项目级配置。 + +--- + +# 使用 MCP 服务器 + +现在你已经配置了 MCP 服务器,让我们看看它们能做什么。 + +使用 MCP 服务器 - 一个中心辐射式示意图,显示开发者的 CLI 与 GitHub、Filesystem、Context7 以及自定义/Web Fetch 服务器相连 + +--- + +## 服务器使用示例 + +**挑选一个服务器来探索,或按顺序逐个学习。** + +| 我想试试…… | 跳转到 | +|---|---| +| GitHub 仓库、issue 与 PR | [GitHub 服务器](#github-server-built-in) | +| 浏览项目文件 | [Filesystem 服务器使用](#filesystem-server-usage) | +| 查询库文档 | [Context7 服务器使用](#context7-server-usage) | +| 自定义服务器、Microsoft Learn MCP 与 web_fetch 用法 | [进阶内容用法](#beyond-the-basics-usage) | + +
+GitHub 服务器(内置) - 访问仓库、issue、PR 等等 + + +### 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 +``` + +
+ +| 功能 | 示例 | +|---------|----------| +| **仓库信息** | 查看提交、分支、贡献者 | +| **Issue** | 列出、创建、搜索和评论 issue | +| **Pull Request** | 查看 PR、diff,创建 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 了本课程仓库,你也可以试试写操作,例如创建 issue 和 pull request。我们会在下面的练习中实际操作一下。 + +> ⚠️ **看不到结果?** GitHub MCP 操作的是仓库的远程仓库(在 github.com 上),而不仅仅是本地文件。请确保你的仓库有远程地址:运行 `git remote -v` 进行检查。 + +
+ +
+Filesystem 服务器 - 浏览并分析项目文件 + + +### Filesystem 服务器 + +配置完成后,filesystem 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.md)构建了 book-lookup 服务器,你可以直接查询你的图书集合: + +```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**:使用内置的 `web_fetch` 工具从任何 URL 拉取内容: + +```bash +copilot + +> Fetch and summarize the README from https://github.com/facebook/react +``` + +
+ +--- + +## 多服务器工作流 + +这些工作流展示了为什么开发者会说"再也不想没有它来工作了"。每个示例都在单个会话中组合了多个 MCP 服务器。 + +使用 MCP 的 Issue 到 PR 工作流 - 展示了从获取 GitHub issue 到创建 pull request 的完整流程 + +*完整的 MCP 工作流:GitHub MCP 检索仓库数据,Filesystem MCP 查找代码,Context7 MCP 提供最佳实践,Copilot 负责分析* + +下面的每个示例都是自包含的。**挑选一个你感兴趣的,或者全部读完。** + +| 我想看到…… | 跳转到 | +|---|---| +| 多个服务器协同工作 | [多服务器探索](#multi-server-exploration) | +| 在一个会话中从 issue 走到 PR | [Issue 到 PR 工作流](#issue-to-pr-workflow) | +| 快速进行项目健康检查 | [健康仪表板](#health-dashboard) | + +
+多服务器探索 - 在一个会话中组合 filesystem、GitHub 和 Context7 + + +#### 用多个 MCP 服务器探索 Book App + +```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 工作流演示](../../../06-mcp-servers/images/mcp-workflow-demo.gif) + +*演示输出会有所不同。你的模型、工具和响应会与此处展示的不同。* + +
+ +**结果**:代码探索 → 历史回顾 → 最佳实践查询 → 改进计划。**全部在一个终端会话中完成,同时使用三个 MCP 服务器。** + +
+ +
+Issue 到 PR 工作流 - 不离开终端,从 GitHub issue 走到 pull request + + +#### 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 implements year validation in 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 +``` + +**零复制粘贴。零上下文切换。一个终端会话。** + +
+ +
+健康仪表板 - 使用多个服务器快速进行项目健康检查 + + +#### 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,看到了如何配置服务器,也看到了真实工作流的实际效果。现在该轮到你自己试一试了。 + +--- + +## ▶️ 自己动手试试 + +现在轮到你了!完成这些练习,在 book app 项目上练习使用 MCP 服务器。 + +### 练习 1:检查你的 MCP 状态 + +先看看有哪些 MCP 服务器可用: + +```bash +copilot + +> /mcp show +``` + +你应该会看到 GitHub 服务器被列为已启用。如果没有,请运行 `/login` 进行身份验证。 + +--- + +### 练习 2:用 Filesystem MCP 探索 Book App + +如果你已配置好 filesystem 服务器,用它来探索 book app: + +```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` 及其包含的函数。 + +> 💡 **还没配置 filesystem 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 服务器 + +现在在一个会话中组合 filesystem 和 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 文件(filesystem MCP),列出 5 本书,包括 "The Hobbit"、"1984"、"Dune"、"To Kill a Mockingbird" 和 "Mysterious Book",然后查询 GitHub 获取提交历史。 + +**自我检查**:当你能够解释为什么"检查我的仓库提交历史"比手动运行 `git log` 并把输出粘贴到提示中更好时,你就理解了 MCP。 + +--- + +## 📝 作业 + +### 主要挑战:Book App MCP 探索 + +练习在 book app 项目上同时使用多个 MCP 服务器。在单个 Copilot 会话中完成以下步骤: + +1. **验证 MCP 正在工作**:运行 `/mcp show` 并确认至少 GitHub 服务器已启用 +2. **设置 filesystem MCP**(如果尚未完成):创建 `~/.copilot/mcp-config.json` 并加入 filesystem 服务器配置 +3. **探索代码**:要求 Copilot 使用 filesystem 服务器: + - 列出 `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/` 中文件的提交 + - 检查是否有任何打开的 issue 或 pull request +5. **组合服务器**:在一个提示中,要求 Copilot: + - 读取 `samples/book-app-project/tests/test_books.py` 中的测试文件 + - 将被测试的函数与 `books.py` 中的所有函数进行比较 + - 总结缺少哪些测试覆盖率 + +**成功标准**:你可以在单个 Copilot 会话中无缝地组合 filesystem 和 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 +} +``` +作者为空,年份为 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.md)用 Python 构建你自己的 MCP 服务器,连接到任何 API。 + +--- + +
+🔧 常见错误与故障排查(点击展开) + +### 常见错误 + +| 错误 | 会发生什么 | 修复方法 | +|---------|--------------|-----| +| 不知道 GitHub MCP 是内置的 | 试图手动安装/配置它 | GitHub MCP 默认包含。直接试试:"List the recent commits in this repo" | +| 在错误的位置查找配置 | 找不到或无法编辑 MCP 设置 | 用户级配置在 `~/.copilot/mcp-config.json` 中,项目级配置在项目根目录的 `.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 +# Run the server command manually to see errors +npx -y @modelcontextprotocol/server-github +``` + +**MCP 工具不可用** - 确保服务器已启用: +```bash +copilot + +> /mcp show +# Check if server is listed and enabled +``` + +如果服务器被禁用,请参阅下面[其他 `/mcp` 命令](#-additional-mcp-commands)了解如何重新启用它。 + +
+ +--- + +
+📚 其他 MCP 命令(点击展开) + + +你可以通过两种方式管理 MCP 服务器:在**聊天会话内使用斜杠命令**,或**直接在终端中使用 `copilot mcp` 命令**(不需要进入聊天会话)。 + +### 选项 1:斜杠命令(在聊天会话内) + +这些命令在你已经在 `copilot` 中时可用: + +| 命令 | 作用 | +|---------|--------------| +| `/mcp show` | 显示所有已配置的 MCP 服务器及其状态 | +| `/mcp add` | 交互式地设置以添加新服务器 | +| `/mcp edit ` | 编辑现有服务器配置 | +| `/mcp enable ` | 启用已禁用的服务器(跨会话保留) | +| `/mcp disable ` | 禁用服务器(跨会话保留) | +| `/mcp delete ` | 永久移除服务器 | +| `/mcp auth ` | 重新对使用 OAuth 的 MCP 服务器进行身份验证(例如,在切换账号后) | + +### 选项 2:`copilot mcp` 命令(在终端中) + +你也可以无需先开启聊天会话,直接从终端管理 MCP 服务器: + +```bash +# List all configured MCP servers +copilot mcp list + +# Enable a server +copilot mcp enable filesystem + +# Disable a server +copilot mcp disable context7 +``` + +> 💡 **何时使用哪种?** 当你已经在聊天会话中时,使用 `/mcp` 斜杠命令。当你想在开始会话之前快速检查或更改服务器设置时,从终端使用 `copilot mcp`。 + +在本课程的大部分内容中,`/mcp show` 就是你所需的全部。其他命令会随着你管理更多服务器而逐渐变得有用。 + +
+ +--- + +# 总结 + +## 🔑 核心要点 + +1. **MCP** 将 Copilot 连接到外部服务(GitHub、文件系统、文档) +2. **GitHub MCP 是内置的** —— 无需配置,只需 `/login` +3. **Filesystem 与 Context7** 通过 `~/.copilot/mcp-config.json` 配置 +4. **多服务器工作流** 在单个会话中组合来自多个数据源的数据 +5. **管理服务器有两种方式**:在聊天中使用 `/mcp` 斜杠命令,或在终端中使用 `copilot mcp` +6. **自定义服务器** 让你可以连接任何 API(可选,附录指南中已介绍) + +> 📋 **快速参考**:完整的命令和快捷键列表请参阅 [GitHub Copilot CLI 命令参考](https://docs.github.com/en/copilot/reference/cli-command-reference)。 + +--- + +## ➡️ 下一步 + +你现在已经具备了所有的构建块:模式、上下文、工作流、agent、skill 和 MCP。是时候将它们全部整合起来了。 + +在 **[第 07 章:融会贯通](../07-putting-it-together/README.md)** 中,你将学习: + +- 在统一工作流中组合 agent、skill 和 MCP +- 从想法到合并的 PR 的完整功能开发 +- 使用 hook 进行自动化 +- 团队环境中的最佳实践 + +--- + +**[← 返回第 05 章](../05-skills/README.md)** | **[继续到第 07 章 →](../07-putting-it-together/README.md)** diff --git a/localization/zh-cn/06-mcp-servers/mcp-custom-server.md b/localization/zh-cn/06-mcp-servers/mcp-custom-server.md new file mode 100644 index 00000000..2785f532 --- /dev/null +++ b/localization/zh-cn/06-mcp-servers/mcp-custom-server.md @@ -0,0 +1,176 @@ +# 构建自定义 MCP 服务器 + +> ⚠️ **本内容完全是可选的。** 仅使用预构建的 MCP 服务器(GitHub、filesystem、Context7),你也能高效地使用 Copilot CLI。本指南面向那些希望将 Copilot 连接到自定义内部 API 的开发者。更多详情请参阅 [MCP for Beginners 课程](https://github.com/microsoft/mcp-for-beginners)。 +> +> **前置条件:** +> - 熟悉 Python +> - 理解 `async`/`await` 模式 +> - 系统中可用 `pip`(本开发容器中已包含) +> +> **[← 返回第 06 章:MCP 服务器](README.md)** + +--- + +想把 Copilot 连接到你自己的 API?下面演示如何用 Python 构建一个简单的 MCP 服务器,用于查询图书信息,并将其与你在本课程中一直使用的 book app 项目联系起来。 + +## 项目设置 + +```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 可调用的工具 | +| 类型提示 + 文档字符串 | 告诉 Copilot 每个工具的功能以及它需要什么参数 | +| `mcp.run()` | 启动服务器并监听请求 | + +> 💡 **为什么用装饰器?** `@mcp.tool()` 装饰器就是你所需的全部。MCP SDK 会自动读取你函数的名称、类型提示和文档字符串,从而生成工具的 schema。无需手写 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** —— 用实际的 API 调用或数据库查询替换模拟的 `BOOKS_DB` +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 for Beginners 课程](https://github.com/microsoft/mcp-for-beginners) + +--- + +**[← 返回第 06 章:MCP 服务器](README.md)** diff --git a/localization/zh-cn/07-putting-it-together/README.md b/localization/zh-cn/07-putting-it-together/README.md new file mode 100644 index 00000000..edf3d2e9 --- /dev/null +++ b/localization/zh-cn/07-putting-it-together/README.md @@ -0,0 +1,512 @@ +![第 07 章:融会贯通](../../../07-putting-it-together/images/chapter-header.png) + +> **你所学的一切在此汇聚。在一次会话中,从想法走到合并的 PR。** + +在本章中,你将把所学的一切整合到完整的工作流中。你将通过多智能体协作来构建功能、设置可在提交前发现安全问题的 pre-commit 钩子、把 Copilot 集成到 CI/CD 流水线中,并且在一个终端会话中从功能想法走到合并的 PR。这正是 GitHub Copilot CLI 真正成为效率倍增器的地方。 + +> 💡 **提示**:本章展示如何把你学到的所有内容组合起来。**你不一定需要 agents、skills 或 MCP 才能高效工作(虽然它们会非常有用)。** 核心工作流——描述、计划、实现、测试、审阅、发布——仅靠第 00–03 章中的内置功能就能完成。 + +## 🎯 学习目标 + +学完本章后,你将能够: + +- 在统一的工作流中组合使用 agents、skills 和 MCP(Model Context Protocol,模型上下文协议) +- 用多工具方法构建完整功能 +- 用 hooks 设置基础自动化 +- 应用专业开发的最佳实践 + +> ⏱️ **预计时间**:约 75 分钟(阅读 15 分钟 + 动手实践 60 分钟) + +--- + +## 🧩 现实类比:交响乐团 + +交响乐团类比 —— 统一的工作流 + +一支交响乐团有许多声部: +- **弦乐**奠定基础(就像你的核心工作流) +- **铜管**带来力量(就像具备专长的 agents) +- **木管**增添色彩(就像扩展能力的 skills) +- **打击乐**保持节奏(就像连接外部系统的 MCP) + +单独看,每个声部都很有限。合在一起、由出色的指挥统领,便能演奏出宏大的乐章。 + +**这就是本章要教你的!**
+*就像指挥家带领乐团一样,你也在把 agents、skills 和 MCP 编排成统一的工作流* + +让我们先走一遍这样一个场景:在一次会话中修改代码、生成测试、进行审阅并创建 PR。 + +--- + +## 一次会话,从想法到合并的 PR + +不必在编辑器、终端、测试运行器和 GitHub 网页之间来回切换、每次都丢失上下文,你可以在一个终端会话中把所有工具组合起来。我们将在下面的[集成模式](#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, use /pr to operate on the pull request for the current branch +> /pr [view|create|fix|auto] + +# Or ask naturally if you want Copilot to draft it from the terminal +> Create a pull request titled "Feature: Add list unread books command" +``` + +**传统做法**:在编辑器、终端、测试运行器、文档和 GitHub 网页之间来回切换。每次切换都会带来上下文损失和摩擦。 + +**关键洞察**:你像建筑师一样调度专家,他们处理细节,你掌控全局。 + +> 💡 **更进一步**:对于这种大型多步骤计划,可以试试 `/fleet`,让 Copilot 并行运行相互独立的子任务。详见[官方文档](https://docs.github.com/copilot/concepts/agents/copilot-cli/fleet)。 + +--- + +# 更多工作流 + +一群人正在拼一幅由齿轮组成的彩色巨型拼图,象征 agents、skills 和 MCP 如何组合成统一的工作流 + +对于已经学完第 04–06 章的高级用户,下面这些工作流展示了 agents、skills 和 MCP 如何成倍提升你的效率。 + +## 集成模式 + +下面是组合一切的思维模型: + +集成模式 —— 一个 4 阶段的工作流:收集上下文(MCP)、分析与规划(Agents)、执行(Skills + 手动)、收尾(MCP) + +--- + +## 工作流 1:调查并修复 Bug + +借助完整的工具集成进行真实世界的 Bug 修复: + +```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 钩子对团队很有用,但并不是高效工作的必需品。如果你刚入门,可以跳过。 +> +> ⚠️ **性能提醒**:该钩子会对每个暂存文件调用一次 `copilot -p`,每个文件需要数秒。对于大型提交,建议只检查关键文件,或者改为手动用 `/review` 进行审阅。 + +**git hook**(git 钩子)是 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` 安装,或者把 `timeout 60` 替换成不带超时保护的简单调用。 + +> 📚 **官方文档**:[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:上手新代码库 + +加入新项目时,把上下文、agents 和 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 +``` + +这一工作流把 `@` 上下文、agents 和 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. 区分清楚:Agents、Skills 与自定义指令 + +每种工具都有自己的最佳应用场景: + +```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 +``` + +> 💡 **关键点**:Agents 和 skills 都既能分析、也能生成代码。真正的区别在于 **它们如何被激活** —— agents 需要显式触发(`/agent`),skills 是自动触发(按提示词匹配),而自定义指令则始终生效。 + +### 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`):始终生效的指南,涵盖编码规范、架构规则以及构建/测试/部署步骤。每次会话都会自动遵循。 +- **Prompt 文件**(`.github/prompts/`):可复用、可参数化的提示词,团队可以共享 —— 例如代码评审、组件生成或 PR 描述的模板。 +- **自定义 agents**(`.github/agents/`):编码特定的角色(例如安全审阅员或文档撰写员),团队任何成员都可以通过 `/agent` 激活它们。 +- **自定义 skills**(`.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 在每个 pull request 上自动进行 Copilot 审阅。这包括自动发布审阅评论以及筛选关键问题。 + +> 📖 **了解更多**:完整的 GitHub Actions 工作流、配置选项与排错技巧,请参见 [CI/CD 集成](../../../appendices/ci-cd-integration.md)。 + +--- + +# 实战练习 + +温馨的桌面:显示器上有代码,旁边摆着台灯、咖啡杯和耳机,一切就绪,准备动手实践 + +把完整的工作流付诸实践。 + +--- + +## ▶️ 自己动手试一试 + +完成示例后,可以尝试下面这些变体: + +1. **端到端挑战**:选一个小功能(例如「列出未读书籍」或「导出为 CSV」)。走一遍完整的工作流: + - 用 `/plan` 规划 + - 用 agents(python-reviewer、pytest-helper)做设计 + - 实现 + - 生成测试 + - 创建 PR + +2. **自动化挑战**:按照「自动化代码审阅」工作流设置 pre-commit 钩子。故意在提交中引入一个文件路径漏洞,看看会不会被拦下来? + +3. **你自己的生产工作流**:为一项你常做的任务设计一套属于自己的工作流。把它写成清单。哪些部分可以用 skills、agents 或 hooks 来自动化? + +**自检**:当你能向同事解释 agents、skills 和 MCP 是如何协同工作的,以及什么时候该用哪种工具时,本课程就算学完了。 + +--- + +## 📝 作业 + +### 主挑战:端到端功能 + +动手示例带你走过了构建「列出未读书籍」功能的全过程。现在请用同样的完整工作流练习另一个功能:**按年份范围搜索书籍**: + +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 章配置过 agents,可以尝试创建并使用自定义 agents。例如用一个 error-handler agent 来审阅实现,用一个 doc-writer agent 来更新 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` 把思路理清楚 | +| 多个工具能配合时只用了一个 | 速度更慢、结果不够全面 | 组合使用:用 Agent 做分析 → 用 Skill 执行 → 用 MCP 集成 | +| 提交前没有审阅 | 安全问题或 Bug 被漏过 | 一定要运行 `/review`,或使用 [pre-commit 钩子](#workflow-2-code-review-automation-optional) | +| 忘记把工作流分享给团队 | 每个人都在重新发明轮子 | 把模式沉淀到共享的 agents、skills 和 instructions 中 | + +
+ +--- + +# 总结 + +## 🔑 核心要点 + +1. **集成 > 隔离**:组合使用工具,效果最大化 +2. **上下文优先**:在分析前总是先准备好必要的上下文 +3. **Agents 用于分析,Skills 用于执行**:用对的工具做对的事 +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 | 专属 agents | +| 05 | 可扩展的 skills | +| 06 | 通过 MCP 连接外部系统 | +| 07 | 统一的生产工作流 | + +现在你已经可以把 GitHub Copilot CLI 真正用作开发流程中的效率倍增器了。 + +## ➡️ 下一步 + +学习不会就此止步: + +1. **每天练习**:用 Copilot CLI 处理真实工作 +2. **打造定制工具**:为你的具体需求创建 agents 和 skills +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.md)** | **[返回课程主页 →](../README.md)** diff --git a/localization/zh-cn/README.md b/localization/zh-cn/README.md new file mode 100644 index 00000000..0e82292c --- /dev/null +++ b/localization/zh-cn/README.md @@ -0,0 +1,110 @@ +![面向初学者的 GitHub Copilot CLI](../../images/copilot-banner.png) + +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](../../LICENSE)  +[![Open project in 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)  +[![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  +[![Join 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) + +# 面向初学者的 GitHub Copilot CLI + +> **✨ 学习如何借助 AI 驱动的命令行助手,为你的开发工作流提速。** + +GitHub Copilot CLI 把 AI 助手直接带到你的终端中。无需切换到浏览器或代码编辑器,你就可以提出问题、生成功能完整的应用、审查代码、生成测试,并在不离开命令行的情况下调试问题。 + +把它想象成一位 24/7 随时在线的资深同事——可以阅读你的代码、解释那些让人困惑的写法,并帮助你更高效地工作! + +> 📘 **更喜欢网页体验?** 你可以直接在 GitHub 上学习这门课程,也可以在 [Awesome Copilot](https://awesome-copilot.github.com/learning-hub/cli-for-beginners/) 上以更传统的浏览方式查看。 + +本课程适合: + +- **软件开发者**:希望从命令行使用 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 模式、聊天、行内补全 | +| [**Copilot on GitHub.com**](https://github.com/copilot) | GitHub | 围绕你的仓库进行沉浸式聊天,创建 agent 等 | +| [**GitHub Copilot cloud agent**](https://docs.github.com/copilot/using-github-copilot/using-copilot-coding-agent-to-work-on-tasks) | GitHub | 把 issue 分配给 agent,由它返回 PR | + +本课程聚焦于 **GitHub Copilot CLI**,让 AI 助手直接进入你的终端。 + +## 📚 课程结构 + +![GitHub Copilot CLI 学习路径](../../images/learning-path.png) + +| 章节 | 标题 | 你将构建什么 | +|:-------:|-------|-------------------| +| 00 | 🚀 [快速开始](./00-quick-start/README.md) | 安装与验证 | +| 01 | 👋 [初步上手](./01-setup-and-first-steps/README.md) | 现场演示 + 三种交互模式 | +| 02 | 🔍 [上下文与对话](./02-context-conversations/README.md) | 多文件项目分析 | +| 03 | ⚡ [开发工作流](./03-development-workflows/README.md) | 代码审查、调试、测试生成 | +| 04 | 🤖 [打造专属的 AI 助手](./04-agents-custom-instructions/README.md) | 适配你工作流的自定义 agent | +| 05 | 🛠️ [自动化重复性任务](./05-skills/README.md) | 自动加载的 skill | +| 06 | 🔌 [连接 GitHub、数据库与 API](./06-mcp-servers/README.md) | MCP 服务器集成 | +| 07 | 🎯 [融会贯通](./07-putting-it-together/README.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) +- 📚 **官方文档:** [GitHub Copilot CLI 文档](https://docs.github.com/copilot/concepts/agents/about-copilot-cli) + +## 参与贡献 + +> **注意**:课程中使用的代码经过精心设计,会在审查、解释和调试场景中产生特定类型的输出,因此我们无法接受修改现有代码的 PR。 + +**如何贡献:** + +1. Fork 本仓库并克隆到本地 +2. 创建一个特性分支(`git checkout -b my-improvement`) +3. 进行你的修改 +4. 提交一个 pull request + +## 许可证 + +本项目基于 MIT 开源许可证授权。完整条款请参阅 [LICENSE](../../LICENSE) 文件。 diff --git a/localization/zh-cn/appendices/README.md b/localization/zh-cn/appendices/README.md new file mode 100644 index 00000000..4b42cacc --- /dev/null +++ b/localization/zh-cn/appendices/README.md @@ -0,0 +1,12 @@ +# 附录 + +这些附录涵盖了对核心课程内容的补充话题。它们是可选阅读材料,等你需要这些特定能力时再查阅即可。 + +| 附录 | 简介 | 前置要求 | +|----------|-------------|--------------| +| [更多上下文功能](additional-context.md) | 处理图片以及多目录权限管理 | 第 02 章 | +| [CI/CD 集成](ci-cd-integration.md) | 用于自动化审阅的 GitHub Actions 工作流 | 第 07 章 | + +--- + +**[← 返回课程主页](../README.md)** diff --git a/localization/zh-cn/appendices/additional-context.md b/localization/zh-cn/appendices/additional-context.md new file mode 100644 index 00000000..663cb0b7 --- /dev/null +++ b/localization/zh-cn/appendices/additional-context.md @@ -0,0 +1,140 @@ +# 更多上下文功能 + +> 📖 **前置要求**:阅读本附录前请先完成[第 02 章:上下文与对话](../02-context-conversations/README.md)。 + +本附录介绍两个额外的上下文功能:处理图片,以及在多个目录之间管理权限。 + +--- + +## 处理图片 + +你可以使用 `@` 语法在对话中包含图片。Copilot 能分析截图、设计稿、示意图以及其他视觉内容。 + +### 基本图片引用 + +```bash +copilot + +> @screenshot.png What's happening in this UI? + +# Copilot analyzes the image and responds + +> @mockup.png @current-design.png Compare these two designs + +# You can also drag and drop images or paste from clipboard +``` + +### 支持的图片格式 + +| 格式 | 适合场景 | +|--------|----------| +| PNG | 截图、UI 设计稿、示意图 | +| JPG/JPEG | 照片、复杂图片 | +| GIF | 简单示意图(仅识别第一帧) | +| WebP | 网页截图 | + +### 图片的实际用例 + +**1. UI 调试** +```bash +> @bug-screenshot.png The button doesn't align properly. What CSS might cause this? +``` + +**2. 设计稿落地** +```bash +> @figma-export.png Write the HTML and Tailwind CSS to match this design +``` + +**3. 错误分析** +```bash +> @error-screenshot.png What does this error mean and how do I fix it? +``` + +**4. 架构评审** +```bash +> @whiteboard-diagram.png Convert this architecture diagram to a Mermaid diagram I can put in docs +``` + +**5. 前后对比** +```bash +> @before.png @after.png What changed between these two versions of the UI? +``` + +### 把图片和代码结合起来 + +把图片和代码上下文结合起来,会更加强大: + +```bash +copilot + +> @screenshot-of-bug.png @src/components/Header.jsx +> The header looks wrong in the screenshot. What's causing it in the code? +``` + +### 图片使用小贴士 + +- **裁剪截图**,只保留相关部分(节省上下文 token) +- **使用高对比度**,让你想分析的 UI 元素更清晰 +- **必要时加注释** —— 上传前圈出或高亮问题区域 +- **一张图聚焦一个概念** —— 多张图也行,但要有重点 + +--- + +## 权限模式 + +默认情况下,Copilot 可以访问你当前目录中的文件。要访问其他位置的文件,需要授予权限。 + +### 添加目录 + +```bash +# Add a directory to the allowed list +copilot --add-dir /path/to/other/project + +# Add multiple directories +copilot --add-dir ~/workspace --add-dir /tmp +``` + +### 允许所有路径 + +```bash +# Disable path restrictions entirely (use with caution) +copilot --allow-all-paths +``` + +### 在会话内部 + +```bash +copilot + +> /add-dir /path/to/other/project +# Now you can reference files from that directory + +> /list-dirs +# See all allowed directories + +> /yolo +# Quick alias for /allow-all on — auto-approves all permission prompts +``` + +### 用于自动化 + +```bash +# Allow all permissions for non-interactive scripts +copilot -p "Review @src/" --allow-all + +# Or use the memorable alias +copilot -p "Review @src/" --yolo +``` + +### 何时需要多目录访问 + +下面这些场景中你通常会需要这些权限: + +1. **Monorepo 工作** —— 跨多个包对比代码 +2. **跨项目重构** —— 更新共享库 +3. **文档项目** —— 引用多个代码库 +4. **迁移工作** —— 对比新旧实现 + +--- + +**[← 返回第 02 章](../02-context-conversations/README.md)** | **[返回附录目录](README.md)** diff --git a/localization/zh-cn/appendices/ci-cd-integration.md b/localization/zh-cn/appendices/ci-cd-integration.md new file mode 100644 index 00000000..7353deba --- /dev/null +++ b/localization/zh-cn/appendices/ci-cd-integration.md @@ -0,0 +1,199 @@ +# CI/CD 集成 + +> 📖 **前置要求**:阅读本附录前请先完成[第 07 章:融会贯通](../07-putting-it-together/README.md)。 +> +> ⚠️ **本附录面向已经拥有 CI/CD 流水线的团队。** 如果你不熟悉 GitHub Actions 或 CI/CD 概念,建议先从第 07 章[自动化代码审阅](../07-putting-it-together/README.md#workflow-3-code-review-automation-optional)中介绍的更简单的 pre-commit 钩子方式入手。 + +本附录展示了如何将 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 # Needed to compare with main branch + + - name: Install Copilot CLI + run: npm install -g @github/copilot + + - name: Review Changed Files + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Get list of changed JS/TS files + 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 + + # Use --silent to suppress progress output + 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'); + + // Only post if there's meaningful content + 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 +# Security-only review +copilot --allow-all -p "Security review of @$file. Check for: SQL injection, XSS, hardcoded secrets, authentication issues." --silent + +# Performance-only review +copilot --allow-all -p "Performance review of @$file. Check for: N+1 queries, memory leaks, blocking operations." --silent +``` + +### 处理大型 PR + +对于包含大量文件的 PR,可以考虑分批或限制数量: + +```yaml +# Limit to first 10 files +FILES=$(git diff --name-only origin/main...HEAD | grep -E '\.(js|ts)$' | head -10) + +# Or set a timeout per file +timeout 60 copilot --allow-all -p "Review @$file" --silent || echo "Review timed out" +``` + +### 团队共享配置 + +为了在团队内保持审阅风格一致,可以创建一份共享配置: + +```json +// .copilot/config.json (committed to repo) +{ + "model": "claude-sonnet-4.5", + "permissions": { + "allowedPaths": ["src/**/*", "tests/**/*"], + "deniedPaths": [".env*", "secrets/**/*", "*.min.js"] + } +} +``` + +--- + +## 替代方案:PR 审阅机器人 + +如果想要更复杂的审阅工作流,可以考虑使用 GitHub Copilot 云端 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.md)** | **[返回附录目录](README.md)** From 41aa7bbf8263faab7690855edcc1aedc72db3b95 Mon Sep 17 00:00:00 2001 From: Justin Yoo Date: Wed, 13 May 2026 20:17:11 +0900 Subject: [PATCH 3/8] Update incorrect markdown formatting order --- localization/es-es/00-quick-start/README.md | 4 ++-- localization/es-es/01-setup-and-first-steps/README.md | 6 +++--- localization/es-es/02-context-conversations/README.md | 4 ++-- localization/es-es/03-development-workflows/README.md | 4 ++-- localization/es-es/04-agents-custom-instructions/README.md | 4 ++-- localization/es-es/05-skills/README.md | 6 +++--- localization/es-es/06-mcp-servers/README.md | 4 ++-- localization/es-es/06-mcp-servers/mcp-custom-server.md | 4 ++-- localization/es-es/07-putting-it-together/README.md | 2 +- localization/es-es/README.md | 2 +- localization/es-es/appendices/README.md | 2 +- localization/es-es/appendices/additional-context.md | 2 +- localization/es-es/appendices/ci-cd-integration.md | 2 +- localization/ja-jp/00-quick-start/README.md | 4 ++-- localization/ja-jp/01-setup-and-first-steps/README.md | 6 +++--- localization/ja-jp/02-context-conversations/README.md | 4 ++-- localization/ja-jp/03-development-workflows/README.md | 4 ++-- localization/ja-jp/04-agents-custom-instructions/README.md | 4 ++-- localization/ja-jp/05-skills/README.md | 6 +++--- localization/ja-jp/06-mcp-servers/README.md | 4 ++-- localization/ja-jp/06-mcp-servers/mcp-custom-server.md | 4 ++-- localization/ja-jp/07-putting-it-together/README.md | 2 +- localization/ja-jp/README.md | 2 +- localization/ja-jp/appendices/README.md | 2 +- localization/ja-jp/appendices/additional-context.md | 2 +- localization/ja-jp/appendices/ci-cd-integration.md | 2 +- localization/ko-kr/00-quick-start/README.md | 4 ++-- localization/ko-kr/01-setup-and-first-steps/README.md | 6 +++--- localization/ko-kr/02-context-conversations/README.md | 4 ++-- localization/ko-kr/03-development-workflows/README.md | 4 ++-- localization/ko-kr/04-agents-custom-instructions/README.md | 4 ++-- localization/ko-kr/05-skills/README.md | 6 +++--- localization/ko-kr/06-mcp-servers/README.md | 4 ++-- localization/ko-kr/06-mcp-servers/mcp-custom-server.md | 4 ++-- localization/ko-kr/07-putting-it-together/README.md | 2 +- localization/ko-kr/README.md | 2 +- localization/ko-kr/appendices/README.md | 2 +- localization/ko-kr/appendices/additional-context.md | 2 +- localization/ko-kr/appendices/ci-cd-integration.md | 2 +- localization/pt-br/00-quick-start/README.md | 4 ++-- localization/pt-br/01-setup-and-first-steps/README.md | 6 +++--- localization/pt-br/02-context-conversations/README.md | 4 ++-- localization/pt-br/03-development-workflows/README.md | 4 ++-- localization/pt-br/04-agents-custom-instructions/README.md | 4 ++-- localization/pt-br/05-skills/README.md | 6 +++--- localization/pt-br/06-mcp-servers/README.md | 4 ++-- localization/pt-br/06-mcp-servers/mcp-custom-server.md | 4 ++-- localization/pt-br/07-putting-it-together/README.md | 2 +- localization/pt-br/README.md | 2 +- localization/pt-br/appendices/README.md | 2 +- localization/pt-br/appendices/additional-context.md | 2 +- localization/pt-br/appendices/ci-cd-integration.md | 2 +- localization/zh-cn/00-quick-start/README.md | 4 ++-- localization/zh-cn/01-setup-and-first-steps/README.md | 6 +++--- localization/zh-cn/02-context-conversations/README.md | 4 ++-- localization/zh-cn/03-development-workflows/README.md | 4 ++-- localization/zh-cn/04-agents-custom-instructions/README.md | 4 ++-- localization/zh-cn/05-skills/README.md | 6 +++--- localization/zh-cn/06-mcp-servers/README.md | 4 ++-- localization/zh-cn/06-mcp-servers/mcp-custom-server.md | 4 ++-- localization/zh-cn/07-putting-it-together/README.md | 2 +- localization/zh-cn/README.md | 2 +- localization/zh-cn/appendices/README.md | 2 +- localization/zh-cn/appendices/additional-context.md | 2 +- localization/zh-cn/appendices/ci-cd-integration.md | 2 +- 65 files changed, 115 insertions(+), 115 deletions(-) diff --git a/localization/es-es/00-quick-start/README.md b/localization/es-es/00-quick-start/README.md index 9f159a6f..6c9339b0 100644 --- a/localization/es-es/00-quick-start/README.md +++ b/localization/es-es/00-quick-start/README.md @@ -222,7 +222,7 @@ Eso es todo en cuanto a la instalación. La diversión de verdad empieza en el C - Aprenderás tres formas distintas de usar Copilot CLI - Generarás código funcional a partir de inglés sencillo -**[Continuar al Capítulo 01: Primeros pasos →](../01-setup-and-first-steps/README.md)** +[**Continuar al Capítulo 01: Primeros pasos →**](../01-setup-and-first-steps/README.md) --- @@ -287,4 +287,4 @@ copilot --- -**[Continuar al Capítulo 01: Primeros pasos →](../01-setup-and-first-steps/README.md)** +[**Continuar al Capítulo 01: Primeros pasos →**](../01-setup-and-first-steps/README.md) diff --git a/localization/es-es/01-setup-and-first-steps/README.md b/localization/es-es/01-setup-and-first-steps/README.md index e188fc59..6c902e51 100644 --- a/localization/es-es/01-setup-and-first-steps/README.md +++ b/localization/es-es/01-setup-and-first-steps/README.md @@ -4,7 +4,7 @@ ¡En este capítulo empieza la magia! Vivirás de primera mano por qué los desarrolladores describen GitHub Copilot CLI como tener a un ingeniero senior en marcación rápida. Verás cómo la IA encuentra bugs de seguridad en segundos, te explica código complejo en lenguaje sencillo y genera scripts funcionales al instante. Después dominarás los tres modos de interacción (Interactivo, Plan y Programático) para que sepas exactamente cuál usar en cada tarea. -> ⚠️ **Requisitos previos**: Asegúrate de haber completado primero **[Capítulo 00: Inicio rápido](../00-quick-start/README.md)**. Necesitarás GitHub Copilot CLI instalado y autenticado antes de ejecutar las demos siguientes. +> ⚠️ **Requisitos previos**: Asegúrate de haber completado primero [**Capítulo 00: Inicio rápido**](../00-quick-start/README.md). Necesitarás GitHub Copilot CLI instalado y autenticado antes de ejecutar las demos siguientes. ## 🎯 Objetivos de aprendizaje @@ -679,7 +679,7 @@ Los ejemplos usaron `/plan` para una funcionalidad de búsqueda y `-p` para revi Ahora que entiendes los tres modos, vamos a aprender a darle a Copilot CLI contexto sobre tu código. -En **[Capítulo 02: Contexto y conversaciones](../02-context-conversations/README.md)** aprenderás: +En [**Capítulo 02: Contexto y conversaciones**](../02-context-conversations/README.md) aprenderás: - La sintaxis `@` para referenciar archivos y directorios - Gestión de sesiones con `--resume` y `--continue` @@ -687,4 +687,4 @@ En **[Capítulo 02: Contexto y conversaciones](../02-context-conversations/READM --- -**[← Volver al inicio del curso](../README.md)** | **[Continuar al Capítulo 02 →](../02-context-conversations/README.md)** +[**← Volver al inicio del curso**](../README.md) | [**Continuar al Capítulo 02 →**](../02-context-conversations/README.md) diff --git a/localization/es-es/02-context-conversations/README.md b/localization/es-es/02-context-conversations/README.md index 87780a35..075cd2c9 100644 --- a/localization/es-es/02-context-conversations/README.md +++ b/localization/es-es/02-context-conversations/README.md @@ -895,7 +895,7 @@ copilot --add-dir /path/to/directory Ahora que puedes darle contexto a Copilot CLI, vamos a ponerlo a trabajar en tareas reales de desarrollo. Las técnicas de contexto que acabas de aprender (referencias a archivos, análisis entre archivos y gestión de sesiones) son la base de los potentes flujos de trabajo del próximo capítulo. -En el **[Capítulo 03: Flujos de trabajo de desarrollo](../03-development-workflows/README.md)** aprenderás: +En el [**Capítulo 03: Flujos de trabajo de desarrollo**](../03-development-workflows/README.md) aprenderás: - Flujos de trabajo de revisión de código - Patrones de refactorización @@ -905,4 +905,4 @@ En el **[Capítulo 03: Flujos de trabajo de desarrollo](../03-development-workfl --- -**[← Volver al Capítulo 01](../01-setup-and-first-steps/README.md)** | **[Continuar al Capítulo 03 →](../03-development-workflows/README.md)** +[**← Volver al Capítulo 01**](../01-setup-and-first-steps/README.md) | [**Continuar al Capítulo 03 →**](../03-development-workflows/README.md) diff --git a/localization/es-es/03-development-workflows/README.md b/localization/es-es/03-development-workflows/README.md index 879ff318..3e255f4d 100644 --- a/localization/es-es/03-development-workflows/README.md +++ b/localization/es-es/03-development-workflows/README.md @@ -960,7 +960,7 @@ Los capítulos restantes cubren características adicionales que extienden las c ## Continúa con temas adicionales -En el **[Capítulo 04: Agentes e instrucciones personalizadas](../04-agents-custom-instructions/README.md)** aprenderás: +En el [**Capítulo 04: Agentes e instrucciones personalizadas**](../04-agents-custom-instructions/README.md) aprenderás: - Usar agentes integrados (`/plan`, `/review`) - Crear agentes especializados (experto frontend, auditor de seguridad) con archivos `.agent.md` @@ -969,4 +969,4 @@ En el **[Capítulo 04: Agentes e instrucciones personalizadas](../04-agents-cust --- -**[← Volver al Capítulo 02](../02-context-conversations/README.md)** | **[Continuar al Capítulo 04 →](../04-agents-custom-instructions/README.md)** +[**← Volver al Capítulo 02**](../02-context-conversations/README.md) | [**Continuar al Capítulo 04 →**](../04-agents-custom-instructions/README.md) diff --git a/localization/es-es/04-agents-custom-instructions/README.md b/localization/es-es/04-agents-custom-instructions/README.md index 93080270..61a5b1f3 100644 --- a/localization/es-es/04-agents-custom-instructions/README.md +++ b/localization/es-es/04-agents-custom-instructions/README.md @@ -770,7 +770,7 @@ copilot # This loads custom instructions by default Los agentes cambian *cómo enfoca y ejecuta acciones dirigidas Copilot* en tu código. A continuación aprenderás sobre las **skills**, que cambian *qué pasos* sigue. ¿Te preguntas en qué se diferencian agentes y skills? El Capítulo 05 lo aborda directamente. -En el **[Capítulo 05: Sistema de skills](../05-skills/README.md)**, aprenderás: +En el [**Capítulo 05: Sistema de skills**](../05-skills/README.md), aprenderás: - Cómo las skills se autodisparan a partir de tus prompts (sin necesidad de un slash command) - Instalar skills de la comunidad @@ -780,4 +780,4 @@ En el **[Capítulo 05: Sistema de skills](../05-skills/README.md)**, aprenderás --- -**[← Volver al Capítulo 03](../03-development-workflows/README.md)** | **[Continuar al Capítulo 05 →](../05-skills/README.md)** +[**← Volver al Capítulo 03**](../03-development-workflows/README.md) | [**Continuar al Capítulo 05 →**](../05-skills/README.md) diff --git a/localization/es-es/05-skills/README.md b/localization/es-es/05-skills/README.md index f4a5404d..4e5bf875 100644 --- a/localization/es-es/05-skills/README.md +++ b/localization/es-es/05-skills/README.md @@ -572,7 +572,7 @@ Los plugins pueden agrupar varias capacidades. Un único plugin puede incluir sk También hay skills prefabricadas disponibles en repositorios de la comunidad: -- **[Awesome Copilot](https://github.com/github/awesome-copilot)** - Recursos oficiales de GitHub Copilot incluyendo documentación y ejemplos de skills +- [**Awesome Copilot**](https://github.com/github/awesome-copilot) - Recursos oficiales de GitHub Copilot incluyendo documentación y ejemplos de skills ### Instalar una skill de la comunidad con GitHub CLI @@ -874,7 +874,7 @@ Ejecuta `/skills reload` después de crear o editar skills para asegurarte de qu Las skills amplían lo que Copilot puede hacer con instrucciones cargadas automáticamente. Pero, ¿qué pasa con conectarse a servicios externos? Ahí es donde entra MCP. -En el **[Capítulo 06: Servidores MCP](../06-mcp-servers/README.md)**, aprenderás: +En el [**Capítulo 06: Servidores MCP**](../06-mcp-servers/README.md), aprenderás: - Qué es MCP (Model Context Protocol) - Conectar a GitHub, sistema de archivos y servicios de documentación @@ -883,4 +883,4 @@ En el **[Capítulo 06: Servidores MCP](../06-mcp-servers/README.md)**, aprender --- -**[← Volver al Capítulo 04](../04-agents-custom-instructions/README.md)** | **[Continuar al Capítulo 06 →](../06-mcp-servers/README.md)** +[**← Volver al Capítulo 04**](../04-agents-custom-instructions/README.md) | [**Continuar al Capítulo 06 →**](../06-mcp-servers/README.md) diff --git a/localization/es-es/06-mcp-servers/README.md b/localization/es-es/06-mcp-servers/README.md index 6a4a5d85..38f0bb13 100644 --- a/localization/es-es/06-mcp-servers/README.md +++ b/localization/es-es/06-mcp-servers/README.md @@ -962,7 +962,7 @@ Para la mayor parte de este curso, `/mcp show` es todo lo que necesitas. Los dem Ya tienes todos los bloques: modos, contexto, flujos de trabajo, agentes, skills y MCP. Es hora de combinarlos. -En el **[Capítulo 07: Combinando todo](../07-putting-it-together/README.md)** aprenderás: +En el [**Capítulo 07: Combinando todo**](../07-putting-it-together/README.md) aprenderás: - Combinar agentes, skills y MCP en flujos de trabajo unificados - Desarrollo completo de funcionalidades de la idea al PR fusionado @@ -971,4 +971,4 @@ En el **[Capítulo 07: Combinando todo](../07-putting-it-together/README.md)** a --- -**[← Volver al Capítulo 05](../05-skills/README.md)** | **[Continuar al Capítulo 07 →](../07-putting-it-together/README.md)** +[**← Volver al Capítulo 05**](../05-skills/README.md) | [**Continuar al Capítulo 07 →**](../07-putting-it-together/README.md) diff --git a/localization/es-es/06-mcp-servers/mcp-custom-server.md b/localization/es-es/06-mcp-servers/mcp-custom-server.md index 37fe226b..40073d2d 100644 --- a/localization/es-es/06-mcp-servers/mcp-custom-server.md +++ b/localization/es-es/06-mcp-servers/mcp-custom-server.md @@ -7,7 +7,7 @@ > - Comprender los patrones `async`/`await` > - Tener `pip` disponible en tu sistema (incluido en este dev container) > -> **[← Volver al Capítulo 06: Servidores MCP](README.md)** +> [**← Volver al Capítulo 06: Servidores MCP**](README.md) --- @@ -173,4 +173,4 @@ Una vez que hayas construido un servidor básico, puedes: --- -**[← Volver al Capítulo 06: Servidores MCP](README.md)** +[**← Volver al Capítulo 06: Servidores MCP**](README.md) diff --git a/localization/es-es/07-putting-it-together/README.md b/localization/es-es/07-putting-it-together/README.md index 10a6bb8d..58d486e3 100644 --- a/localization/es-es/07-putting-it-together/README.md +++ b/localization/es-es/07-putting-it-together/README.md @@ -509,4 +509,4 @@ Tu aprendizaje no termina aquí: **¡Buen trabajo! Ahora ve a construir algo increíble.** -**[← Volver al Capítulo 06](../06-mcp-servers/README.md)** | **[Volver al inicio del curso →](../README.md)** +[**← Volver al Capítulo 06**](../06-mcp-servers/README.md) | [**Volver al inicio del curso →**](../README.md) diff --git a/localization/es-es/README.md b/localization/es-es/README.md index 147d1f3c..2503c05a 100644 --- a/localization/es-es/README.md +++ b/localization/es-es/README.md @@ -87,7 +87,7 @@ Cada capítulo sigue el mismo patrón: ## 📋 Referencia de comandos de GitHub Copilot CLI -La **[referencia de comandos de GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference)** te ayuda a encontrar comandos y atajos de teclado para usar Copilot CLI de forma eficaz. +La [**referencia de comandos de GitHub Copilot CLI**](https://docs.github.com/en/copilot/reference/cli-command-reference) te ayuda a encontrar comandos y atajos de teclado para usar Copilot CLI de forma eficaz. ## 🙋 Obtener ayuda diff --git a/localization/es-es/appendices/README.md b/localization/es-es/appendices/README.md index a4592325..d3843459 100644 --- a/localization/es-es/appendices/README.md +++ b/localization/es-es/appendices/README.md @@ -9,4 +9,4 @@ Estos apéndices cubren temas adicionales que amplían el contenido principal de --- -**[← Volver al inicio del curso](../README.md)** +[**← Volver al inicio del curso**](../README.md) diff --git a/localization/es-es/appendices/additional-context.md b/localization/es-es/appendices/additional-context.md index 9097f790..e023b1c1 100644 --- a/localization/es-es/appendices/additional-context.md +++ b/localization/es-es/appendices/additional-context.md @@ -137,4 +137,4 @@ Escenarios comunes donde necesitarás estos permisos: --- -**[← Volver al Capítulo 02](../02-context-conversations/README.md)** | **[Volver a los apéndices](README.md)** +[**← Volver al Capítulo 02**](../02-context-conversations/README.md) | [**Volver a los apéndices**](README.md) diff --git a/localization/es-es/appendices/ci-cd-integration.md b/localization/es-es/appendices/ci-cd-integration.md index cb26037e..fe19b418 100644 --- a/localization/es-es/appendices/ci-cd-integration.md +++ b/localization/es-es/appendices/ci-cd-integration.md @@ -196,4 +196,4 @@ fi --- -**[← Volver al Capítulo 07](../07-putting-it-together/README.md)** | **[Volver a los apéndices](README.md)** +[**← Volver al Capítulo 07**](../07-putting-it-together/README.md) | [**Volver a los apéndices**](README.md) diff --git a/localization/ja-jp/00-quick-start/README.md b/localization/ja-jp/00-quick-start/README.md index 237287b0..c7209cfa 100644 --- a/localization/ja-jp/00-quick-start/README.md +++ b/localization/ja-jp/00-quick-start/README.md @@ -222,7 +222,7 @@ copilot - Copilot CLI を使う 3 つの方法を学ぶ - 平易な日本語からコードを生成する -**[第 01 章: はじめの一歩に進む →](../01-setup-and-first-steps/README.md)** +[**第 01 章: はじめの一歩に進む →**](../01-setup-and-first-steps/README.md) --- @@ -287,4 +287,4 @@ copilot --- -**[第 01 章: はじめの一歩に進む →](../01-setup-and-first-steps/README.md)** +[**第 01 章: はじめの一歩に進む →**](../01-setup-and-first-steps/README.md) diff --git a/localization/ja-jp/01-setup-and-first-steps/README.md b/localization/ja-jp/01-setup-and-first-steps/README.md index 2819619b..8ea9c742 100644 --- a/localization/ja-jp/01-setup-and-first-steps/README.md +++ b/localization/ja-jp/01-setup-and-first-steps/README.md @@ -4,7 +4,7 @@ この章から本当の楽しさが始まります!GitHub Copilot CLI を「シニアエンジニアをスピードダイヤルに登録している」と表現する開発者の理由を、実際に体験していただきます。AI がセキュリティバグを数秒で見つけ、複雑なコードを平易な言葉で説明し、動作するスクリプトを即座に生成する様子を見た後、3 つのインタラクションモード(インタラクティブ、プラン、プログラマティック)をマスターして、どのタスクにどのモードを使えばよいか正確に理解しましょう。 -> ⚠️ **前提条件**: 先に **[第 00 章: クイックスタート](../00-quick-start/README.md)** を完了していることを確認してください。以下のデモを実行するには、GitHub Copilot CLI がインストールされ、認証済みである必要があります。 +> ⚠️ **前提条件**: 先に [**第 00 章: クイックスタート**](../00-quick-start/README.md) を完了していることを確認してください。以下のデモを実行するには、GitHub Copilot CLI がインストールされ、認証済みである必要があります。 ## 🎯 学習目標 @@ -679,7 +679,7 @@ Copilot CLI がリンクを表示し、QR コードへのアクセスを提供 3 つのモードを理解したので、次はコードについて Copilot CLI にコンテキストを提供する方法を学びましょう。 -**[第 02 章: コンテキストと会話](../02-context-conversations/README.md)**では以下を学びます。 +[**第 02 章: コンテキストと会話**](../02-context-conversations/README.md)では以下を学びます。 - ファイルとディレクトリを参照するための `@` 構文 - `--resume` と `--continue` を使ったセッション管理 @@ -687,4 +687,4 @@ Copilot CLI がリンクを表示し、QR コードへのアクセスを提供 --- -**[← コースホームに戻る](../README.md)** | **[第 02 章に進む →](../02-context-conversations/README.md)** +[**← コースホームに戻る**](../README.md) | [**第 02 章に進む →**](../02-context-conversations/README.md) diff --git a/localization/ja-jp/02-context-conversations/README.md b/localization/ja-jp/02-context-conversations/README.md index a7dbbc06..b38d5f11 100644 --- a/localization/ja-jp/02-context-conversations/README.md +++ b/localization/ja-jp/02-context-conversations/README.md @@ -895,7 +895,7 @@ copilot --add-dir /path/to/directory Copilot CLI にコンテキストを提供できるようになったので、実際の開発タスクに活用しましょう。今学んだコンテキスト技術(ファイル参照、クロスファイル分析、セッション管理)は次の章の強力なワークフローの基礎となります。 -**[第 03 章: 開発ワークフロー](../03-development-workflows/README.md)**では以下を学びます。 +[**第 03 章: 開発ワークフロー**](../03-development-workflows/README.md)では以下を学びます。 - コードレビューワークフロー - リファクタリングパターン @@ -905,4 +905,4 @@ Copilot CLI にコンテキストを提供できるようになったので、 --- -**[← 第 01 章に戻る](../01-setup-and-first-steps/README.md)** | **[第 03 章に進む →](../03-development-workflows/README.md)** +[**← 第 01 章に戻る**](../01-setup-and-first-steps/README.md) | [**第 03 章に進む →**](../03-development-workflows/README.md) diff --git a/localization/ja-jp/03-development-workflows/README.md b/localization/ja-jp/03-development-workflows/README.md index b9ca4b89..b9eaaac5 100644 --- a/localization/ja-jp/03-development-workflows/README.md +++ b/localization/ja-jp/03-development-workflows/README.md @@ -959,7 +959,7 @@ GitHub Copilot CLI を使う唯一の「正しい」方法はありません。 ## 追加トピックに進む -**[第 04 章: エージェントとカスタム指示](../04-agents-custom-instructions/README.md)**では以下を学びます。 +[**第 04 章: エージェントとカスタム指示**](../04-agents-custom-instructions/README.md)では以下を学びます。 - 組み込みエージェント(`/plan`、`/review`)の使用 - `.agent.md` ファイルを使った特化したエージェントの作成(フロントエンドエキスパート、セキュリティ監査員) @@ -968,4 +968,4 @@ GitHub Copilot CLI を使う唯一の「正しい」方法はありません。 --- -**[← 第 02 章に戻る](../02-context-conversations/README.md)** | **[第 04 章に進む →](../04-agents-custom-instructions/README.md)** +[**← 第 02 章に戻る**](../02-context-conversations/README.md) | [**第 04 章に進む →**](../04-agents-custom-instructions/README.md) diff --git a/localization/ja-jp/04-agents-custom-instructions/README.md b/localization/ja-jp/04-agents-custom-instructions/README.md index 80adb2af..1fc50684 100644 --- a/localization/ja-jp/04-agents-custom-instructions/README.md +++ b/localization/ja-jp/04-agents-custom-instructions/README.md @@ -770,7 +770,7 @@ copilot # デフォルトでカスタム指示を読み込む エージェントは Copilot がコードに*どのようにアプローチして対象を絞ったアクションを取るか*を変えます。次は**スキル**について学びます - これは*どのステップ*に従うかを変えます。エージェントとスキルの違いが気になりますか?第 05 章でそれを正面から取り上げます。 -**[第 05 章: スキルシステム](../05-skills/README.md)**では以下を学びます。 +[**第 05 章: スキルシステム**](../05-skills/README.md)では以下を学びます。 - スキルがプロンプトから自動的にトリガーされる方法(スラッシュコマンド不要) - コミュニティスキルのインストール @@ -780,4 +780,4 @@ copilot # デフォルトでカスタム指示を読み込む --- -**[← 第 03 章に戻る](../03-development-workflows/README.md)** | **[第 05 章に進む →](../05-skills/README.md)** +[**← 第 03 章に戻る**](../03-development-workflows/README.md) | [**第 05 章に進む →**](../05-skills/README.md) diff --git a/localization/ja-jp/05-skills/README.md b/localization/ja-jp/05-skills/README.md index c6ebefcb..aeb1ce5c 100644 --- a/localization/ja-jp/05-skills/README.md +++ b/localization/ja-jp/05-skills/README.md @@ -572,7 +572,7 @@ copilot plugin marketplace update プリメイドスキルはコミュニティリポジトリからも入手できます。 -- **[Awesome Copilot](https://github.com/github/awesome-copilot)** - スキルのドキュメントと例を含む公式 GitHub Copilot リソース +- [**Awesome Copilot**](https://github.com/github/awesome-copilot) - スキルのドキュメントと例を含む公式 GitHub Copilot リソース ### GitHub CLI でコミュニティスキルをインストールする @@ -874,7 +874,7 @@ copilot スキルは自動読み込みの指示で Copilot ができることを拡張します。しかし外部サービスへの接続はどうでしょうか?そこで MCP の出番です。 -**[第 06 章: MCP サーバー](../06-mcp-servers/README.md)**では以下を学びます。 +[**第 06 章: MCP サーバー**](../06-mcp-servers/README.md)では以下を学びます。 - MCP(Model Context Protocol)とは何か - GitHub、ファイルシステム、ドキュメントサービスへの接続 @@ -883,4 +883,4 @@ copilot --- -**[← 第 04 章に戻る](../04-agents-custom-instructions/README.md)** | **[第 06 章に進む →](../06-mcp-servers/README.md)** +[**← 第 04 章に戻る**](../04-agents-custom-instructions/README.md) | [**第 06 章に進む →**](../06-mcp-servers/README.md) diff --git a/localization/ja-jp/06-mcp-servers/README.md b/localization/ja-jp/06-mcp-servers/README.md index 35a364e0..50f79921 100644 --- a/localization/ja-jp/06-mcp-servers/README.md +++ b/localization/ja-jp/06-mcp-servers/README.md @@ -962,7 +962,7 @@ copilot mcp disable context7 これですべてのビルディングブロックが揃いました: モード、コンテキスト、ワークフロー、エージェント、スキル、MCP。すべてを組み合わせる時間です。 -**[第 07 章: すべてをまとめる](../07-putting-it-together/README.md)**では以下を学びます。 +[**第 07 章: すべてをまとめる**](../07-putting-it-together/README.md)では以下を学びます。 - エージェント、スキル、MCP を統合ワークフローで組み合わせる - アイデアからマージされた PR までの完全な機能開発 @@ -971,4 +971,4 @@ copilot mcp disable context7 --- -**[← 第 05 章に戻る](../05-skills/README.md)** | **[第 07 章に進む →](../07-putting-it-together/README.md)** +[**← 第 05 章に戻る**](../05-skills/README.md) | [**第 07 章に進む →**](../07-putting-it-together/README.md) diff --git a/localization/ja-jp/06-mcp-servers/mcp-custom-server.md b/localization/ja-jp/06-mcp-servers/mcp-custom-server.md index 49c9400c..4016f245 100644 --- a/localization/ja-jp/06-mcp-servers/mcp-custom-server.md +++ b/localization/ja-jp/06-mcp-servers/mcp-custom-server.md @@ -7,7 +7,7 @@ > - `async`/`await` パターンを理解している > - システムで `pip` が利用可能(この開発コンテナに含まれている) > -> **[← 第 06 章: MCP サーバーに戻る](README.md)** +> [**← 第 06 章: MCP サーバーに戻る**](README.md) --- @@ -173,4 +173,4 @@ copilot --- -**[← 第 06 章: MCP サーバーに戻る](README.md)** +[**← 第 06 章: MCP サーバーに戻る**](README.md) diff --git a/localization/ja-jp/07-putting-it-together/README.md b/localization/ja-jp/07-putting-it-together/README.md index 97a2e1fb..49570289 100644 --- a/localization/ja-jp/07-putting-it-together/README.md +++ b/localization/ja-jp/07-putting-it-together/README.md @@ -509,4 +509,4 @@ Include: Summary, Changes Made, Testing Done, Screenshots Needed" **素晴らしい仕事をしました!今度は素晴らしいものを作りましょう。** -**[← 第 06 章に戻る](../06-mcp-servers/README.md)** | **[コースホームに戻る →](../README.md)** +[**← 第 06 章に戻る**](../06-mcp-servers/README.md) | [**コースホームに戻る →**](../README.md) diff --git a/localization/ja-jp/README.md b/localization/ja-jp/README.md index 58ff8126..b2c6a7d6 100644 --- a/localization/ja-jp/README.md +++ b/localization/ja-jp/README.md @@ -87,7 +87,7 @@ GitHub Copilot は AI を活用したツールのファミリーへと進化し ## 📋 GitHub Copilot CLI コマンドリファレンス {#-github-copilot-cli-command-reference} -**[GitHub Copilot CLI コマンドリファレンス](https://docs.github.com/en/copilot/reference/cli-command-reference)** では、Copilot CLI を効果的に使うためのコマンドやキーボードショートカットを確認できます。 +[**GitHub Copilot CLI コマンドリファレンス**](https://docs.github.com/en/copilot/reference/cli-command-reference) では、Copilot CLI を効果的に使うためのコマンドやキーボードショートカットを確認できます。 ## 🙋 ヘルプを得るには diff --git a/localization/ja-jp/appendices/README.md b/localization/ja-jp/appendices/README.md index a34f276d..dec57652 100644 --- a/localization/ja-jp/appendices/README.md +++ b/localization/ja-jp/appendices/README.md @@ -9,4 +9,4 @@ --- -**[← コースホームに戻る](../README.md)** +[**← コースホームに戻る**](../README.md) diff --git a/localization/ja-jp/appendices/additional-context.md b/localization/ja-jp/appendices/additional-context.md index 4738fc19..b31cfb9f 100644 --- a/localization/ja-jp/appendices/additional-context.md +++ b/localization/ja-jp/appendices/additional-context.md @@ -137,4 +137,4 @@ copilot -p "Review @src/" --yolo --- -**[← 第 02 章に戻る](../02-context-conversations/README.md)** | **[付録に戻る](README.md)** +[**← 第 02 章に戻る**](../02-context-conversations/README.md) | [**付録に戻る**](README.md) diff --git a/localization/ja-jp/appendices/ci-cd-integration.md b/localization/ja-jp/appendices/ci-cd-integration.md index 0a007931..fcb4a1d2 100644 --- a/localization/ja-jp/appendices/ci-cd-integration.md +++ b/localization/ja-jp/appendices/ci-cd-integration.md @@ -196,4 +196,4 @@ fi --- -**[← 第 07 章に戻る](../07-putting-it-together/README.md)** | **[付録に戻る](README.md)** +[**← 第 07 章に戻る**](../07-putting-it-together/README.md) | [**付録に戻る**](README.md) diff --git a/localization/ko-kr/00-quick-start/README.md b/localization/ko-kr/00-quick-start/README.md index 0a82cffd..c2317450 100644 --- a/localization/ko-kr/00-quick-start/README.md +++ b/localization/ko-kr/00-quick-start/README.md @@ -222,7 +222,7 @@ copilot - Copilot CLI를 사용하는 세 가지 방식 학습 - 일반 영어 설명으로 동작하는 코드 생성 -**[챕터 01로 계속: 첫걸음 →](../01-setup-and-first-steps/README.md)** +[**챕터 01로 계속: 첫걸음 →**](../01-setup-and-first-steps/README.md) --- @@ -287,4 +287,4 @@ copilot --- -**[챕터 01로 계속: 첫걸음 →](../01-setup-and-first-steps/README.md)** +[**챕터 01로 계속: 첫걸음 →**](../01-setup-and-first-steps/README.md) diff --git a/localization/ko-kr/01-setup-and-first-steps/README.md b/localization/ko-kr/01-setup-and-first-steps/README.md index 1901927e..f704abca 100644 --- a/localization/ko-kr/01-setup-and-first-steps/README.md +++ b/localization/ko-kr/01-setup-and-first-steps/README.md @@ -4,7 +4,7 @@ 이 챕터에서 진정한 마법이 시작됩니다! 개발자들이 GitHub Copilot CLI를 "빠른 통화 한 통으로 시니어 엔지니어를 부르는 것"이라고 표현하는 이유를 직접 경험하게 됩니다. AI가 초 단위로 보안 버그를 발견하고, 복잡한 코드를 쉬운 영어로 설명하고, 즉시 동작하는 스크립트를 생성하는 모습을 보게 됩니다. 그런 다음 세 가지 상호작용 모드(Interactive, Plan, Programmatic)를 마스터하여 어떤 작업에 어떤 모드를 사용해야 하는지 정확히 알게 됩니다. -> ⚠️ **사전 요건**: 아직 **[챕터 00: 빠른 시작](../00-quick-start/README.md)**을 완료하지 않았다면 먼저 완료하세요. 아래 데모를 실행하기 전에 GitHub Copilot CLI가 설치되고 인증되어 있어야 합니다. +> ⚠️ **사전 요건**: 아직 [**챕터 00: 빠른 시작**](../00-quick-start/README.md)을 완료하지 않았다면 먼저 완료하세요. 아래 데모를 실행하기 전에 GitHub Copilot CLI가 설치되고 인증되어 있어야 합니다. ## 🎯 학습 목표 @@ -679,7 +679,7 @@ Copilot CLI가 링크를 표시하고 QR 코드에 접근할 수 있게 합니 세 가지 모드를 이해했으니 이제 Copilot CLI에 코드에 대한 컨텍스트를 제공하는 방법을 배워 봅시다. -**[챕터 02: 컨텍스트와 대화](../02-context-conversations/README.md)**에서 배울 내용: +[**챕터 02: 컨텍스트와 대화**](../02-context-conversations/README.md)에서 배울 내용: - 파일과 디렉터리를 참조하는 `@` 문법 - `--resume`과 `--continue`를 사용한 세션 관리 @@ -687,4 +687,4 @@ Copilot CLI가 링크를 표시하고 QR 코드에 접근할 수 있게 합니 --- -**[← 강의 홈으로](../README.md)** | **[챕터 02로 계속 →](../02-context-conversations/README.md)** +[**← 강의 홈으로**](../README.md) | [**챕터 02로 계속 →**](../02-context-conversations/README.md) diff --git a/localization/ko-kr/02-context-conversations/README.md b/localization/ko-kr/02-context-conversations/README.md index a3f432f6..d20b8065 100644 --- a/localization/ko-kr/02-context-conversations/README.md +++ b/localization/ko-kr/02-context-conversations/README.md @@ -896,7 +896,7 @@ copilot --add-dir /path/to/directory 이제 Copilot CLI에 컨텍스트를 제공할 수 있게 되었으니, 실제 개발 작업에 활용해 봅시다. 방금 배운 컨텍스트 기술(파일 참조, 교차 파일 분석, 세션 관리)은 다음 장의 강력한 워크플로의 토대가 됩니다. -**[3장: 개발 워크플로](../03-development-workflows/README.md)** 에서는 다음을 배웁니다. +[**3장: 개발 워크플로**](../03-development-workflows/README.md) 에서는 다음을 배웁니다. - 코드 리뷰 워크플로 - 리팩터링 패턴 @@ -906,4 +906,4 @@ copilot --add-dir /path/to/directory --- -**[← 1장으로 돌아가기](../01-setup-and-first-steps/README.md)** | **[3장으로 계속하기 →](../03-development-workflows/README.md)** +[**← 1장으로 돌아가기**](../01-setup-and-first-steps/README.md) | [**3장으로 계속하기 →**](../03-development-workflows/README.md) diff --git a/localization/ko-kr/03-development-workflows/README.md b/localization/ko-kr/03-development-workflows/README.md index c4885ded..514a60f3 100644 --- a/localization/ko-kr/03-development-workflows/README.md +++ b/localization/ko-kr/03-development-workflows/README.md @@ -960,7 +960,7 @@ GitHub Copilot CLI를 사용하는 단 하나의 "정답"은 없습니다. 자 ## 추가 주제로 계속하기 -**[Chapter 04: Agents and Custom Instructions](../04-agents-custom-instructions/README.md)**에서는 다음을 배웁니다. +[**Chapter 04: Agents and Custom Instructions**](../04-agents-custom-instructions/README.md)에서는 다음을 배웁니다. - 내장 에이전트(`/plan`, `/review`) 사용 - `.agent.md` 파일로 전문화된 에이전트(프론트엔드 전문가, 보안 감사자) 만들기 @@ -969,4 +969,4 @@ GitHub Copilot CLI를 사용하는 단 하나의 "정답"은 없습니다. 자 --- -**[← Chapter 02로 돌아가기](../02-context-conversations/README.md)** | **[Chapter 04로 계속하기 →](../04-agents-custom-instructions/README.md)** +[**← Chapter 02로 돌아가기**](../02-context-conversations/README.md) | [**Chapter 04로 계속하기 →**](../04-agents-custom-instructions/README.md) diff --git a/localization/ko-kr/04-agents-custom-instructions/README.md b/localization/ko-kr/04-agents-custom-instructions/README.md index 40e82578..573df35c 100644 --- a/localization/ko-kr/04-agents-custom-instructions/README.md +++ b/localization/ko-kr/04-agents-custom-instructions/README.md @@ -770,7 +770,7 @@ copilot # This loads custom instructions by default 에이전트는 *Copilot이 코드에 접근하고 목적에 맞춰 행동하는 방식*을 바꿉니다. 다음으로 배울 **skill**은 *어떤 단계*를 따르는지를 바꿉니다. 에이전트와 skill의 차이가 궁금하신가요? 5장에서 정면으로 다룹니다. -**[5장: Skills 시스템](../05-skills/README.md)** 에서는 다음을 배웁니다: +[**5장: Skills 시스템**](../05-skills/README.md) 에서는 다음을 배웁니다: - 슬래시 명령 없이 프롬프트에서 자동으로 트리거되는 skill - 커뮤니티 skill 설치 @@ -780,4 +780,4 @@ copilot # This loads custom instructions by default --- -**[← 3장으로 돌아가기](../03-development-workflows/README.md)** | **[5장으로 계속 →](../05-skills/README.md)** +[**← 3장으로 돌아가기**](../03-development-workflows/README.md) | [**5장으로 계속 →**](../05-skills/README.md) diff --git a/localization/ko-kr/05-skills/README.md b/localization/ko-kr/05-skills/README.md index 5f912269..87de1cec 100644 --- a/localization/ko-kr/05-skills/README.md +++ b/localization/ko-kr/05-skills/README.md @@ -572,7 +572,7 @@ copilot plugin marketplace update 미리 만들어진 스킬은 커뮤니티 저장소에서도 받을 수 있습니다: -- **[Awesome Copilot](https://github.com/github/awesome-copilot)** - 스킬 문서와 예제를 포함한 공식 GitHub Copilot 리소스 +- [**Awesome Copilot**](https://github.com/github/awesome-copilot) - 스킬 문서와 예제를 포함한 공식 GitHub Copilot 리소스 ### GitHub CLI로 커뮤니티 스킬 설치하기 @@ -874,7 +874,7 @@ copilot 스킬은 자동 로드되는 지시문으로 Copilot이 할 수 있는 일을 확장합니다. 그렇다면 외부 서비스에 연결하는 것은 어떨까요? 그것이 바로 MCP의 역할입니다. -**[Chapter 06: MCP Servers](../06-mcp-servers/README.md)**에서는 다음을 배웁니다: +[**Chapter 06: MCP Servers**](../06-mcp-servers/README.md)에서는 다음을 배웁니다: - MCP(Model Context Protocol)란 무엇인가 - GitHub, 파일 시스템, 문서 서비스에 연결하기 @@ -883,4 +883,4 @@ copilot --- -**[← Chapter 04로 돌아가기](../04-agents-custom-instructions/README.md)** | **[Chapter 06으로 계속하기 →](../06-mcp-servers/README.md)** +[**← Chapter 04로 돌아가기**](../04-agents-custom-instructions/README.md) | [**Chapter 06으로 계속하기 →**](../06-mcp-servers/README.md) diff --git a/localization/ko-kr/06-mcp-servers/README.md b/localization/ko-kr/06-mcp-servers/README.md index 75fdc8c7..699e3683 100644 --- a/localization/ko-kr/06-mcp-servers/README.md +++ b/localization/ko-kr/06-mcp-servers/README.md @@ -962,7 +962,7 @@ copilot mcp disable context7 이제 모든 구성 요소를 갖추셨습니다: 모드, 컨텍스트, 워크플로, 에이전트, 스킬, MCP. 이제 모두 합쳐 볼 시간입니다. -**[챕터 07: 모두 합치기](../07-putting-it-together/README.md)**에서는 다음을 배웁니다: +[**챕터 07: 모두 합치기**](../07-putting-it-together/README.md)에서는 다음을 배웁니다: - 통합된 워크플로에서 에이전트, 스킬, MCP 결합하기 - 아이디어부터 병합된 PR까지 완전한 기능 개발 @@ -971,4 +971,4 @@ copilot mcp disable context7 --- -**[← 챕터 05로 돌아가기](../05-skills/README.md)** | **[챕터 07로 계속 →](../07-putting-it-together/README.md)** +[**← 챕터 05로 돌아가기**](../05-skills/README.md) | [**챕터 07로 계속 →**](../07-putting-it-together/README.md) diff --git a/localization/ko-kr/06-mcp-servers/mcp-custom-server.md b/localization/ko-kr/06-mcp-servers/mcp-custom-server.md index 1f058d7f..d5439fe0 100644 --- a/localization/ko-kr/06-mcp-servers/mcp-custom-server.md +++ b/localization/ko-kr/06-mcp-servers/mcp-custom-server.md @@ -7,7 +7,7 @@ > - `async`/`await` 패턴 이해 > - 시스템에 `pip` 설치 (이 dev container에는 포함되어 있습니다) > -> **[← 6장으로 돌아가기: MCP 서버](README.md)** +> [**← 6장으로 돌아가기: MCP 서버**](README.md) --- @@ -173,4 +173,4 @@ copilot --- -**[← 6장으로 돌아가기: MCP 서버](README.md)** +[**← 6장으로 돌아가기: MCP 서버**](README.md) diff --git a/localization/ko-kr/07-putting-it-together/README.md b/localization/ko-kr/07-putting-it-together/README.md index dc03cd03..7718a52d 100644 --- a/localization/ko-kr/07-putting-it-together/README.md +++ b/localization/ko-kr/07-putting-it-together/README.md @@ -509,4 +509,4 @@ Include: Summary, Changes Made, Testing Done, Screenshots Needed" **정말 잘하셨습니다! 이제 멋진 것을 직접 만들어 볼 차례입니다.** -**[← 6장으로 돌아가기](../06-mcp-servers/README.md)** | **[강의 홈으로 돌아가기 →](../README.md)** +[**← 6장으로 돌아가기**](../06-mcp-servers/README.md) | [**강의 홈으로 돌아가기 →**](../README.md) diff --git a/localization/ko-kr/README.md b/localization/ko-kr/README.md index ef9d4717..502406e1 100644 --- a/localization/ko-kr/README.md +++ b/localization/ko-kr/README.md @@ -87,7 +87,7 @@ GitHub Copilot은 AI 기반 도구의 제품군으로 발전했습니다. 각 ## 📋 GitHub Copilot CLI 명령어 참조 -**[GitHub Copilot CLI 명령어 참조](https://docs.github.com/en/copilot/reference/cli-command-reference)**에서 Copilot CLI를 효과적으로 사용하는 데 도움이 되는 명령어와 키보드 단축키를 찾아볼 수 있습니다. +[**GitHub Copilot CLI 명령어 참조**](https://docs.github.com/en/copilot/reference/cli-command-reference)에서 Copilot CLI를 효과적으로 사용하는 데 도움이 되는 명령어와 키보드 단축키를 찾아볼 수 있습니다. ## 🙋 도움 받기 diff --git a/localization/ko-kr/appendices/README.md b/localization/ko-kr/appendices/README.md index a1ebd743..cd5f2450 100644 --- a/localization/ko-kr/appendices/README.md +++ b/localization/ko-kr/appendices/README.md @@ -9,4 +9,4 @@ --- -**[← 강의 홈으로 돌아가기](../README.md)** +[**← 강의 홈으로 돌아가기**](../README.md) diff --git a/localization/ko-kr/appendices/additional-context.md b/localization/ko-kr/appendices/additional-context.md index 31632588..9c6b84ed 100644 --- a/localization/ko-kr/appendices/additional-context.md +++ b/localization/ko-kr/appendices/additional-context.md @@ -137,4 +137,4 @@ copilot -p "Review @src/" --yolo --- -**[← 2장으로 돌아가기](../02-context-conversations/README.md)** | **[부록 목록으로 돌아가기](README.md)** +[**← 2장으로 돌아가기**](../02-context-conversations/README.md) | [**부록 목록으로 돌아가기**](README.md) diff --git a/localization/ko-kr/appendices/ci-cd-integration.md b/localization/ko-kr/appendices/ci-cd-integration.md index 7013f4b5..d8f32864 100644 --- a/localization/ko-kr/appendices/ci-cd-integration.md +++ b/localization/ko-kr/appendices/ci-cd-integration.md @@ -196,4 +196,4 @@ fi --- -**[← 7장으로 돌아가기](../07-putting-it-together/README.md)** | **[부록 목록으로 돌아가기](README.md)** +[**← 7장으로 돌아가기**](../07-putting-it-together/README.md) | [**부록 목록으로 돌아가기**](README.md) diff --git a/localization/pt-br/00-quick-start/README.md b/localization/pt-br/00-quick-start/README.md index cd51509d..b7fb8858 100644 --- a/localization/pt-br/00-quick-start/README.md +++ b/localization/pt-br/00-quick-start/README.md @@ -222,7 +222,7 @@ Quando terminar, você pode sair do Copilot CLI: - Aprender três formas diferentes de usar o Copilot CLI - Gerar código funcional a partir de linguagem natural -**[Continuar para o Capítulo 01: Primeiros Passos →](../01-setup-and-first-steps/README.md)** +[**Continuar para o Capítulo 01: Primeiros Passos →**](../01-setup-and-first-steps/README.md) --- @@ -287,4 +287,4 @@ copilot --- -**[Continuar para o Capítulo 01: Primeiros Passos →](../01-setup-and-first-steps/README.md)** +[**Continuar para o Capítulo 01: Primeiros Passos →**](../01-setup-and-first-steps/README.md) diff --git a/localization/pt-br/01-setup-and-first-steps/README.md b/localization/pt-br/01-setup-and-first-steps/README.md index 25982075..63169b6d 100644 --- a/localization/pt-br/01-setup-and-first-steps/README.md +++ b/localization/pt-br/01-setup-and-first-steps/README.md @@ -4,7 +4,7 @@ Este capítulo é onde a mágica começa! Você vai experimentar em primeira mão por que os desenvolvedores descrevem o GitHub Copilot CLI como ter um engenheiro sênior disponível a qualquer hora. Você verá a IA encontrar bugs de segurança em segundos, terá código complexo explicado em linguagem simples e gerará scripts funcionais instantaneamente. Em seguida, você dominará os três modos de interação (Interativo, Plan e Programático) para saber exatamente qual usar para cada tarefa. -> ⚠️ **Pré-requisitos**: Certifique-se de ter concluído o **[Capítulo 00: Início Rápido](../00-quick-start/README.md)** primeiro. Você precisará do GitHub Copilot CLI instalado e autenticado antes de executar as demos abaixo. +> ⚠️ **Pré-requisitos**: Certifique-se de ter concluído o [**Capítulo 00: Início Rápido**](../00-quick-start/README.md) primeiro. Você precisará do GitHub Copilot CLI instalado e autenticado antes de executar as demos abaixo. ## 🎯 Objetivos de aprendizado @@ -679,7 +679,7 @@ Os exemplos usaram `/plan` para uma funcionalidade de busca e `-p` para revisõe Agora que você entende os três modos, vamos aprender a fornecer contexto ao Copilot CLI sobre o seu código. -No **[Capítulo 02: Contexto e Conversas](../02-context-conversations/README.md)**, você aprenderá: +No [**Capítulo 02: Contexto e Conversas**](../02-context-conversations/README.md), você aprenderá: - A sintaxe `@` para referenciar arquivos e diretórios - Gerenciamento de sessões com `--resume` e `--continue` @@ -687,4 +687,4 @@ No **[Capítulo 02: Contexto e Conversas](../02-context-conversations/README.md) --- -**[← Voltar ao Início do Curso](../README.md)** | **[Continuar para o Capítulo 02 →](../02-context-conversations/README.md)** +[**← Voltar ao Início do Curso**](../README.md) | [**Continuar para o Capítulo 02 →**](../02-context-conversations/README.md) diff --git a/localization/pt-br/02-context-conversations/README.md b/localization/pt-br/02-context-conversations/README.md index 3569db72..813f900c 100644 --- a/localization/pt-br/02-context-conversations/README.md +++ b/localization/pt-br/02-context-conversations/README.md @@ -895,7 +895,7 @@ copilot --add-dir /caminho/para/diretório Agora que você pode fornecer contexto ao Copilot CLI, vamos colocá-lo para trabalhar em tarefas reais de desenvolvimento. As técnicas de contexto que você acabou de aprender (referências de arquivo, análise entre arquivos e gerenciamento de sessões) são a base para os fluxos de trabalho poderosos do próximo capítulo. -No **[Capítulo 03: Fluxos de Trabalho de Desenvolvimento](../03-development-workflows/README.md)**, você aprenderá: +No [**Capítulo 03: Fluxos de Trabalho de Desenvolvimento**](../03-development-workflows/README.md), você aprenderá: - Fluxos de trabalho de revisão de código - Padrões de refatoração @@ -905,4 +905,4 @@ No **[Capítulo 03: Fluxos de Trabalho de Desenvolvimento](../03-development-wor --- -**[← Voltar ao Capítulo 01](../01-setup-and-first-steps/README.md)** | **[Continuar para o Capítulo 03 →](../03-development-workflows/README.md)** +[**← Voltar ao Capítulo 01**](../01-setup-and-first-steps/README.md) | [**Continuar para o Capítulo 03 →**](../03-development-workflows/README.md) diff --git a/localization/pt-br/03-development-workflows/README.md b/localization/pt-br/03-development-workflows/README.md index 04fd456b..a02521d3 100644 --- a/localization/pt-br/03-development-workflows/README.md +++ b/localization/pt-br/03-development-workflows/README.md @@ -960,7 +960,7 @@ Os capítulos restantes cobrem funcionalidades adicionais que estendem as capaci ## Continuar para Tópicos Adicionais -No **[Capítulo 04: Agentes e Instruções Personalizadas](../04-agents-custom-instructions/README.md)**, você aprenderá: +No [**Capítulo 04: Agentes e Instruções Personalizadas**](../04-agents-custom-instructions/README.md), você aprenderá: - Usar agentes integrados (`/plan`, `/review`) - Criar agentes especializados (especialista em frontend, auditor de segurança) com arquivos `.agent.md` @@ -969,4 +969,4 @@ No **[Capítulo 04: Agentes e Instruções Personalizadas](../04-agents-custom-i --- -**[← Voltar ao Capítulo 02](../02-context-conversations/README.md)** | **[Continuar para o Capítulo 04 →](../04-agents-custom-instructions/README.md)** +[**← Voltar ao Capítulo 02**](../02-context-conversations/README.md) | [**Continuar para o Capítulo 04 →**](../04-agents-custom-instructions/README.md) diff --git a/localization/pt-br/04-agents-custom-instructions/README.md b/localization/pt-br/04-agents-custom-instructions/README.md index 7990700f..6b01a3d9 100644 --- a/localization/pt-br/04-agents-custom-instructions/README.md +++ b/localization/pt-br/04-agents-custom-instructions/README.md @@ -770,7 +770,7 @@ copilot # Isso carrega instruções personalizadas por padrão Agentes mudam *como o Copilot aborda e toma ações direcionadas* no seu código. A seguir, você aprenderá sobre **skills** - que mudam *quais etapas* ele segue. Quer saber como agentes e skills diferem? O Capítulo 05 aborda isso diretamente. -No **[Capítulo 05: Sistema de Skills](../05-skills/README.md)**, você aprenderá: +No [**Capítulo 05: Sistema de Skills**](../05-skills/README.md), você aprenderá: - Como as skills são acionadas automaticamente pelos seus prompts (sem slash command necessário) - Instalar skills da comunidade @@ -780,4 +780,4 @@ No **[Capítulo 05: Sistema de Skills](../05-skills/README.md)**, você aprender --- -**[← Voltar ao Capítulo 03](../03-development-workflows/README.md)** | **[Continuar para o Capítulo 05 →](../05-skills/README.md)** +[**← Voltar ao Capítulo 03**](../03-development-workflows/README.md) | [**Continuar para o Capítulo 05 →**](../05-skills/README.md) diff --git a/localization/pt-br/05-skills/README.md b/localization/pt-br/05-skills/README.md index d328d218..ce21be5b 100644 --- a/localization/pt-br/05-skills/README.md +++ b/localization/pt-br/05-skills/README.md @@ -572,7 +572,7 @@ Plugins podem agrupar múltiplas capacidades juntas. Um único plugin pode inclu Skills pré-prontas também estão disponíveis em repositórios da comunidade: -- **[Awesome Copilot](https://github.com/github/awesome-copilot)** - Recursos oficiais do GitHub Copilot incluindo documentação e exemplos de skills +- [**Awesome Copilot**](https://github.com/github/awesome-copilot) - Recursos oficiais do GitHub Copilot incluindo documentação e exemplos de skills ### Instalando uma Skill da Comunidade com o GitHub CLI @@ -874,7 +874,7 @@ Execute `/skills reload` após criar ou editar skills para garantir que as alter Skills ampliam o que o Copilot pode fazer com instruções carregadas automaticamente. Mas e quanto a se conectar a serviços externos? É aí que entra o MCP. -No **[Capítulo 06: Servidores MCP](../06-mcp-servers/README.md)**, você aprenderá: +No [**Capítulo 06: Servidores MCP**](../06-mcp-servers/README.md), você aprenderá: - O que é MCP (Model Context Protocol) - Conectar ao GitHub, sistema de arquivos e serviços de documentação @@ -883,4 +883,4 @@ No **[Capítulo 06: Servidores MCP](../06-mcp-servers/README.md)**, você aprend --- -**[← Voltar ao Capítulo 04](../04-agents-custom-instructions/README.md)** | **[Continuar para o Capítulo 06 →](../06-mcp-servers/README.md)** +[**← Voltar ao Capítulo 04**](../04-agents-custom-instructions/README.md) | [**Continuar para o Capítulo 06 →**](../06-mcp-servers/README.md) diff --git a/localization/pt-br/06-mcp-servers/README.md b/localization/pt-br/06-mcp-servers/README.md index 420cd815..4eb81943 100644 --- a/localization/pt-br/06-mcp-servers/README.md +++ b/localization/pt-br/06-mcp-servers/README.md @@ -962,7 +962,7 @@ Para a maior parte deste curso, `/mcp show` é tudo que você precisa. Os outros Agora você tem todos os blocos de construção: modos, contexto, fluxos de trabalho, agentes, skills e MCP. Hora de colocá-los todos juntos. -No **[Capítulo 07: Colocando Tudo Junto](../07-putting-it-together/README.md)**, você aprenderá: +No [**Capítulo 07: Colocando Tudo Junto**](../07-putting-it-together/README.md), você aprenderá: - Combinar agentes, skills e MCP em fluxos de trabalho unificados - Desenvolvimento completo de funcionalidades de ideia a PR mesclado @@ -971,4 +971,4 @@ No **[Capítulo 07: Colocando Tudo Junto](../07-putting-it-together/README.md)** --- -**[← Voltar ao Capítulo 05](../05-skills/README.md)** | **[Continuar para o Capítulo 07 →](../07-putting-it-together/README.md)** +[**← Voltar ao Capítulo 05**](../05-skills/README.md) | [**Continuar para o Capítulo 07 →**](../07-putting-it-together/README.md) diff --git a/localization/pt-br/06-mcp-servers/mcp-custom-server.md b/localization/pt-br/06-mcp-servers/mcp-custom-server.md index 6a643009..07ef6b2f 100644 --- a/localization/pt-br/06-mcp-servers/mcp-custom-server.md +++ b/localization/pt-br/06-mcp-servers/mcp-custom-server.md @@ -7,7 +7,7 @@ > - Entendimento de padrões `async`/`await` > - `pip` disponível no seu sistema (incluído neste dev container) > -> **[← Voltar ao Capítulo 06: Servidores MCP](README.md)** +> [**← Voltar ao Capítulo 06: Servidores MCP**](README.md) --- @@ -173,4 +173,4 @@ Uma vez que você construiu um servidor básico, você pode: --- -**[← Voltar ao Capítulo 06: Servidores MCP](README.md)** +[**← Voltar ao Capítulo 06: Servidores MCP**](README.md) diff --git a/localization/pt-br/07-putting-it-together/README.md b/localization/pt-br/07-putting-it-together/README.md index c7c1bae7..92847fc9 100644 --- a/localization/pt-br/07-putting-it-together/README.md +++ b/localization/pt-br/07-putting-it-together/README.md @@ -509,4 +509,4 @@ Seu aprendizado não para aqui: **Ótimo trabalho! Agora vá construir algo incrível.** -**[← Voltar ao Capítulo 06](../06-mcp-servers/README.md)** | **[Retornar ao Início do Curso →](../README.md)** +[**← Voltar ao Capítulo 06**](../06-mcp-servers/README.md) | [**Retornar ao Início do Curso →**](../README.md) diff --git a/localization/pt-br/README.md b/localization/pt-br/README.md index 5977fcb7..a58cdf41 100644 --- a/localization/pt-br/README.md +++ b/localization/pt-br/README.md @@ -87,7 +87,7 @@ Cada capítulo segue o mesmo padrão: ## 📋 Referência de comandos do GitHub Copilot CLI -A **[referência de comandos do GitHub Copilot CLI](https://docs.github.com/en/copilot/reference/cli-command-reference)** ajuda você a encontrar comandos e atalhos de teclado para usar o Copilot CLI com eficiência. +A [**referência de comandos do GitHub Copilot CLI**](https://docs.github.com/en/copilot/reference/cli-command-reference) ajuda você a encontrar comandos e atalhos de teclado para usar o Copilot CLI com eficiência. ## 🙋 Obtendo ajuda diff --git a/localization/pt-br/appendices/README.md b/localization/pt-br/appendices/README.md index 19214ad7..c219ebcc 100644 --- a/localization/pt-br/appendices/README.md +++ b/localization/pt-br/appendices/README.md @@ -9,4 +9,4 @@ Esses apêndices cobrem tópicos adicionais que ampliam o conteúdo principal do --- -**[← Retornar ao Início do Curso](../README.md)** +[**← Retornar ao Início do Curso**](../README.md) diff --git a/localization/pt-br/appendices/additional-context.md b/localization/pt-br/appendices/additional-context.md index d0d51744..49be16a7 100644 --- a/localization/pt-br/appendices/additional-context.md +++ b/localization/pt-br/appendices/additional-context.md @@ -137,4 +137,4 @@ Cenários comuns onde você precisará dessas permissões: --- -**[← Voltar ao Capítulo 02](../02-context-conversations/README.md)** | **[Retornar aos Apêndices](README.md)** +[**← Voltar ao Capítulo 02**](../02-context-conversations/README.md) | [**Retornar aos Apêndices**](README.md) diff --git a/localization/pt-br/appendices/ci-cd-integration.md b/localization/pt-br/appendices/ci-cd-integration.md index 146d5b8d..ccc9b661 100644 --- a/localization/pt-br/appendices/ci-cd-integration.md +++ b/localization/pt-br/appendices/ci-cd-integration.md @@ -196,4 +196,4 @@ fi --- -**[← Voltar ao Capítulo 07](../07-putting-it-together/README.md)** | **[Retornar aos Apêndices](README.md)** +[**← Voltar ao Capítulo 07**](../07-putting-it-together/README.md) | [**Retornar aos Apêndices**](README.md) diff --git a/localization/zh-cn/00-quick-start/README.md b/localization/zh-cn/00-quick-start/README.md index c5539094..8d353649 100644 --- a/localization/zh-cn/00-quick-start/README.md +++ b/localization/zh-cn/00-quick-start/README.md @@ -222,7 +222,7 @@ copilot - 学习使用 Copilot CLI 的三种不同方式 - 用普通英语生成可运行的代码 -**[继续学习第 01 章:初步上手 →](../01-setup-and-first-steps/README.md)** +[**继续学习第 01 章:初步上手 →**](../01-setup-and-first-steps/README.md) --- @@ -287,4 +287,4 @@ copilot --- -**[继续学习第 01 章:初步上手 →](../01-setup-and-first-steps/README.md)** +[**继续学习第 01 章:初步上手 →**](../01-setup-and-first-steps/README.md) diff --git a/localization/zh-cn/01-setup-and-first-steps/README.md b/localization/zh-cn/01-setup-and-first-steps/README.md index 7809c544..e350a966 100644 --- a/localization/zh-cn/01-setup-and-first-steps/README.md +++ b/localization/zh-cn/01-setup-and-first-steps/README.md @@ -4,7 +4,7 @@ 本章是魔法开始的地方!你将亲身体验为什么开发者把 GitHub Copilot CLI 形容为「随时能拨通的资深工程师」。你将看到 AI 在几秒钟内找出安全漏洞,用通俗的语言解释复杂的代码,并即时生成可用的脚本。然后你将掌握三种交互模式(Interactive、Plan 和 Programmatic),让你清楚地知道任何任务该使用哪一种。 -> ⚠️ **前置条件**:请确保你已经完成了 **[第 00 章:快速入门](../00-quick-start/README.md)**。在运行下面的演示之前,你需要先安装并完成 GitHub Copilot CLI 的身份认证。 +> ⚠️ **前置条件**:请确保你已经完成了 [**第 00 章:快速入门**](../00-quick-start/README.md)。在运行下面的演示之前,你需要先安装并完成 GitHub Copilot CLI 的身份认证。 ## 🎯 学习目标 @@ -679,7 +679,7 @@ Copilot CLI 会显示一个链接并提供一个 QR 码。在你的手机上或 现在你已经理解了三种模式,让我们来学习如何向 Copilot CLI 提供关于你代码的上下文。 -在 **[第 02 章:上下文与对话](../02-context-conversations/README.md)** 中,你将学习: +在 [**第 02 章:上下文与对话**](../02-context-conversations/README.md) 中,你将学习: - 用于引用文件和目录的 `@` 语法 - 使用 `--resume` 和 `--continue` 进行会话管理 @@ -687,4 +687,4 @@ Copilot CLI 会显示一个链接并提供一个 QR 码。在你的手机上或 --- -**[← 返回课程主页](../README.md)** | **[继续到第 02 章 →](../02-context-conversations/README.md)** +[**← 返回课程主页**](../README.md) | [**继续到第 02 章 →**](../02-context-conversations/README.md) diff --git a/localization/zh-cn/02-context-conversations/README.md b/localization/zh-cn/02-context-conversations/README.md index f5f0d318..bb12eaf1 100644 --- a/localization/zh-cn/02-context-conversations/README.md +++ b/localization/zh-cn/02-context-conversations/README.md @@ -895,7 +895,7 @@ copilot --add-dir /path/to/directory 既然你已经能给 Copilot CLI 提供上下文了,就让它真正在实际开发任务中派上用场吧。你刚刚学到的上下文技巧(文件引用、跨文件分析和会话管理)正是下一章中那些强大工作流的基础。 -在 **[第 03 章:开发工作流](../03-development-workflows/README.md)** 中,你将学习: +在 [**第 03 章:开发工作流**](../03-development-workflows/README.md) 中,你将学习: - 代码审查工作流 - 重构模式 @@ -905,4 +905,4 @@ copilot --add-dir /path/to/directory --- -**[← 返回第 01 章](../01-setup-and-first-steps/README.md)** | **[继续到第 03 章 →](../03-development-workflows/README.md)** +[**← 返回第 01 章**](../01-setup-and-first-steps/README.md) | [**继续到第 03 章 →**](../03-development-workflows/README.md) diff --git a/localization/zh-cn/03-development-workflows/README.md b/localization/zh-cn/03-development-workflows/README.md index af6035ad..ad509f7d 100644 --- a/localization/zh-cn/03-development-workflows/README.md +++ b/localization/zh-cn/03-development-workflows/README.md @@ -960,7 +960,7 @@ copilot ## 继续学习更多主题 -在 **[第 04 章:智能体与自定义指令](../04-agents-custom-instructions/README.md)** 中,你将学到: +在 [**第 04 章:智能体与自定义指令**](../04-agents-custom-instructions/README.md) 中,你将学到: - 使用内置智能体(`/plan`、`/review`) - 用 `.agent.md` 文件创建专门的智能体(前端专家、安全审计员) @@ -969,4 +969,4 @@ copilot --- -**[← 返回第 02 章](../02-context-conversations/README.md)** | **[继续到第 04 章 →](../04-agents-custom-instructions/README.md)** +[**← 返回第 02 章**](../02-context-conversations/README.md) | [**继续到第 04 章 →**](../04-agents-custom-instructions/README.md) diff --git a/localization/zh-cn/04-agents-custom-instructions/README.md b/localization/zh-cn/04-agents-custom-instructions/README.md index 65ab3d34..a98f6a63 100644 --- a/localization/zh-cn/04-agents-custom-instructions/README.md +++ b/localization/zh-cn/04-agents-custom-instructions/README.md @@ -770,7 +770,7 @@ copilot # This loads custom instructions by default 智能体改变的是 *Copilot 在你的代码中如何思考问题、采取有针对性的行动* 的方式。接下来,你将了解 **技能(skills)**——它们改变的是 Copilot 遵循的 *步骤*。想知道智能体和技能到底有什么不同?第 05 章会正面回答这个问题。 -在 **[第 05 章:Skills 系统](../05-skills/README.md)** 中,你将学到: +在 [**第 05 章:Skills 系统**](../05-skills/README.md) 中,你将学到: - 技能如何根据你的提示自动触发(无需斜杠命令) - 安装社区提供的技能 @@ -780,4 +780,4 @@ copilot # This loads custom instructions by default --- -**[← 返回第 03 章](../03-development-workflows/README.md)** | **[继续学习第 05 章 →](../05-skills/README.md)** +[**← 返回第 03 章**](../03-development-workflows/README.md) | [**继续学习第 05 章 →**](../05-skills/README.md) diff --git a/localization/zh-cn/05-skills/README.md b/localization/zh-cn/05-skills/README.md index b5effeb6..9724c499 100644 --- a/localization/zh-cn/05-skills/README.md +++ b/localization/zh-cn/05-skills/README.md @@ -572,7 +572,7 @@ copilot plugin marketplace update 预制好的技能也可以从社区仓库中获取: -- **[Awesome Copilot](https://github.com/github/awesome-copilot)** —— GitHub 官方的 Copilot 资源,包含技能文档与示例 +- [**Awesome Copilot**](https://github.com/github/awesome-copilot) —— GitHub 官方的 Copilot 资源,包含技能文档与示例 ### 使用 GitHub CLI 安装社区技能 @@ -874,7 +874,7 @@ copilot 技能通过自动加载的指令扩展了 Copilot 能做的事情。但要连接外部服务怎么办?这就是 MCP 的用武之地。 -在**[第 06 章:MCP 服务器](../06-mcp-servers/README.md)**中,你将学习: +在[**第 06 章:MCP 服务器**](../06-mcp-servers/README.md)中,你将学习: - 什么是 MCP(Model Context Protocol,模型上下文协议) - 连接到 GitHub、文件系统和文档服务 @@ -883,4 +883,4 @@ copilot --- -**[← 返回第 04 章](../04-agents-custom-instructions/README.md)** | **[继续到第 06 章 →](../06-mcp-servers/README.md)** +[**← 返回第 04 章**](../04-agents-custom-instructions/README.md) | [**继续到第 06 章 →**](../06-mcp-servers/README.md) diff --git a/localization/zh-cn/06-mcp-servers/README.md b/localization/zh-cn/06-mcp-servers/README.md index 7ce4465a..6a97feb3 100644 --- a/localization/zh-cn/06-mcp-servers/README.md +++ b/localization/zh-cn/06-mcp-servers/README.md @@ -962,7 +962,7 @@ copilot mcp disable context7 你现在已经具备了所有的构建块:模式、上下文、工作流、agent、skill 和 MCP。是时候将它们全部整合起来了。 -在 **[第 07 章:融会贯通](../07-putting-it-together/README.md)** 中,你将学习: +在 [**第 07 章:融会贯通**](../07-putting-it-together/README.md) 中,你将学习: - 在统一工作流中组合 agent、skill 和 MCP - 从想法到合并的 PR 的完整功能开发 @@ -971,4 +971,4 @@ copilot mcp disable context7 --- -**[← 返回第 05 章](../05-skills/README.md)** | **[继续到第 07 章 →](../07-putting-it-together/README.md)** +[**← 返回第 05 章**](../05-skills/README.md) | [**继续到第 07 章 →**](../07-putting-it-together/README.md) diff --git a/localization/zh-cn/06-mcp-servers/mcp-custom-server.md b/localization/zh-cn/06-mcp-servers/mcp-custom-server.md index 2785f532..0b1e9cf4 100644 --- a/localization/zh-cn/06-mcp-servers/mcp-custom-server.md +++ b/localization/zh-cn/06-mcp-servers/mcp-custom-server.md @@ -7,7 +7,7 @@ > - 理解 `async`/`await` 模式 > - 系统中可用 `pip`(本开发容器中已包含) > -> **[← 返回第 06 章:MCP 服务器](README.md)** +> [**← 返回第 06 章:MCP 服务器**](README.md) --- @@ -173,4 +173,4 @@ copilot --- -**[← 返回第 06 章:MCP 服务器](README.md)** +[**← 返回第 06 章:MCP 服务器**](README.md) diff --git a/localization/zh-cn/07-putting-it-together/README.md b/localization/zh-cn/07-putting-it-together/README.md index edf3d2e9..d90b8354 100644 --- a/localization/zh-cn/07-putting-it-together/README.md +++ b/localization/zh-cn/07-putting-it-together/README.md @@ -509,4 +509,4 @@ Include: Summary, Changes Made, Testing Done, Screenshots Needed" **干得漂亮!现在去打造一些精彩的东西吧。** -**[← 返回第 06 章](../06-mcp-servers/README.md)** | **[返回课程主页 →](../README.md)** +[**← 返回第 06 章**](../06-mcp-servers/README.md) | [**返回课程主页 →**](../README.md) diff --git a/localization/zh-cn/README.md b/localization/zh-cn/README.md index 0e82292c..55b80161 100644 --- a/localization/zh-cn/README.md +++ b/localization/zh-cn/README.md @@ -87,7 +87,7 @@ GitHub Copilot 已经发展成为一系列 AI 驱动的工具。下面是各个 ## 📋 GitHub Copilot CLI 命令参考 -**[GitHub Copilot CLI 命令参考文档](https://docs.github.com/en/copilot/reference/cli-command-reference)** 可以帮你查找命令和键盘快捷键,从而更高效地使用 Copilot CLI。 +[**GitHub Copilot CLI 命令参考文档**](https://docs.github.com/en/copilot/reference/cli-command-reference) 可以帮你查找命令和键盘快捷键,从而更高效地使用 Copilot CLI。 ## 🙋 获取帮助 diff --git a/localization/zh-cn/appendices/README.md b/localization/zh-cn/appendices/README.md index 4b42cacc..be964b55 100644 --- a/localization/zh-cn/appendices/README.md +++ b/localization/zh-cn/appendices/README.md @@ -9,4 +9,4 @@ --- -**[← 返回课程主页](../README.md)** +[**← 返回课程主页**](../README.md) diff --git a/localization/zh-cn/appendices/additional-context.md b/localization/zh-cn/appendices/additional-context.md index 663cb0b7..6289c59c 100644 --- a/localization/zh-cn/appendices/additional-context.md +++ b/localization/zh-cn/appendices/additional-context.md @@ -137,4 +137,4 @@ copilot -p "Review @src/" --yolo --- -**[← 返回第 02 章](../02-context-conversations/README.md)** | **[返回附录目录](README.md)** +[**← 返回第 02 章**](../02-context-conversations/README.md) | [**返回附录目录**](README.md) diff --git a/localization/zh-cn/appendices/ci-cd-integration.md b/localization/zh-cn/appendices/ci-cd-integration.md index 7353deba..2b3cc473 100644 --- a/localization/zh-cn/appendices/ci-cd-integration.md +++ b/localization/zh-cn/appendices/ci-cd-integration.md @@ -196,4 +196,4 @@ fi --- -**[← 返回第 07 章](../07-putting-it-together/README.md)** | **[返回附录目录](README.md)** +[**← 返回第 07 章**](../07-putting-it-together/README.md) | [**返回附录目录**](README.md) From fa2946c3daacd99d3b5578ba548c8b9a3acd5b71 Mon Sep 17 00:00:00 2001 From: Justin Yoo Date: Wed, 13 May 2026 20:30:17 +0900 Subject: [PATCH 4/8] docs(l10n): localize internal anchor links to translated heading slugs Re-map [text](#anchor) and cross-file [text](path#anchor) targets so they point to the localized heading slugs rather than the original English slugs. Preserves leading-hyphen status from the original anchor and mirrors github-slugger semantics for translated heading text. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- localization/es-es/00-quick-start/README.md | 2 +- .../es-es/02-context-conversations/README.md | 16 ++++++++-------- .../es-es/03-development-workflows/README.md | 4 ++-- .../04-agents-custom-instructions/README.md | 14 +++++++------- localization/es-es/06-mcp-servers/README.md | 14 +++++++------- .../es-es/07-putting-it-together/README.md | 4 ++-- localization/ja-jp/00-quick-start/README.md | 2 +- .../ja-jp/02-context-conversations/README.md | 16 ++++++++-------- .../ja-jp/03-development-workflows/README.md | 4 ++-- .../04-agents-custom-instructions/README.md | 14 +++++++------- localization/ja-jp/06-mcp-servers/README.md | 14 +++++++------- .../ja-jp/07-putting-it-together/README.md | 4 ++-- localization/ja-jp/README.md | 2 +- localization/ko-kr/00-quick-start/README.md | 2 +- .../ko-kr/02-context-conversations/README.md | 16 ++++++++-------- .../ko-kr/03-development-workflows/README.md | 4 ++-- .../04-agents-custom-instructions/README.md | 14 +++++++------- localization/ko-kr/06-mcp-servers/README.md | 14 +++++++------- .../ko-kr/07-putting-it-together/README.md | 4 ++-- localization/ko-kr/README.md | 2 +- localization/pt-br/00-quick-start/README.md | 2 +- .../pt-br/02-context-conversations/README.md | 16 ++++++++-------- .../pt-br/03-development-workflows/README.md | 4 ++-- .../04-agents-custom-instructions/README.md | 12 ++++++------ localization/pt-br/06-mcp-servers/README.md | 14 +++++++------- .../pt-br/07-putting-it-together/README.md | 4 ++-- localization/zh-cn/00-quick-start/README.md | 2 +- .../zh-cn/02-context-conversations/README.md | 16 ++++++++-------- .../zh-cn/03-development-workflows/README.md | 4 ++-- .../04-agents-custom-instructions/README.md | 14 +++++++------- localization/zh-cn/06-mcp-servers/README.md | 14 +++++++------- .../zh-cn/07-putting-it-together/README.md | 4 ++-- localization/zh-cn/README.md | 2 +- 33 files changed, 137 insertions(+), 137 deletions(-) diff --git a/localization/es-es/00-quick-start/README.md b/localization/es-es/00-quick-start/README.md index 6c9339b0..282516c7 100644 --- a/localization/es-es/00-quick-start/README.md +++ b/localization/es-es/00-quick-start/README.md @@ -204,7 +204,7 @@ copilot **Salida esperada**: un resumen de las funciones y comandos principales de la app de libros. -Si ves un error, consulta la [sección de solución de problemas](#troubleshooting) más abajo. +Si ves un error, consulta la [sección de solución de problemas](#solución-de-problemas) más abajo. Cuando termines puedes salir de Copilot CLI: diff --git a/localization/es-es/02-context-conversations/README.md b/localization/es-es/02-context-conversations/README.md index 075cd2c9..329559d5 100644 --- a/localization/es-es/02-context-conversations/README.md +++ b/localization/es-es/02-context-conversations/README.md @@ -440,15 +440,15 @@ Sin volver a explicar. Sin volver a leer archivos. Solo continúa trabajando. Cueva de cristal abstracta en tonos azules y morados que representa una exploración más profunda de los conceptos de contexto -Estos temas se construyen sobre los esenciales anteriores. **Elige lo que te interese o salta directamente a [Práctica](#practice).** +Estos temas se construyen sobre los esenciales anteriores. **Elige lo que te interese o salta directamente a [Práctica](#práctica).** | Quiero aprender sobre... | Saltar a | |---|---| -| Patrones comodín y comandos de sesión avanzados | [Patrones @ adicionales y comandos de sesión](#additional-patterns) | -| Construir contexto a través de varios prompts | [Conversaciones conscientes del contexto](#context-aware-conversations) | -| Límites de tokens y `/compact` | [Entender las ventanas de contexto](#understanding-context-windows) | -| Cómo elegir los archivos correctos para referenciar | [Elegir qué referenciar](#choosing-what-to-reference) | -| Analizar capturas de pantalla y mockups | [Trabajar con imágenes](#working-with-images) | +| Patrones comodín y comandos de sesión avanzados | [Patrones @ adicionales y comandos de sesión](#patrones-adicionales) | +| Construir contexto a través de varios prompts | [Conversaciones conscientes del contexto](#conversaciones-conscientes-del-contexto) | +| Límites de tokens y `/compact` | [Entender las ventanas de contexto](#entender-las-ventanas-de-contexto) | +| Cómo elegir los archivos correctos para referenciar | [Elegir qué referenciar](#elegir-qué-referenciar) | +| Analizar capturas de pantalla y mockups | [Trabajar con imágenes](#trabajar-con-imágenes) |
Patrones @ adicionales y comandos de sesión @@ -707,7 +707,7 @@ copilot > @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. ``` -> 📖 **Aprende más**: Consulta [Funciones de contexto adicionales](../appendices/additional-context.md#working-with-images) para conocer formatos compatibles, casos de uso prácticos y consejos para combinar imágenes con código. +> 📖 **Aprende más**: Consulta [Funciones de contexto adicionales](../appendices/additional-context.md#trabajar-con-imágenes) para conocer formatos compatibles, casos de uso prácticos y consejos para combinar imágenes con código.
@@ -773,7 +773,7 @@ Tras completar los demos, prueba estas variaciones: 2. **Reto de sesión**: Inicia una sesión, nómbrala con `/rename my-first-session`, trabaja en algo, sal con `/exit`, luego ejecuta `copilot --continue`. ¿Recuerda lo que estabas haciendo? -3. **Reto de contexto**: Ejecuta `/context` a mitad de la sesión. ¿Cuántos tokens estás usando? Prueba `/compact` y vuelve a verificar. (Consulta [Entender las ventanas de contexto](#understanding-context-windows) en Profundiza más para más información sobre `/compact`.) +3. **Reto de contexto**: Ejecuta `/context` a mitad de la sesión. ¿Cuántos tokens estás usando? Prueba `/compact` y vuelve a verificar. (Consulta [Entender las ventanas de contexto](#entender-las-ventanas-de-contexto) en Profundiza más para más información sobre `/compact`.) **Autocomprobación**: Entiendes el contexto cuando puedes explicar por qué `@folder/` es más potente que abrir cada archivo individualmente. diff --git a/localization/es-es/03-development-workflows/README.md b/localization/es-es/03-development-workflows/README.md index 3e255f4d..f62abc12 100644 --- a/localization/es-es/03-development-workflows/README.md +++ b/localization/es-es/03-development-workflows/README.md @@ -49,8 +49,8 @@ Este capítulo cubre cinco flujos de trabajo que los desarrolladores suelen usar | Localizar y corregir un error | [Flujo 3: Depuración](#workflow-3-debugging) | | Generar tests para mi código | [Flujo 4: Generación de tests](#workflow-4-test-generation) | | Escribir mejores commits y PRs | [Flujo 5: Integración con Git](#workflow-5-git-integration) | -| Investigar antes de codificar | [Consejo rápido: investiga antes de planificar o codificar](#quick-tip-research-before-you-plan-or-code) | -| Ver un flujo completo de corrección de errores de principio a fin | [Poniéndolo todo junto](#putting-it-all-together-bug-fix-workflow) | +| Investigar antes de codificar | [Consejo rápido: investiga antes de planificar o codificar](#consejo-rápido-investiga-antes-de-planificar-o-codificar) | +| Ver un flujo completo de corrección de errores de principio a fin | [Poniéndolo todo junto](#poniéndolo-todo-junto-flujo-de-corrección-de-errores) | **Selecciona un flujo de trabajo a continuación para expandirlo** y ver cómo GitHub Copilot CLI puede mejorar tu proceso de desarrollo en esa área. diff --git a/localization/es-es/04-agents-custom-instructions/README.md b/localization/es-es/04-agents-custom-instructions/README.md index 61a5b1f3..846ea1aa 100644 --- a/localization/es-es/04-agents-custom-instructions/README.md +++ b/localization/es-es/04-agents-custom-instructions/README.md @@ -197,11 +197,11 @@ Cada tema a continuación es independiente. **Elige lo que te interese: no neces | Quiero... | Ir a | |---|---| -| Ver por qué los agentes superan a los prompts genéricos | [Especialista vs genérico](#specialist-vs-generic-see-the-difference) | -| Combinar agentes en una funcionalidad | [Trabajar con varios agentes](#working-with-multiple-agents) | +| Ver por qué los agentes superan a los prompts genéricos | [Especialista vs genérico](#especialista-vs-genérico-nota-la-diferencia) | +| Combinar agentes en una funcionalidad | [Trabajar con varios agentes](#trabajar-con-varios-agentes) | | Organizar, nombrar y compartir agentes | [Organizar y compartir agentes](#organizing--sharing-agents) | -| Configurar contexto de proyecto siempre activo | [Configurar tu proyecto para Copilot](#configuring-your-project-for-copilot) | -| Consultar propiedades YAML y herramientas | [Referencia del archivo de agente](#agent-file-reference) | +| Configurar contexto de proyecto siempre activo | [Configurar tu proyecto para Copilot](#configurar-tu-proyecto-para-copilot) | +| Consultar propiedades YAML y herramientas | [Referencia del archivo de agente](#referencia-del-archivo-de-agente) | Selecciona un escenario abajo para expandirlo. @@ -384,13 +384,13 @@ Piénsalo así: los agentes son especialistas a los que llamas, y los archivos d ### Dónde colocar tus archivos -Ya conoces las dos ubicaciones principales (consulta [Dónde colocar los archivos de agente](#where-to-put-agent-files) más arriba). Usa este árbol de decisión para elegir: +Ya conoces las dos ubicaciones principales (consulta [Dónde colocar los archivos de agente](#dónde-colocar-los-archivos-de-agente) más arriba). Usa este árbol de decisión para elegir: Árbol de decisión sobre dónde colocar los archivos de agente: experimentando → carpeta actual, uso por el equipo → .github/agents/, en todas partes → ~/.copilot/agents/ **Empieza simple:** Crea un único archivo `*.agent.md` en la carpeta de tu proyecto. Muévelo a una ubicación permanente cuando estés satisfecho con él. -Más allá de los archivos de agente, Copilot también lee **archivos de instrucciones a nivel de proyecto** automáticamente, sin necesidad de `/agent`. Consulta [Configurar tu proyecto para Copilot](#configuring-your-project-for-copilot) más abajo para `AGENTS.md`, `.instructions.md` y `/init`. +Más allá de los archivos de agente, Copilot también lee **archivos de instrucciones a nivel de proyecto** automáticamente, sin necesidad de `/agent`. Consulta [Configurar tu proyecto para Copilot](#configurar-tu-proyecto-para-copilot) más abajo para `AGENTS.md`, `.instructions.md` y `/init`.
@@ -468,7 +468,7 @@ copilot --no-custom-instructions ### Un ejemplo más completo -Has visto el [formato de agente mínimo](#-add-your-agents) más arriba. Aquí tienes un agente más completo que usa la propiedad `tools`. Crea `~/.copilot/agents/python-reviewer.agent.md`: +Has visto el [formato de agente mínimo](#-añade-tus-agentes) más arriba. Aquí tienes un agente más completo que usa la propiedad `tools`. Crea `~/.copilot/agents/python-reviewer.agent.md`: ```markdown --- diff --git a/localization/es-es/06-mcp-servers/README.md b/localization/es-es/06-mcp-servers/README.md index 38f0bb13..98be438a 100644 --- a/localization/es-es/06-mcp-servers/README.md +++ b/localization/es-es/06-mcp-servers/README.md @@ -187,9 +187,9 @@ El servidor MCP de GitHub viene integrado y no requiere configuración. A contin | Quiero... | Ir a | |---|---| -| Dejar que Copilot navegue por los archivos de mi proyecto | [Servidor Filesystem](#filesystem-server) | -| Obtener documentación de librerías actualizada | [Servidor Context7](#context7-server-documentation) | -| Explorar extras opcionales (servidores personalizados, web_fetch) | [Más allá de lo básico](#beyond-the-basics) | +| Dejar que Copilot navegue por los archivos de mi proyecto | [Servidor Filesystem](#servidor-filesystem) | +| Obtener documentación de librerías actualizada | [Servidor Context7](#servidor-context7-documentación) | +| Explorar extras opcionales (servidores personalizados, web_fetch) | [Más allá de lo básico](#más-allá-de-lo-básico) |
Servidor Filesystem - Deja que Copilot explore los archivos de tu proyecto @@ -369,7 +369,7 @@ Ahora que tienes servidores MCP configurados, veamos lo que pueden hacer. | Quiero probar... | Ir a | |---|---| -| Repos, issues y PRs de GitHub | [Servidor GitHub](#github-server-built-in) | +| Repos, issues y PRs de GitHub | [Servidor GitHub](#servidor-github-integrado) | | Navegar por archivos del proyecto | [Uso del servidor Filesystem](#filesystem-server-usage) | | Búsqueda de documentación de librerías | [Uso del servidor Context7](#context7-server-usage) | | Servidor personalizado, MCP de Microsoft Learn y uso de web_fetch | [Uso de Más allá de lo básico](#beyond-the-basics-usage) | @@ -533,7 +533,7 @@ copilot > Look up information about "1984" using the book lookup server. Search for books by George Orwell ``` -**MCP de Microsoft Learn**: Si has instalado el [servidor MCP de Microsoft Learn](#microsoft-learn-mcp-server), puedes consultar la documentación oficial de Microsoft directamente: +**MCP de Microsoft Learn**: Si has instalado el [servidor MCP de Microsoft Learn](#servidor-mcp-de-microsoft-learn), puedes consultar la documentación oficial de Microsoft directamente: ```bash copilot @@ -746,7 +746,7 @@ copilot **Resultado esperado**: Copilot lista `book_app.py`, `books.py` y `utils.py` con sus funciones. -> 💡 **¿Aún no has configurado el MCP de filesystem?** Crea el archivo de configuración a partir de la sección [Configuración completa](#complete-configuration-file) de arriba. Después reinicia Copilot. +> 💡 **¿Aún no has configurado el MCP de filesystem?** Crea el archivo de configuración a partir de la sección [Configuración completa](#archivo-de-configuración-completo) de arriba. Después reinicia Copilot. --- @@ -821,7 +821,7 @@ copilot **Paso 2: Crea el archivo de configuración** -Usa el JSON de la sección [Configuración completa](#complete-configuration-file) de arriba y guárdalo como `~/.copilot/mcp-config.json`. +Usa el JSON de la sección [Configuración completa](#archivo-de-configuración-completo) de arriba y guárdalo como `~/.copilot/mcp-config.json`. **Paso 3: Problema de calidad de datos a buscar** diff --git a/localization/es-es/07-putting-it-together/README.md b/localization/es-es/07-putting-it-together/README.md index 58d486e3..4022ff8c 100644 --- a/localization/es-es/07-putting-it-together/README.md +++ b/localization/es-es/07-putting-it-together/README.md @@ -424,7 +424,7 @@ Documenta tu flujo de trabajo a medida que avances.
💡 Pistas (haz clic para expandir) -**Sigue el patrón del ejemplo ["De la idea al PR fusionado"](#idea-to-merged-pr-in-one-session)** del inicio de este capítulo. Los pasos clave son: +**Sigue el patrón del ejemplo ["De la idea al PR fusionado"](#de-la-idea-al-pr-fusionado-en-una-sola-sesión)** del inicio de este capítulo. Los pasos clave son: 1. Reúne contexto con `@samples/book-app-project/books.py` 2. Planifica con `/plan Add a "search by year" command` @@ -452,7 +452,7 @@ Documenta tu flujo de trabajo a medida que avances. |---------|--------------|-----| | Saltar directamente a la implementación | Te pierdes problemas de diseño que cuesta corregir más tarde | Usa primero `/plan` para reflexionar sobre el enfoque | | Usar una sola herramienta cuando varias ayudarían | Resultados más lentos y menos completos | Combina: agente para análisis → skill para ejecución → MCP para integración | -| No revisar antes de hacer commit | Se cuelan problemas de seguridad o bugs | Ejecuta siempre `/review` o usa un [hook de pre-commit](#workflow-2-code-review-automation-optional) | +| No revisar antes de hacer commit | Se cuelan problemas de seguridad o bugs | Ejecuta siempre `/review` o usa un [hook de pre-commit](#flujo-de-trabajo-2-automatización-de-revisión-de-código-opcional) | | Olvidar compartir flujos de trabajo con el equipo | Cada persona reinventa la rueda | Documenta los patrones en agentes, skills e instrucciones compartidas |
diff --git a/localization/ja-jp/00-quick-start/README.md b/localization/ja-jp/00-quick-start/README.md index c7209cfa..93fef147 100644 --- a/localization/ja-jp/00-quick-start/README.md +++ b/localization/ja-jp/00-quick-start/README.md @@ -204,7 +204,7 @@ copilot **期待される出力**: ブックアプリの主な関数とコマンドの概要。 -エラーが表示された場合は、下記の[トラブルシューティング](#troubleshooting)セクションを確認してください。 +エラーが表示された場合は、下記の[トラブルシューティング](#トラブルシューティング-troubleshooting)セクションを確認してください。 完了したら Copilot CLI を終了できます。 diff --git a/localization/ja-jp/02-context-conversations/README.md b/localization/ja-jp/02-context-conversations/README.md index b38d5f11..4aef45ac 100644 --- a/localization/ja-jp/02-context-conversations/README.md +++ b/localization/ja-jp/02-context-conversations/README.md @@ -440,15 +440,15 @@ Issue #1 (duplicate functions) was fixed on Monday. 深いコンテキストの概念の探求を表す青と紫のトーンの抽象的な水晶洞窟 -これらのトピックは上記の必須事項を基に構築されています。**興味のあるものを選んで、または[練習](#practice)に進んでください。** +これらのトピックは上記の必須事項を基に構築されています。**興味のあるものを選んで、または[練習](#練習-practice)に進んでください。** | 学びたいこと... | ジャンプ先 | |---|---| -| ワイルドカードパターンと高度なセッションコマンド | [追加の @ パターンとセッションコマンド](#additional-patterns) | -| 複数のプロンプトにわたるコンテキストの積み上げ | [コンテキスト対応の会話](#context-aware-conversations) | -| トークン制限と `/compact` | [コンテキストウィンドウを理解する](#understanding-context-windows) | -| 参照するファイルの選び方 | [何を参照するかを選ぶ](#choosing-what-to-reference) | -| スクリーンショットやモックアップの分析 | [画像を使う](#working-with-images) | +| ワイルドカードパターンと高度なセッションコマンド | [追加の @ パターンとセッションコマンド](#追加の-パターン) | +| 複数のプロンプトにわたるコンテキストの積み上げ | [コンテキスト対応の会話](#コンテキスト対応の会話) | +| トークン制限と `/compact` | [コンテキストウィンドウを理解する](#コンテキストウィンドウを理解する) | +| 参照するファイルの選び方 | [何を参照するかを選ぶ](#何を参照するかを選ぶ) | +| スクリーンショットやモックアップの分析 | [画像を使う](#画像を使う) |
追加の @ パターンとセッションコマンド @@ -707,7 +707,7 @@ copilot > @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.md#working-with-images)を参照してください。 +> 📖 **詳細**: サポートされているフォーマット、実践的なユースケース、画像とコードを組み合わせるヒントについては、[追加コンテキスト機能](../appendices/additional-context.md#画像の操作)を参照してください。
@@ -773,7 +773,7 @@ copilot --continue 2. **セッションチャレンジ**: セッションを開始して `/rename my-first-session` で名前を付け、何かを作業して `/exit` で終了し、`copilot --continue` を実行する。何をしていたか覚えていますか? -3. **コンテキストチャレンジ**: セッション中に `/context` を実行する。どれだけのトークンを使用していますか?`/compact` を試して再確認しましょう。(`/compact` の詳細については「さらに深く学ぶ」の[コンテキストウィンドウを理解する](#understanding-context-windows)を参照。) +3. **コンテキストチャレンジ**: セッション中に `/context` を実行する。どれだけのトークンを使用していますか?`/compact` を試して再確認しましょう。(`/compact` の詳細については「さらに深く学ぶ」の[コンテキストウィンドウを理解する](#コンテキストウィンドウを理解する)を参照。) **自己確認**: `@folder/` が各ファイルを個別に開くより強力な理由を説明できればコンテキストを理解しています。 diff --git a/localization/ja-jp/03-development-workflows/README.md b/localization/ja-jp/03-development-workflows/README.md index b9eaaac5..d70f5441 100644 --- a/localization/ja-jp/03-development-workflows/README.md +++ b/localization/ja-jp/03-development-workflows/README.md @@ -49,8 +49,8 @@ | バグを追跡して修正する | [ワークフロー 3: デバッグ](#workflow-3-debugging) | | コードのテストを生成する | [ワークフロー 4: テスト生成](#workflow-4-test-generation) | | より良いコミットと PR を書く | [ワークフロー 5: Git 統合](#workflow-5-git-integration) | -| コーディング前に調査する | [クイックヒント: 計画やコーディング前に調査する](#quick-tip-research-before-you-plan-or-code) | -| バグ修正ワークフロー全体を見る | [すべてをまとめる](#putting-it-all-together-bug-fix-workflow) | +| コーディング前に調査する | [クイックヒント: 計画やコーディング前に調査する](#クイックヒント-計画やコーディング前に調査する-quick-tip-research-before-you-plan-or-code) | +| バグ修正ワークフロー全体を見る | [すべてをまとめる](#すべてをまとめる-バグ修正ワークフロー-putting-it-all-together-bug-fix-workflow) | **以下のワークフローを選択して展開し**、その分野で GitHub Copilot CLI が開発プロセスをどのように強化できるかを確認しましょう。 diff --git a/localization/ja-jp/04-agents-custom-instructions/README.md b/localization/ja-jp/04-agents-custom-instructions/README.md index 1fc50684..6267f2c5 100644 --- a/localization/ja-jp/04-agents-custom-instructions/README.md +++ b/localization/ja-jp/04-agents-custom-instructions/README.md @@ -197,11 +197,11 @@ copilot --agent python-reviewer | 目的... | ジャンプ先 | |---|---| -| エージェントが汎用プロンプトより優れている理由を確認する | [専門家対汎用](#specialist-vs-generic-see-the-difference) | -| 機能でエージェントを組み合わせる | [複数エージェントで働く](#working-with-multiple-agents) | +| エージェントが汎用プロンプトより優れている理由を確認する | [専門家対汎用](#専門家対汎用-違いを確認する) | +| 機能でエージェントを組み合わせる | [複数エージェントで働く](#複数エージェントで働く) | | エージェントの整理、命名、共有 | [エージェントの整理と共有](#organizing--sharing-agents) | -| 常時オンのプロジェクトコンテキストを設定する | [Copilot のためのプロジェクト設定](#configuring-your-project-for-copilot) | -| YAML プロパティとツールを調べる | [エージェントファイルリファレンス](#agent-file-reference) | +| 常時オンのプロジェクトコンテキストを設定する | [Copilot のためのプロジェクト設定](#copilot-のためのプロジェクト設定) | +| YAML プロパティとツールを調べる | [エージェントファイルリファレンス](#エージェントファイルリファレンス) | 以下のシナリオを選択して展開します。 @@ -384,13 +384,13 @@ copilot ### ファイルを置く場所 -2 つのメインの場所はすでに知っています(上記の[エージェントファイルを置く場所](#where-to-put-agent-files)を参照)。選択するためのディシジョンツリーです。 +2 つのメインの場所はすでに知っています(上記の[エージェントファイルを置く場所](#エージェントファイルを置く場所)を参照)。選択するためのディシジョンツリーです。 エージェントファイルを置く場所のディシジョンツリー: 実験中 → 現在のフォルダ、チームで使う → .github/agents/、どこでも → ~/.copilot/agents/ **シンプルに始める:** プロジェクトフォルダに単一の `*.agent.md` ファイルを作成し、満足できたら恒久的な場所に移動します。 -エージェントファイルの他にも、Copilot はプロジェクトレベルの**指示ファイル**を自動的に読み込みます(`/agent` は不要)。`AGENTS.md`、`.instructions.md`、`/init` については以下の[Copilot のためのプロジェクト設定](#configuring-your-project-for-copilot)を参照してください。 +エージェントファイルの他にも、Copilot はプロジェクトレベルの**指示ファイル**を自動的に読み込みます(`/agent` は不要)。`AGENTS.md`、`.instructions.md`、`/init` については以下の[Copilot のためのプロジェクト設定](#copilot-のためのプロジェクト設定)を参照してください。
@@ -468,7 +468,7 @@ copilot --no-custom-instructions ### より完全な例 -上記で[最小限のエージェントフォーマット](#-add-your-agents)を見ました。`tools` プロパティを使ったより包括的なエージェントです。`~/.copilot/agents/python-reviewer.agent.md` を作成します: +上記で[最小限のエージェントフォーマット](#-エージェントを追加する)を見ました。`tools` プロパティを使ったより包括的なエージェントです。`~/.copilot/agents/python-reviewer.agent.md` を作成します: ```markdown --- diff --git a/localization/ja-jp/06-mcp-servers/README.md b/localization/ja-jp/06-mcp-servers/README.md index 50f79921..149eefdb 100644 --- a/localization/ja-jp/06-mcp-servers/README.md +++ b/localization/ja-jp/06-mcp-servers/README.md @@ -187,9 +187,9 @@ GitHub MCP サーバーは組み込みで設定は不要です。以下は追加 | 目的... | ジャンプ先 | |---|---| -| Copilot にプロジェクトファイルを参照させる | [Filesystem サーバー](#filesystem-server) | -| 最新のライブラリドキュメントを取得する | [Context7 サーバー](#context7-server-documentation) | -| オプションの追加機能(カスタムサーバー、web_fetch)を探る | [基本を超えて](#beyond-the-basics) | +| Copilot にプロジェクトファイルを参照させる | [Filesystem サーバー](#filesystem-サーバー) | +| 最新のライブラリドキュメントを取得する | [Context7 サーバー](#context7-サーバー-ドキュメント) | +| オプションの追加機能(カスタムサーバー、web_fetch)を探る | [基本を超えて](#基本を超えて) |
Filesystem サーバー - Copilot がプロジェクトファイルを探索できるようにする @@ -369,7 +369,7 @@ MCP サーバーを設定したので、何ができるかを見てみましょ | 試したいこと... | ジャンプ先 | |---|---| -| GitHub のリポジトリ、イシュー、PR | [GitHub サーバー](#github-server-built-in) | +| GitHub のリポジトリ、イシュー、PR | [GitHub サーバー](#github-サーバー-組み込み) | | プロジェクトファイルの参照 | [Filesystem サーバーの使用方法](#filesystem-server-usage) | | ライブラリドキュメントの検索 | [Context7 サーバーの使用方法](#context7-server-usage) | | カスタムサーバー、Microsoft Learn MCP、web_fetch の使用 | [基本を超えての使用方法](#beyond-the-basics-usage) | @@ -533,7 +533,7 @@ 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 ドキュメントを直接検索できます。 +**Microsoft Learn MCP**: [Microsoft Learn MCP サーバー](#microsoft-learn-mcp-サーバー)をインストールした場合、公式 Microsoft ドキュメントを直接検索できます。 ```bash copilot @@ -746,7 +746,7 @@ copilot **期待される結果**: Copilot が `book_app.py`、`books.py`、`utils.py` とその関数をリストアップします。 -> 💡 **filesystem MCP をまだ設定していませんか?** 上記の[完全な設定](#complete-configuration-file)セクションから設定ファイルを作成してください。そして Copilot を再起動します。 +> 💡 **filesystem MCP をまだ設定していませんか?** 上記の[完全な設定](#完全な設定ファイル)セクションから設定ファイルを作成してください。そして Copilot を再起動します。 --- @@ -821,7 +821,7 @@ copilot **ステップ 2: 設定ファイルを作成する** -上記の[完全な設定](#complete-configuration-file)セクションの JSON を使って `~/.copilot/mcp-config.json` として保存します。 +上記の[完全な設定](#完全な設定ファイル)セクションの JSON を使って `~/.copilot/mcp-config.json` として保存します。 **ステップ 3: 探すデータ品質の問題** diff --git a/localization/ja-jp/07-putting-it-together/README.md b/localization/ja-jp/07-putting-it-together/README.md index 49570289..1db50ca7 100644 --- a/localization/ja-jp/07-putting-it-together/README.md +++ b/localization/ja-jp/07-putting-it-together/README.md @@ -424,7 +424,7 @@ Include: Summary, Changes Made, Testing Done, Screenshots Needed"
💡 ヒント(クリックして展開) -**この章の上部にある[「アイデアからマージされた PR へ」](#idea-to-merged-pr-in-one-session)の例のパターンに従ってください。** 主なステップは以下です: +**この章の上部にある[「アイデアからマージされた PR へ」](#1-つのセッションでアイデアからマージされた-pr-へ)の例のパターンに従ってください。** 主なステップは以下です: 1. `@samples/book-app-project/books.py` でコンテキストを収集する 2. `/plan Add a "search by year" command` で計画する @@ -452,7 +452,7 @@ Include: Summary, Changes Made, Testing Done, Screenshots Needed" |---------|--------------|-----| | 実装にすぐ飛びつく | 後で修正コストの高い設計上の問題を見逃す | まず `/plan` を使ってアプローチを考える | | 1 つのツールだけ使う | 遅く、徹底性に欠ける | 組み合わせる: 分析にエージェント → 実行にスキル → 統合に MCP | -| コミット前にレビューしない | セキュリティの問題やバグが見過ごされる | 常に `/review` を実行するか[プリコミットフック](#workflow-2-code-review-automation-optional)を使う | +| コミット前にレビューしない | セキュリティの問題やバグが見過ごされる | 常に `/review` を実行するか[プリコミットフック](#ワークフロー-2-コードレビューの自動化-オプション)を使う | | ワークフローをチームと共有しない | 各人がゼロから発明する | 共有エージェント、スキル、指示にパターンを文書化する |
diff --git a/localization/ja-jp/README.md b/localization/ja-jp/README.md index b2c6a7d6..cffb8e5d 100644 --- a/localization/ja-jp/README.md +++ b/localization/ja-jp/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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) +🎯 [学習内容](#学習内容-what-youll-learn)   ✅ [前提条件](#前提条件-prerequisites)   🤖 [Copilot ファミリー](#github-copilot-ファミリーを理解する-understanding-the-github-copilot-family)   📚 [コース構成](#コース構成-course-structure)   📋 [コマンドリファレンス](#-github-copilot-cli-コマンドリファレンス--github-copilot-cli-command-reference) # GitHub Copilot CLI for Beginners diff --git a/localization/ko-kr/00-quick-start/README.md b/localization/ko-kr/00-quick-start/README.md index c2317450..b5470eaf 100644 --- a/localization/ko-kr/00-quick-start/README.md +++ b/localization/ko-kr/00-quick-start/README.md @@ -204,7 +204,7 @@ copilot **예상 출력**: 도서 앱의 주요 기능과 명령어 요약. -오류가 발생하면 아래 [문제 해결 섹션](#troubleshooting)을 확인하세요. +오류가 발생하면 아래 [문제 해결 섹션](#문제-해결)을 확인하세요. 완료되면 Copilot CLI를 종료할 수 있습니다: diff --git a/localization/ko-kr/02-context-conversations/README.md b/localization/ko-kr/02-context-conversations/README.md index d20b8065..1a200e3c 100644 --- a/localization/ko-kr/02-context-conversations/README.md +++ b/localization/ko-kr/02-context-conversations/README.md @@ -441,15 +441,15 @@ Issue #1 (duplicate functions) was fixed on Monday. 컨텍스트 개념을 더 깊이 탐험하는 모습을 표현한, 푸른빛과 보랏빛이 도는 추상적인 크리스털 동굴 -이 주제들은 위의 핵심 내용을 토대로 합니다. **관심 가는 것을 선택하거나, [실습](#practice)으로 바로 건너뛰어도 됩니다.** +이 주제들은 위의 핵심 내용을 토대로 합니다. **관심 가는 것을 선택하거나, [실습](#실습)으로 바로 건너뛰어도 됩니다.** | 알고 싶은 주제... | 이동 | |---|---| -| 와일드카드 패턴과 고급 세션 명령 | [추가 @ 패턴 및 세션 명령](#additional-patterns) | -| 여러 프롬프트에 걸쳐 컨텍스트 쌓기 | [컨텍스트 인지 대화](#context-aware-conversations) | -| 토큰 제한과 `/compact` | [컨텍스트 윈도우 이해하기](#understanding-context-windows) | -| 참조할 파일을 어떻게 고를지 | [참조할 대상 고르기](#choosing-what-to-reference) | -| 스크린샷과 목업 분석 | [이미지 다루기](#working-with-images) | +| 와일드카드 패턴과 고급 세션 명령 | [추가 @ 패턴 및 세션 명령](#추가-패턴) | +| 여러 프롬프트에 걸쳐 컨텍스트 쌓기 | [컨텍스트 인지 대화](#컨텍스트-인지-대화) | +| 토큰 제한과 `/compact` | [컨텍스트 윈도우 이해하기](#컨텍스트-윈도우-이해하기) | +| 참조할 파일을 어떻게 고를지 | [참조할 대상 고르기](#참조할-대상-고르기) | +| 스크린샷과 목업 분석 | [이미지 다루기](#이미지-다루기) |
추가 @ 패턴 및 세션 명령 @@ -708,7 +708,7 @@ copilot > @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.md#working-with-images)을 참고하세요. +> 📖 **더 알아보기**: 지원되는 형식, 실용적인 활용 사례, 이미지와 코드를 결합하는 팁은 [추가 컨텍스트 기능](../appendices/additional-context.md#이미지로-작업하기)을 참고하세요.
@@ -774,7 +774,7 @@ copilot --continue 2. **세션 챌린지**: 세션을 시작하고 `/rename my-first-session`으로 이름을 부여한 뒤, 무언가 작업하고 `/exit`으로 나가세요. 그런 다음 `copilot --continue`를 실행해 보세요. 무엇을 하고 있었는지 기억하나요? -3. **컨텍스트 챌린지**: 세션 도중에 `/context`를 실행해 보세요. 토큰을 얼마나 쓰고 있나요? `/compact`를 시도한 뒤 다시 확인해 보세요. (`/compact`에 대한 자세한 내용은 더 깊이 들어가기의 [컨텍스트 윈도우 이해하기](#understanding-context-windows)를 참고하세요.) +3. **컨텍스트 챌린지**: 세션 도중에 `/context`를 실행해 보세요. 토큰을 얼마나 쓰고 있나요? `/compact`를 시도한 뒤 다시 확인해 보세요. (`/compact`에 대한 자세한 내용은 더 깊이 들어가기의 [컨텍스트 윈도우 이해하기](#컨텍스트-윈도우-이해하기)를 참고하세요.) **자가 점검**: 각 파일을 일일이 여는 것보다 `@folder/`가 왜 더 강력한지를 설명할 수 있다면, 컨텍스트를 이해한 것입니다. diff --git a/localization/ko-kr/03-development-workflows/README.md b/localization/ko-kr/03-development-workflows/README.md index 514a60f3..cc6d87bc 100644 --- a/localization/ko-kr/03-development-workflows/README.md +++ b/localization/ko-kr/03-development-workflows/README.md @@ -49,8 +49,8 @@ | 버그를 추적하고 수정하기 | [Workflow 3: Debugging](#workflow-3-debugging) | | 코드에 대한 테스트 생성하기 | [Workflow 4: Test Generation](#workflow-4-test-generation) | | 더 나은 커밋과 PR 작성하기 | [Workflow 5: Git Integration](#workflow-5-git-integration) | -| 코딩 전에 리서치하기 | [Quick Tip: Research Before You Plan or Code](#quick-tip-research-before-you-plan-or-code) | -| 처음부터 끝까지 버그 수정 워크플로 살펴보기 | [Putting It All Together](#putting-it-all-together-bug-fix-workflow) | +| 코딩 전에 리서치하기 | [Quick Tip: Research Before You Plan or Code](#빠른-팁-계획하거나-코딩하기-전에-먼저-리서치하기) | +| 처음부터 끝까지 버그 수정 워크플로 살펴보기 | [Putting It All Together](#모두-합치기-버그-수정-워크플로) | **아래에서 워크플로를 선택해 펼쳐 보고**, 해당 영역에서 GitHub Copilot CLI가 개발 과정을 어떻게 향상시키는지 확인해 보세요. diff --git a/localization/ko-kr/04-agents-custom-instructions/README.md b/localization/ko-kr/04-agents-custom-instructions/README.md index 573df35c..627efdaf 100644 --- a/localization/ko-kr/04-agents-custom-instructions/README.md +++ b/localization/ko-kr/04-agents-custom-instructions/README.md @@ -197,11 +197,11 @@ copilot --agent python-reviewer | 하고 싶은 것 | 이동할 곳 | |---|---| -| 에이전트가 일반 프롬프트보다 나은 이유 보기 | [Specialist vs Generic](#specialist-vs-generic-see-the-difference) | -| 한 기능에 여러 에이전트 결합하기 | [Working with Multiple Agents](#working-with-multiple-agents) | +| 에이전트가 일반 프롬프트보다 나은 이유 보기 | [Specialist vs Generic](#전문가-vs-일반-에이전트-차이를-직접-확인하기) | +| 한 기능에 여러 에이전트 결합하기 | [Working with Multiple Agents](#여러-에이전트-함께-사용하기) | | 에이전트 정리·명명·공유하기 | [Organizing & Sharing Agents](#organizing--sharing-agents) | -| 항상 활성화되는 프로젝트 컨텍스트 설정하기 | [Configuring Your Project for Copilot](#configuring-your-project-for-copilot) | -| YAML 속성과 도구 찾아보기 | [Agent File Reference](#agent-file-reference) | +| 항상 활성화되는 프로젝트 컨텍스트 설정하기 | [Configuring Your Project for Copilot](#copilot용-프로젝트-구성) | +| YAML 속성과 도구 찾아보기 | [Agent File Reference](#에이전트-파일-레퍼런스) | 아래 시나리오를 선택해 펼쳐 보세요. @@ -384,13 +384,13 @@ copilot ### 파일을 두는 위치 -이미 두 가지 주요 위치를 알고 있습니다(위 [에이전트 파일을 두는 위치](#where-to-put-agent-files) 참조). 다음 결정 트리를 참고해 선택하세요: +이미 두 가지 주요 위치를 알고 있습니다(위 [에이전트 파일을 두는 위치](#에이전트-파일을-두는-위치) 참조). 다음 결정 트리를 참고해 선택하세요: 에이전트 파일 위치 결정 트리: 실험 중 → 현재 폴더, 팀 사용 → .github/agents/, 어디서나 → ~/.copilot/agents/ **간단하게 시작하세요:** 프로젝트 폴더에 `*.agent.md` 파일 하나를 만드세요. 만족스러우면 영구적인 위치로 옮기면 됩니다. -에이전트 파일 외에도 Copilot은 `/agent` 없이 자동으로 적용되는 **프로젝트 수준 지침 파일**도 읽습니다. `AGENTS.md`, `.instructions.md`, `/init`에 대해서는 아래 [Configuring Your Project for Copilot](#configuring-your-project-for-copilot)을 참고하세요. +에이전트 파일 외에도 Copilot은 `/agent` 없이 자동으로 적용되는 **프로젝트 수준 지침 파일**도 읽습니다. `AGENTS.md`, `.instructions.md`, `/init`에 대해서는 아래 [Configuring Your Project for Copilot](#copilot용-프로젝트-구성)을 참고하세요.
@@ -468,7 +468,7 @@ copilot --no-custom-instructions ### 보다 완전한 예시 -위에서 [최소 에이전트 형식](#-add-your-agents)을 보았습니다. 다음은 `tools` 속성을 사용하는 보다 포괄적인 에이전트입니다. `~/.copilot/agents/python-reviewer.agent.md`를 만들어 보세요: +위에서 [최소 에이전트 형식](#-에이전트-추가하기)을 보았습니다. 다음은 `tools` 속성을 사용하는 보다 포괄적인 에이전트입니다. `~/.copilot/agents/python-reviewer.agent.md`를 만들어 보세요: ```markdown --- diff --git a/localization/ko-kr/06-mcp-servers/README.md b/localization/ko-kr/06-mcp-servers/README.md index 699e3683..2aaf6f7c 100644 --- a/localization/ko-kr/06-mcp-servers/README.md +++ b/localization/ko-kr/06-mcp-servers/README.md @@ -187,9 +187,9 @@ GitHub MCP 서버는 내장되어 있어서 별도 설정이 필요 없습니다 | 하고 싶은 일... | 이동 | |---|---| -| Copilot이 내 프로젝트 파일을 탐색하게 하기 | [Filesystem 서버](#filesystem-server) | -| 최신 라이브러리 문서 가져오기 | [Context7 서버](#context7-server-documentation) | -| 선택적 추가 기능 살펴보기 (커스텀 서버, web_fetch) | [기본을 넘어서](#beyond-the-basics) | +| Copilot이 내 프로젝트 파일을 탐색하게 하기 | [Filesystem 서버](#filesystem-서버) | +| 최신 라이브러리 문서 가져오기 | [Context7 서버](#context7-서버-문서) | +| 선택적 추가 기능 살펴보기 (커스텀 서버, web_fetch) | [기본을 넘어서](#기본을-넘어서) |
Filesystem 서버 - Copilot이 프로젝트 파일을 탐색하게 하기 @@ -369,7 +369,7 @@ Copilot을 자신의 API, 데이터베이스 또는 내부 도구에 연결하 | 시도해 보고 싶은 것... | 이동 | |---|---| -| GitHub 저장소, 이슈, PR | [GitHub 서버](#github-server-built-in) | +| GitHub 저장소, 이슈, PR | [GitHub 서버](#github-서버-내장) | | 프로젝트 파일 탐색 | [Filesystem 서버 사용](#filesystem-server-usage) | | 라이브러리 문서 조회 | [Context7 서버 사용](#context7-server-usage) | | 커스텀 서버, Microsoft Learn MCP 및 web_fetch 사용 | [기본을 넘어서 - 사용](#beyond-the-basics-usage) | @@ -533,7 +533,7 @@ 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 문서를 직접 조회할 수 있습니다: +**Microsoft Learn MCP**: [Microsoft Learn MCP 서버](#microsoft-learn-mcp-서버)를 설치했다면 공식 Microsoft 문서를 직접 조회할 수 있습니다: ```bash copilot @@ -746,7 +746,7 @@ copilot **기대 결과**: Copilot이 `book_app.py`, `books.py`, `utils.py`와 그 함수들을 나열합니다. -> 💡 **filesystem MCP를 아직 구성하지 않으셨나요?** 위 [전체 구성](#complete-configuration-file) 섹션에서 구성 파일을 만드세요. 그런 다음 Copilot을 재시작하세요. +> 💡 **filesystem MCP를 아직 구성하지 않으셨나요?** 위 [전체 구성](#전체-구성-파일) 섹션에서 구성 파일을 만드세요. 그런 다음 Copilot을 재시작하세요. --- @@ -821,7 +821,7 @@ copilot **2단계: 구성 파일 만들기** -위 [전체 구성](#complete-configuration-file) 섹션의 JSON을 사용하여 `~/.copilot/mcp-config.json`으로 저장하세요. +위 [전체 구성](#전체-구성-파일) 섹션의 JSON을 사용하여 `~/.copilot/mcp-config.json`으로 저장하세요. **3단계: 찾아야 할 데이터 품질 문제** diff --git a/localization/ko-kr/07-putting-it-together/README.md b/localization/ko-kr/07-putting-it-together/README.md index 7718a52d..955229b0 100644 --- a/localization/ko-kr/07-putting-it-together/README.md +++ b/localization/ko-kr/07-putting-it-together/README.md @@ -424,7 +424,7 @@ Include: Summary, Changes Made, Testing Done, Screenshots Needed"
💡 힌트 (클릭해서 펼치기) -**이번 장 첫 부분의 ["한 세션으로 아이디어부터 머지된 PR까지"](#idea-to-merged-pr-in-one-session) 예시 패턴을 그대로 따라 보세요.** 핵심 단계는 다음과 같습니다: +**이번 장 첫 부분의 ["한 세션으로 아이디어부터 머지된 PR까지"](#한-세션으로-아이디어부터-머지된-pr까지) 예시 패턴을 그대로 따라 보세요.** 핵심 단계는 다음과 같습니다: 1. `@samples/book-app-project/books.py`로 컨텍스트 수집 2. `/plan Add a "search by year" command`로 계획 수립 @@ -452,7 +452,7 @@ Include: Summary, Changes Made, Testing Done, Screenshots Needed" |---------|--------------|-----| | 곧바로 구현부터 뛰어들기 | 나중에 비싸게 고쳐야 할 설계 이슈를 놓칩니다 | 먼저 `/plan`으로 접근 방식을 정리하세요 | | 여러 도구가 도움이 될 상황에서 한 가지만 사용하기 | 더 느리고 덜 꼼꼼한 결과 | 결합하세요: 분석은 에이전트 → 실행은 스킬 → 통합은 MCP | -| 커밋 전에 리뷰하지 않기 | 보안 이슈나 버그가 그대로 통과합니다 | 항상 `/review`를 실행하거나 [pre-commit 훅](#workflow-2-code-review-automation-optional)을 사용하세요 | +| 커밋 전에 리뷰하지 않기 | 보안 이슈나 버그가 그대로 통과합니다 | 항상 `/review`를 실행하거나 [pre-commit 훅](#워크플로-2-코드-리뷰-자동화-선택)을 사용하세요 | | 팀과 워크플로를 공유하는 것을 잊기 | 팀원마다 같은 일을 다시 만들게 됩니다 | 공용 에이전트, 스킬, 인스트럭션에 패턴을 문서화하세요 |
diff --git a/localization/ko-kr/README.md b/localization/ko-kr/README.md index 502406e1..79213dd4 100644 --- a/localization/ko-kr/README.md +++ b/localization/ko-kr/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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) +🎯 [학습 목표](#학습-목표)   ✅ [사전 요건](#사전-요건)   🤖 [Copilot 제품군](#github-copilot-제품군-이해하기)   📚 [강의 구성](#강의-구성)   📋 [명령어 참조](#-github-copilot-cli-명령어-참조) # GitHub Copilot CLI for Beginners diff --git a/localization/pt-br/00-quick-start/README.md b/localization/pt-br/00-quick-start/README.md index b7fb8858..287d7862 100644 --- a/localization/pt-br/00-quick-start/README.md +++ b/localization/pt-br/00-quick-start/README.md @@ -204,7 +204,7 @@ copilot **Saída esperada**: Um resumo das principais funções e comandos do aplicativo de livros. -Se você vir um erro, verifique a [seção de solução de problemas](#troubleshooting) abaixo. +Se você vir um erro, verifique a [seção de solução de problemas](#solução-de-problemas) abaixo. Quando terminar, você pode sair do Copilot CLI: diff --git a/localization/pt-br/02-context-conversations/README.md b/localization/pt-br/02-context-conversations/README.md index 813f900c..1c07d6ed 100644 --- a/localization/pt-br/02-context-conversations/README.md +++ b/localization/pt-br/02-context-conversations/README.md @@ -440,15 +440,15 @@ Sem precisar explicar novamente. Sem precisar reler arquivos. Apenas continue tr Caverna de cristal abstrata em tons de azul e roxo representando exploração mais profunda dos conceitos de contexto -Esses tópicos se baseiam nos fundamentos acima. **Escolha o que lhe interessa ou pule para [Prática](#practice).** +Esses tópicos se baseiam nos fundamentos acima. **Escolha o que lhe interessa ou pule para [Prática](#prática).** | Quero aprender sobre... | Ir para | |---|---| -| Padrões de curinga e comandos avançados de sessão | [Padrões @ Adicionais & Comandos de Sessão](#additional-patterns) | -| Construir sobre contexto em múltiplos prompts | [Conversas Conscientes do Contexto](#context-aware-conversations) | -| Limites de tokens e `/compact` | [Entendendo as Janelas de Contexto](#understanding-context-windows) | -| Como escolher os arquivos certos para referenciar | [Escolhendo o que Referenciar](#choosing-what-to-reference) | -| Analisar capturas de tela e mockups | [Trabalhando com Imagens](#working-with-images) | +| Padrões de curinga e comandos avançados de sessão | [Padrões @ Adicionais & Comandos de Sessão](#padrões-adicionais) | +| Construir sobre contexto em múltiplos prompts | [Conversas Conscientes do Contexto](#conversas-conscientes-do-contexto) | +| Limites de tokens e `/compact` | [Entendendo as Janelas de Contexto](#entendendo-as-janelas-de-contexto) | +| Como escolher os arquivos certos para referenciar | [Escolhendo o que Referenciar](#escolhendo-o-que-referenciar) | +| Analisar capturas de tela e mockups | [Trabalhando com Imagens](#trabalhando-com-imagens) |
Padrões @ Adicionais & Comandos de Sessão @@ -707,7 +707,7 @@ copilot > @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. ``` -> 📖 **Saiba mais**: Veja [Funcionalidades Adicionais de Contexto](../appendices/additional-context.md#working-with-images) para formatos suportados, casos de uso práticos e dicas para combinar imagens com código. +> 📖 **Saiba mais**: Veja [Funcionalidades Adicionais de Contexto](../appendices/additional-context.md#trabalhando-com-imagens) para formatos suportados, casos de uso práticos e dicas para combinar imagens com código.
@@ -773,7 +773,7 @@ Após concluir as demos, experimente estas variações: 2. **Desafio de Sessão**: Inicie uma sessão, nomeie-a com `/rename my-first-session`, faça alguma coisa, saia com `/exit` e execute `copilot --continue`. Ela lembra o que você estava fazendo? -3. **Desafio de Contexto**: Execute `/context` no meio de uma sessão. Quantos tokens você está usando? Experimente `/compact` e verifique novamente. (Veja [Entendendo as Janelas de Contexto](#understanding-context-windows) em Indo Mais Fundo para mais sobre `/compact`.) +3. **Desafio de Contexto**: Execute `/context` no meio de uma sessão. Quantos tokens você está usando? Experimente `/compact` e verifique novamente. (Veja [Entendendo as Janelas de Contexto](#entendendo-as-janelas-de-contexto) em Indo Mais Fundo para mais sobre `/compact`.) **Autoavaliação**: Você entende o contexto quando consegue explicar por que `@folder/` é mais poderoso do que abrir cada arquivo individualmente. diff --git a/localization/pt-br/03-development-workflows/README.md b/localization/pt-br/03-development-workflows/README.md index a02521d3..00d0697e 100644 --- a/localization/pt-br/03-development-workflows/README.md +++ b/localization/pt-br/03-development-workflows/README.md @@ -49,8 +49,8 @@ Este capítulo cobre cinco fluxos de trabalho que os desenvolvedores normalmente | Rastrear e corrigir um bug | [Fluxo de Trabalho 3: Depuração](#workflow-3-debugging) | | Gerar testes para meu código | [Fluxo de Trabalho 4: Geração de Testes](#workflow-4-test-generation) | | Escrever commits e PRs melhores | [Fluxo de Trabalho 5: Integração com Git](#workflow-5-git-integration) | -| Pesquisar antes de codificar | [Dica Rápida: Pesquise Antes de Planejar ou Codificar](#quick-tip-research-before-you-plan-or-code) | -| Ver um fluxo de trabalho completo de correção de bug | [Juntando Tudo](#putting-it-all-together-bug-fix-workflow) | +| Pesquisar antes de codificar | [Dica Rápida: Pesquise Antes de Planejar ou Codificar](#dica-rápida-pesquise-antes-de-planejar-ou-codificar) | +| Ver um fluxo de trabalho completo de correção de bug | [Juntando Tudo](#juntando-tudo-fluxo-de-trabalho-de-correção-de-bug) | **Selecione um fluxo de trabalho abaixo para expandi-lo** e veja como o GitHub Copilot CLI pode aprimorar o seu processo de desenvolvimento nessa área. diff --git a/localization/pt-br/04-agents-custom-instructions/README.md b/localization/pt-br/04-agents-custom-instructions/README.md index 6b01a3d9..74e1f8de 100644 --- a/localization/pt-br/04-agents-custom-instructions/README.md +++ b/localization/pt-br/04-agents-custom-instructions/README.md @@ -197,11 +197,11 @@ Cada tópico abaixo é independente. **Escolha o que lhe interessa - você não | Quero... | Ir para | |---|---| -| Ver por que agentes superam prompts genéricos | [Especialista vs Genérico](#specialist-vs-generic-see-the-difference) | -| Combinar agentes em uma funcionalidade | [Trabalhando com Múltiplos Agentes](#working-with-multiple-agents) | +| Ver por que agentes superam prompts genéricos | [Especialista vs Genérico](#especialista-vs-genérico-veja-a-diferença) | +| Combinar agentes em uma funcionalidade | [Trabalhando com Múltiplos Agentes](#trabalhando-com-múltiplos-agentes) | | Organizar, nomear e compartilhar agentes | [Organizando & Compartilhando Agentes](#organizing--sharing-agents) | -| Configurar contexto sempre ativo do projeto | [Configurando Seu Projeto para o Copilot](#configuring-your-project-for-copilot) | -| Consultar propriedades YAML e ferramentas | [Referência de Arquivo de Agente](#agent-file-reference) | +| Configurar contexto sempre ativo do projeto | [Configurando Seu Projeto para o Copilot](#configurando-seu-projeto-para-o-copilot) | +| Consultar propriedades YAML e ferramentas | [Referência de Arquivo de Agente](#referência-de-arquivo-de-agente) | Selecione um cenário abaixo para expandi-lo. @@ -384,13 +384,13 @@ Pense desta forma: agentes são especialistas que você chama, e arquivos de ins ### Onde Colocar Seus Arquivos -Você já conhece os dois locais principais (veja [Onde colocar os arquivos de agente](#where-to-put-agent-files) acima). Use esta árvore de decisão para escolher: +Você já conhece os dois locais principais (veja [Onde colocar os arquivos de agente](#onde-colocar-os-arquivos-de-agente) acima). Use esta árvore de decisão para escolher: Árvore de decisão para onde colocar arquivos de agente: experimentando → pasta atual, uso pela equipe → .github/agents/, em todo lugar → ~/.copilot/agents/ **Comece simples:** Crie um único arquivo `*.agent.md` na sua pasta do projeto. Mova-o para um local permanente quando estiver satisfeito com ele. -Além dos arquivos de agente, o Copilot também lê **arquivos de instruções de nível de projeto** automaticamente, sem necessidade de `/agent`. Veja [Configurando Seu Projeto para o Copilot](#configuring-your-project-for-copilot) abaixo para `AGENTS.md`, `.instructions.md` e `/init`. +Além dos arquivos de agente, o Copilot também lê **arquivos de instruções de nível de projeto** automaticamente, sem necessidade de `/agent`. Veja [Configurando Seu Projeto para o Copilot](#configurando-seu-projeto-para-o-copilot) abaixo para `AGENTS.md`, `.instructions.md` e `/init`.
diff --git a/localization/pt-br/06-mcp-servers/README.md b/localization/pt-br/06-mcp-servers/README.md index 4eb81943..8dc8145d 100644 --- a/localization/pt-br/06-mcp-servers/README.md +++ b/localization/pt-br/06-mcp-servers/README.md @@ -187,9 +187,9 @@ O servidor GitHub MCP é integrado e não requer configuração. Abaixo estão s | Quero... | Ir para | |---|---| -| Deixar o Copilot navegar pelos arquivos do meu projeto | [Servidor Filesystem](#filesystem-server) | -| Obter documentação atualizada de biblioteca | [Servidor Context7](#context7-server-documentation) | -| Explorar extras opcionais (servidores personalizados, web_fetch) | [Além do Básico](#beyond-the-basics) | +| Deixar o Copilot navegar pelos arquivos do meu projeto | [Servidor Filesystem](#servidor-filesystem) | +| Obter documentação atualizada de biblioteca | [Servidor Context7](#servidor-context7-documentação) | +| Explorar extras opcionais (servidores personalizados, web_fetch) | [Além do Básico](#além-do-básico) |
Servidor Filesystem - Deixar o Copilot explorar os arquivos do projeto @@ -369,7 +369,7 @@ Agora que você tem servidores MCP configurados, vamos ver o que eles podem faze | Quero experimentar... | Ir para | |---|---| -| Repositórios, issues e PRs do GitHub | [Servidor GitHub](#github-server-built-in) | +| Repositórios, issues e PRs do GitHub | [Servidor GitHub](#servidor-github-integrado) | | Navegação pelos arquivos do projeto | [Uso do Servidor Filesystem](#filesystem-server-usage) | | Consulta de documentação de biblioteca | [Uso do Servidor Context7](#context7-server-usage) | | Servidor personalizado, Microsoft Learn MCP e uso do web_fetch | [Uso do Além do Básico](#beyond-the-basics-usage) | @@ -533,7 +533,7 @@ copilot > Look up information about "1984" using the book lookup server. Search for books by George Orwell ``` -**Microsoft Learn MCP**: Se você instalou o [servidor Microsoft Learn MCP](#microsoft-learn-mcp-server), você pode consultar a documentação oficial da Microsoft diretamente: +**Microsoft Learn MCP**: Se você instalou o [servidor Microsoft Learn MCP](#servidor-microsoft-learn-mcp), você pode consultar a documentação oficial da Microsoft diretamente: ```bash copilot @@ -746,7 +746,7 @@ copilot **Resultado esperado**: O Copilot lista `book_app.py`, `books.py` e `utils.py` com suas funções. -> 💡 **Ainda não tem o filesystem MCP configurado?** Crie o arquivo de configuração da seção [Configuração Completa](#complete-configuration-file) acima. Então reinicie o Copilot. +> 💡 **Ainda não tem o filesystem MCP configurado?** Crie o arquivo de configuração da seção [Configuração Completa](#arquivo-de-configuração-completo) acima. Então reinicie o Copilot. --- @@ -821,7 +821,7 @@ copilot **Etapa 2: Criar o arquivo de configuração** -Use o JSON da seção [Configuração Completa](#complete-configuration-file) acima e salve como `~/.copilot/mcp-config.json`. +Use o JSON da seção [Configuração Completa](#arquivo-de-configuração-completo) acima e salve como `~/.copilot/mcp-config.json`. **Etapa 3: Problema de qualidade de dados para procurar** diff --git a/localization/pt-br/07-putting-it-together/README.md b/localization/pt-br/07-putting-it-together/README.md index 92847fc9..0f8ff0cf 100644 --- a/localization/pt-br/07-putting-it-together/README.md +++ b/localization/pt-br/07-putting-it-together/README.md @@ -424,7 +424,7 @@ Documente seu fluxo de trabalho conforme avança.
💡 Dicas (clique para expandir) -**Siga o padrão do exemplo ["De Ideia a PR Mesclado"](#idea-to-merged-pr-in-one-session)** no início deste capítulo. Os passos principais são: +**Siga o padrão do exemplo ["De Ideia a PR Mesclado"](#de-ideia-a-pr-mesclado-em-uma-sessão)** no início deste capítulo. Os passos principais são: 1. Reunir contexto com `@samples/book-app-project/books.py` 2. Planejar com `/plan Add a "search by year" command` @@ -452,7 +452,7 @@ Documente seu fluxo de trabalho conforme avança. |------|----------------|---------| | Pular direto para a implementação | Perder problemas de design que são custosos para corrigir depois | Use `/plan` primeiro para pensar sobre a abordagem | | Usar uma ferramenta quando múltiplas ajudariam | Resultados mais lentos e menos completos | Combine: Agente para análise → Skill para execução → MCP para integração | -| Não revisar antes de commitar | Problemas de segurança ou bugs passam despercebidos | Sempre execute `/review` ou use um [hook de pré-commit](#workflow-2-code-review-automation-optional) | +| Não revisar antes de commitar | Problemas de segurança ou bugs passam despercebidos | Sempre execute `/review` ou use um [hook de pré-commit](#fluxo-de-trabalho-2-automação-de-revisão-de-código-opcional) | | Esquecer de compartilhar fluxos de trabalho com a equipe | Cada pessoa reinventa a roda | Documente padrões em agentes, skills e instruções compartilhadas |
diff --git a/localization/zh-cn/00-quick-start/README.md b/localization/zh-cn/00-quick-start/README.md index 8d353649..1b99947b 100644 --- a/localization/zh-cn/00-quick-start/README.md +++ b/localization/zh-cn/00-quick-start/README.md @@ -204,7 +204,7 @@ copilot **预期输出**:一段对该图书应用主要函数与命令的总结。 -如果出现错误,请查看下方的 [故障排查部分](#troubleshooting)。 +如果出现错误,请查看下方的 [故障排查部分](#故障排查)。 完成后,你可以退出 Copilot CLI: diff --git a/localization/zh-cn/02-context-conversations/README.md b/localization/zh-cn/02-context-conversations/README.md index bb12eaf1..4178de83 100644 --- a/localization/zh-cn/02-context-conversations/README.md +++ b/localization/zh-cn/02-context-conversations/README.md @@ -440,15 +440,15 @@ Issue #1 (duplicate functions) was fixed on Monday. 蓝紫色调的抽象水晶洞窟,象征对上下文概念的更深入探索 -这些主题建立在上文的基础知识之上。**挑你感兴趣的看,或者直接跳到 [实践](#practice)。** +这些主题建立在上文的基础知识之上。**挑你感兴趣的看,或者直接跳到 [实践](#实践)。** | 我想了解…… | 跳转到 | |---|---| -| 通配符模式与高级会话命令 | [更多 @ 模式与会话命令](#additional-patterns) | -| 在多个提示词之间叠加上下文 | [上下文感知对话](#context-aware-conversations) | -| Token 限制与 `/compact` | [理解上下文窗口](#understanding-context-windows) | -| 如何挑选要引用的文件 | [选择要引用的内容](#choosing-what-to-reference) | -| 分析截图和原型图 | [处理图片](#working-with-images) | +| 通配符模式与高级会话命令 | [更多 @ 模式与会话命令](#更多-模式) | +| 在多个提示词之间叠加上下文 | [上下文感知对话](#上下文感知对话) | +| Token 限制与 `/compact` | [理解上下文窗口](#理解上下文窗口) | +| 如何挑选要引用的文件 | [选择要引用的内容](#选择要引用的内容) | +| 分析截图和原型图 | [处理图片](#处理图片) |
更多 @ 模式与会话命令 @@ -707,7 +707,7 @@ copilot > @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.md#working-with-images),了解支持的格式、实用场景,以及把图片与代码结合使用的小技巧。 +> 📖 **了解更多**:参见 [更多上下文功能](../appendices/additional-context.md#处理图片),了解支持的格式、实用场景,以及把图片与代码结合使用的小技巧。
@@ -773,7 +773,7 @@ copilot --continue 2. **会话挑战**:开启一个会话,用 `/rename my-first-session` 给它命名,做点事情,用 `/exit` 退出,然后运行 `copilot --continue`。它还记得你之前在做什么吗? -3. **上下文挑战**:在会话进行中运行 `/context`。你用了多少 token?再尝试 `/compact`,然后再次检查。(关于 `/compact` 的更多内容,请参见“深入了解”中的 [理解上下文窗口](#understanding-context-windows)。) +3. **上下文挑战**:在会话进行中运行 `/context`。你用了多少 token?再尝试 `/compact`,然后再次检查。(关于 `/compact` 的更多内容,请参见“深入了解”中的 [理解上下文窗口](#理解上下文窗口)。) **自我检查**:当你能解释为什么 `@folder/` 比逐个打开每个文件更强大时,就说明你真正理解了上下文。 diff --git a/localization/zh-cn/03-development-workflows/README.md b/localization/zh-cn/03-development-workflows/README.md index ad509f7d..e6d0e3c9 100644 --- a/localization/zh-cn/03-development-workflows/README.md +++ b/localization/zh-cn/03-development-workflows/README.md @@ -49,8 +49,8 @@ | 追踪并修复 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) | +| 编码前进行调研 | [小贴士:在规划或编码前先调研](#小贴士-在规划或编码前先调研) | +| 看一个端到端的修 Bug 完整流程 | [全部串起来](#全部串起来-修-bug-工作流) | **点击下方任一工作流将其展开**,看看 GitHub Copilot CLI 如何在该领域强化你的开发流程。 diff --git a/localization/zh-cn/04-agents-custom-instructions/README.md b/localization/zh-cn/04-agents-custom-instructions/README.md index a98f6a63..1c4589ab 100644 --- a/localization/zh-cn/04-agents-custom-instructions/README.md +++ b/localization/zh-cn/04-agents-custom-instructions/README.md @@ -197,11 +197,11 @@ copilot --agent python-reviewer | 我想要…… | 跳转到 | |---|---| -| 看看为什么智能体比通用提示更胜一筹 | [专家 vs 通才](#specialist-vs-generic-see-the-difference) | -| 在一个功能上组合多个智能体 | [使用多个智能体协作](#working-with-multiple-agents) | +| 看看为什么智能体比通用提示更胜一筹 | [专家 vs 通才](#专家-vs-通才-直观对比) | +| 在一个功能上组合多个智能体 | [使用多个智能体协作](#使用多个智能体协作) | | 组织、命名并分享智能体 | [组织与分享智能体](#organizing--sharing-agents) | -| 配置始终生效的项目上下文 | [为 Copilot 配置你的项目](#configuring-your-project-for-copilot) | -| 查阅 YAML 属性和工具 | [智能体文件参考](#agent-file-reference) | +| 配置始终生效的项目上下文 | [为 Copilot 配置你的项目](#为-copilot-配置你的项目) | +| 查阅 YAML 属性和工具 | [智能体文件参考](#智能体文件参考) | 点击下方任一场景即可展开。 @@ -384,13 +384,13 @@ copilot ### 文件应放在哪里 -你已经了解了两个主要位置(参见上文 [智能体文件应当放在哪里](#where-to-put-agent-files))。可以使用下面这棵决策树来决定: +你已经了解了两个主要位置(参见上文 [智能体文件应当放在哪里](#智能体文件应当放在哪里))。可以使用下面这棵决策树来决定: 智能体文件位置决策树:试验阶段 → 当前文件夹;团队使用 → .github/agents/;到处使用 → ~/.copilot/agents/ **从简单开始:** 先在你的项目目录里创建一个 `*.agent.md` 文件。等你对它满意了,再把它移到一个长期位置。 -除了智能体文件,Copilot 还会自动读取 **项目级别的指令文件**,无需 `/agent`。详情见下文的 [为 Copilot 配置你的项目](#configuring-your-project-for-copilot),其中介绍了 `AGENTS.md`、`.instructions.md` 以及 `/init`。 +除了智能体文件,Copilot 还会自动读取 **项目级别的指令文件**,无需 `/agent`。详情见下文的 [为 Copilot 配置你的项目](#为-copilot-配置你的项目),其中介绍了 `AGENTS.md`、`.instructions.md` 以及 `/init`。
@@ -468,7 +468,7 @@ copilot --no-custom-instructions ### 一个更完整的示例 -你已经在前面看过 [最简智能体格式](#-add-your-agents)。下面是一个更完整、并且使用了 `tools` 属性的智能体。请创建 `~/.copilot/agents/python-reviewer.agent.md`: +你已经在前面看过 [最简智能体格式](#-添加你的智能体)。下面是一个更完整、并且使用了 `tools` 属性的智能体。请创建 `~/.copilot/agents/python-reviewer.agent.md`: ```markdown --- diff --git a/localization/zh-cn/06-mcp-servers/README.md b/localization/zh-cn/06-mcp-servers/README.md index 6a97feb3..35b9f40d 100644 --- a/localization/zh-cn/06-mcp-servers/README.md +++ b/localization/zh-cn/06-mcp-servers/README.md @@ -187,9 +187,9 @@ GitHub MCP 服务器是内置的,无需任何设置。下面是你可以添加 | 我想要…… | 跳转到 | |---|---| -| 让 Copilot 浏览我的项目文件 | [Filesystem 服务器](#filesystem-server) | -| 获取最新的库文档 | [Context7 服务器](#context7-server-documentation) | -| 探索可选的进阶功能(自定义服务器、web_fetch) | [进阶内容](#beyond-the-basics) | +| 让 Copilot 浏览我的项目文件 | [Filesystem 服务器](#filesystem-服务器) | +| 获取最新的库文档 | [Context7 服务器](#context7-服务器-文档) | +| 探索可选的进阶功能(自定义服务器、web_fetch) | [进阶内容](#进阶内容) |
Filesystem 服务器 - 让 Copilot 探索你的项目文件 @@ -369,7 +369,7 @@ copilot | 我想试试…… | 跳转到 | |---|---| -| GitHub 仓库、issue 与 PR | [GitHub 服务器](#github-server-built-in) | +| GitHub 仓库、issue 与 PR | [GitHub 服务器](#github-服务器-内置) | | 浏览项目文件 | [Filesystem 服务器使用](#filesystem-server-usage) | | 查询库文档 | [Context7 服务器使用](#context7-server-usage) | | 自定义服务器、Microsoft Learn MCP 与 web_fetch 用法 | [进阶内容用法](#beyond-the-basics-usage) | @@ -533,7 +533,7 @@ 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 的官方文档: +**Microsoft Learn MCP**:如果你安装了 [Microsoft Learn MCP 服务器](#microsoft-learn-mcp-服务器),你可以直接查询 Microsoft 的官方文档: ```bash copilot @@ -746,7 +746,7 @@ copilot **预期结果**:Copilot 列出 `book_app.py`、`books.py` 和 `utils.py` 及其包含的函数。 -> 💡 **还没配置 filesystem MCP?** 使用上面[完整配置](#complete-configuration-file)章节中的 JSON 创建配置文件。然后重启 Copilot。 +> 💡 **还没配置 filesystem MCP?** 使用上面[完整配置](#完整的配置文件)章节中的 JSON 创建配置文件。然后重启 Copilot。 --- @@ -821,7 +821,7 @@ copilot **第 2 步:创建配置文件** -使用上面[完整配置](#complete-configuration-file)章节中的 JSON,并将其保存为 `~/.copilot/mcp-config.json`。 +使用上面[完整配置](#完整的配置文件)章节中的 JSON,并将其保存为 `~/.copilot/mcp-config.json`。 **第 3 步:要查找的数据质量问题** diff --git a/localization/zh-cn/07-putting-it-together/README.md b/localization/zh-cn/07-putting-it-together/README.md index d90b8354..e3786996 100644 --- a/localization/zh-cn/07-putting-it-together/README.md +++ b/localization/zh-cn/07-putting-it-together/README.md @@ -424,7 +424,7 @@ Include: Summary, Changes Made, Testing Done, Screenshots Needed"
💡 提示(点击展开) -**沿用本章开头[「一次会话,从想法到合并的 PR」](#idea-to-merged-pr-in-one-session)示例中的模式。** 关键步骤包括: +**沿用本章开头[「一次会话,从想法到合并的 PR」](#一次会话-从想法到合并的-pr)示例中的模式。** 关键步骤包括: 1. 用 `@samples/book-app-project/books.py` 收集上下文 2. 用 `/plan Add a "search by year" command` 进行规划 @@ -452,7 +452,7 @@ Include: Summary, Changes Made, Testing Done, Screenshots Needed" |---------|--------------|-----| | 直接跳到实现阶段 | 错过设计层面的问题,后续修复成本高 | 先用 `/plan` 把思路理清楚 | | 多个工具能配合时只用了一个 | 速度更慢、结果不够全面 | 组合使用:用 Agent 做分析 → 用 Skill 执行 → 用 MCP 集成 | -| 提交前没有审阅 | 安全问题或 Bug 被漏过 | 一定要运行 `/review`,或使用 [pre-commit 钩子](#workflow-2-code-review-automation-optional) | +| 提交前没有审阅 | 安全问题或 Bug 被漏过 | 一定要运行 `/review`,或使用 [pre-commit 钩子](#工作流-2-自动化代码审阅-可选) | | 忘记把工作流分享给团队 | 每个人都在重新发明轮子 | 把模式沉淀到共享的 agents、skills 和 instructions 中 |
diff --git a/localization/zh-cn/README.md b/localization/zh-cn/README.md index 55b80161..ccd11c3a 100644 --- a/localization/zh-cn/README.md +++ b/localization/zh-cn/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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) +🎯 [你将学到什么](#你将学到什么)   ✅ [先决条件](#先决条件)   🤖 [Copilot 家族](#了解-github-copilot-家族)   📚 [课程结构](#课程结构)   📋 [命令参考](#-github-copilot-cli-命令参考) # 面向初学者的 GitHub Copilot CLI From 98f78ec3fd59e3b9b1859ea81e0714bda3bd13b7 Mon Sep 17 00:00:00 2001 From: Justin Yoo Date: Wed, 13 May 2026 20:39:35 +0900 Subject: [PATCH 5/8] docs(l10n): emit GitHub-correct leading-hyphen anchor slugs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Headings that begin with emoji + space produce a slug with a leading hyphen on GitHub (e.g. ## 🎯 Learning Objectives -> #-learning-objectives). The original anchors in the source markdown are inconsistent about this (some include the leading hyphen, some don't), so the localized files now use the canonical, github-slugger-faithful slug for the localized heading text regardless of how the source anchor was written. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- localization/es-es/README.md | 2 +- localization/ja-jp/README.md | 2 +- localization/ko-kr/README.md | 2 +- localization/pt-br/README.md | 2 +- localization/zh-cn/README.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/localization/es-es/README.md b/localization/es-es/README.md index 2503c05a..de8d7d90 100644 --- a/localization/es-es/README.md +++ b/localization/es-es/README.md @@ -5,7 +5,7 @@ [![Documentación oficial de 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)  [![Únete a Discord de AI Foundry](https://img.shields.io/badge/Discord-AI_Community-blue?style=flat-square&logo=discord&color=5865f2&logoColor=fff)](https://aka.ms/foundry/discord) -🎯 [Qué aprenderás](#qué-aprenderás)   ✅ [Requisitos previos](#requisitos-previos)   🤖 [Familia Copilot](#entendiendo-la-familia-de-github-copilot)   📚 [Estructura del curso](#estructura-del-curso)   📋 [Referencia de comandos](#-referencia-de-comandos-de-github-copilot-cli) +🎯 [Qué aprenderás](#-qué-aprenderás)   ✅ [Requisitos previos](#-requisitos-previos)   🤖 [Familia Copilot](#-entendiendo-la-familia-de-github-copilot)   📚 [Estructura del curso](#-estructura-del-curso)   📋 [Referencia de comandos](#-referencia-de-comandos-de-github-copilot-cli) # GitHub Copilot CLI para principiantes diff --git a/localization/ja-jp/README.md b/localization/ja-jp/README.md index cffb8e5d..0ebb6b20 100644 --- a/localization/ja-jp/README.md +++ b/localization/ja-jp/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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 ファミリー](#github-copilot-ファミリーを理解する-understanding-the-github-copilot-family)   📚 [コース構成](#コース構成-course-structure)   📋 [コマンドリファレンス](#-github-copilot-cli-コマンドリファレンス--github-copilot-cli-command-reference) +🎯 [学習内容](#-学習内容-what-youll-learn)   ✅ [前提条件](#-前提条件-prerequisites)   🤖 [Copilot ファミリー](#-github-copilot-ファミリーを理解する-understanding-the-github-copilot-family)   📚 [コース構成](#-コース構成-course-structure)   📋 [コマンドリファレンス](#-github-copilot-cli-コマンドリファレンス--github-copilot-cli-command-reference) # GitHub Copilot CLI for Beginners diff --git a/localization/ko-kr/README.md b/localization/ko-kr/README.md index 79213dd4..e51ff72d 100644 --- a/localization/ko-kr/README.md +++ b/localization/ko-kr/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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) -🎯 [학습 목표](#학습-목표)   ✅ [사전 요건](#사전-요건)   🤖 [Copilot 제품군](#github-copilot-제품군-이해하기)   📚 [강의 구성](#강의-구성)   📋 [명령어 참조](#-github-copilot-cli-명령어-참조) +🎯 [학습 목표](#-학습-목표)   ✅ [사전 요건](#-사전-요건)   🤖 [Copilot 제품군](#-github-copilot-제품군-이해하기)   📚 [강의 구성](#-강의-구성)   📋 [명령어 참조](#-github-copilot-cli-명령어-참조) # GitHub Copilot CLI for Beginners diff --git a/localization/pt-br/README.md b/localization/pt-br/README.md index a58cdf41..d7b54d8b 100644 --- a/localization/pt-br/README.md +++ b/localization/pt-br/README.md @@ -5,7 +5,7 @@ [![Documentação oficial do 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)  [![Entre na comunidade AI Foundry no Discord](https://img.shields.io/badge/Discord-AI_Community-blue?style=flat-square&logo=discord&color=5865f2&logoColor=fff)](https://aka.ms/foundry/discord) -🎯 [O que você vai aprender](#o-que-você-vai-aprender)   ✅ [Pré-requisitos](#pré-requisitos)   🤖 [Família Copilot](#entendendo-a-família-github-copilot)   📚 [Estrutura do curso](#estrutura-do-curso)   📋 [Referência de comandos](#-referência-de-comandos-do-github-copilot-cli) +🎯 [O que você vai aprender](#-o-que-você-vai-aprender)   ✅ [Pré-requisitos](#-pré-requisitos)   🤖 [Família Copilot](#-entendendo-a-família-github-copilot)   📚 [Estrutura do curso](#-estrutura-do-curso)   📋 [Referência de comandos](#-referência-de-comandos-do-github-copilot-cli) # GitHub Copilot CLI para Iniciantes diff --git a/localization/zh-cn/README.md b/localization/zh-cn/README.md index ccd11c3a..f5c2233d 100644 --- a/localization/zh-cn/README.md +++ b/localization/zh-cn/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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) -🎯 [你将学到什么](#你将学到什么)   ✅ [先决条件](#先决条件)   🤖 [Copilot 家族](#了解-github-copilot-家族)   📚 [课程结构](#课程结构)   📋 [命令参考](#-github-copilot-cli-命令参考) +🎯 [你将学到什么](#-你将学到什么)   ✅ [先决条件](#-先决条件)   🤖 [Copilot 家族](#-了解-github-copilot-家族)   📚 [课程结构](#-课程结构)   📋 [命令参考](#-github-copilot-cli-命令参考) # 面向初学者的 GitHub Copilot CLI From 77cf8256b3ba58342c31e57a9417f1b805783ef8 Mon Sep 17 00:00:00 2001 From: Justin Yoo Date: Wed, 13 May 2026 20:43:55 +0900 Subject: [PATCH 6/8] docs(l10n,ja-jp): drop unsupported {#anchor} heading IDs and re-canonicalize GFM does not honor Pandoc-style explicit heading IDs; the ja-jp translator agent had appended them to 9 headings, where they rendered as literal text and polluted the auto-generated slug. Strip the annotations and re-canonicalize incoming anchors that referenced the old polluted slug. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- localization/ja-jp/00-quick-start/README.md | 5 ++--- .../ja-jp/02-context-conversations/README.md | 5 ++--- .../ja-jp/03-development-workflows/README.md | 10 ++++------ localization/ja-jp/README.md | 17 ++++++----------- 4 files changed, 14 insertions(+), 23 deletions(-) diff --git a/localization/ja-jp/00-quick-start/README.md b/localization/ja-jp/00-quick-start/README.md index 93fef147..4e3dcbae 100644 --- a/localization/ja-jp/00-quick-start/README.md +++ b/localization/ja-jp/00-quick-start/README.md @@ -204,7 +204,7 @@ copilot **期待される出力**: ブックアプリの主な関数とコマンドの概要。 -エラーが表示された場合は、下記の[トラブルシューティング](#トラブルシューティング-troubleshooting)セクションを確認してください。 +エラーが表示された場合は、下記の[トラブルシューティング](#トラブルシューティング)セクションを確認してください。 完了したら Copilot CLI を終了できます。 @@ -226,8 +226,7 @@ copilot --- -## トラブルシューティング {#troubleshooting} - +## トラブルシューティング ### 「copilot: command not found」 CLI がインストールされていません。別のインストール方法を試してください。 diff --git a/localization/ja-jp/02-context-conversations/README.md b/localization/ja-jp/02-context-conversations/README.md index 4aef45ac..ee88c940 100644 --- a/localization/ja-jp/02-context-conversations/README.md +++ b/localization/ja-jp/02-context-conversations/README.md @@ -440,7 +440,7 @@ Issue #1 (duplicate functions) was fixed on Monday. 深いコンテキストの概念の探求を表す青と紫のトーンの抽象的な水晶洞窟 -これらのトピックは上記の必須事項を基に構築されています。**興味のあるものを選んで、または[練習](#練習-practice)に進んでください。** +これらのトピックは上記の必須事項を基に構築されています。**興味のあるものを選んで、または[練習](#練習)に進んでください。** | 学びたいこと... | ジャンプ先 | |---|---| @@ -713,8 +713,7 @@ copilot --- -# 練習 {#practice} - +# 練習 コードが表示されたモニター、ランプ、コーヒーカップ、ヘッドホンが置かれた居心地の良いデスク コンテキストとセッション管理のスキルを適用する時間です。 diff --git a/localization/ja-jp/03-development-workflows/README.md b/localization/ja-jp/03-development-workflows/README.md index d70f5441..5d1abb1e 100644 --- a/localization/ja-jp/03-development-workflows/README.md +++ b/localization/ja-jp/03-development-workflows/README.md @@ -49,8 +49,8 @@ | バグを追跡して修正する | [ワークフロー 3: デバッグ](#workflow-3-debugging) | | コードのテストを生成する | [ワークフロー 4: テスト生成](#workflow-4-test-generation) | | より良いコミットと PR を書く | [ワークフロー 5: Git 統合](#workflow-5-git-integration) | -| コーディング前に調査する | [クイックヒント: 計画やコーディング前に調査する](#クイックヒント-計画やコーディング前に調査する-quick-tip-research-before-you-plan-or-code) | -| バグ修正ワークフロー全体を見る | [すべてをまとめる](#すべてをまとめる-バグ修正ワークフロー-putting-it-all-together-bug-fix-workflow) | +| コーディング前に調査する | [クイックヒント: 計画やコーディング前に調査する](#クイックヒント-計画やコーディング前に調査する) | +| バグ修正ワークフロー全体を見る | [すべてをまとめる](#すべてをまとめる-バグ修正ワークフロー) | **以下のワークフローを選択して展開し**、その分野で GitHub Copilot CLI が開発プロセスをどのように強化できるかを確認しましょう。 @@ -695,8 +695,7 @@ copilot --- -## クイックヒント: 計画やコーディング前に調査する {#quick-tip-research-before-you-plan-or-code} - +## クイックヒント: 計画やコーディング前に調査する ライブラリを調査したり、ベストプラクティスを理解したり、不慣れなトピックを探索したりする必要がある場合は、コードを書く前に `/research` を使って深い調査を実行しましょう。 ```bash @@ -711,8 +710,7 @@ Copilot は GitHub リポジトリとウェブソースを検索し、参照付 --- -## すべてをまとめる: バグ修正ワークフロー {#putting-it-all-together-bug-fix-workflow} - +## すべてをまとめる: バグ修正ワークフロー 報告されたバグを修正するための完全なワークフローです。 ```bash diff --git a/localization/ja-jp/README.md b/localization/ja-jp/README.md index 0ebb6b20..ed9462cb 100644 --- a/localization/ja-jp/README.md +++ b/localization/ja-jp/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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 ファミリー](#-github-copilot-ファミリーを理解する-understanding-the-github-copilot-family)   📚 [コース構成](#-コース構成-course-structure)   📋 [コマンドリファレンス](#-github-copilot-cli-コマンドリファレンス--github-copilot-cli-command-reference) +🎯 [学習内容](#-学習内容)   ✅ [前提条件](#-前提条件)   🤖 [Copilot ファミリー](#-github-copilot-ファミリーを理解する)   📚 [コース構成](#-コース構成)   📋 [コマンドリファレンス](#-github-copilot-cli-コマンドリファレンス) # GitHub Copilot CLI for Beginners @@ -29,24 +29,21 @@ GitHub Copilot CLI は、AI 支援機能をターミナルに直接提供しま -## 🎯 学習内容 {#what-youll-learn} - +## 🎯 学習内容 このハンズオンコースは、GitHub Copilot CLI をゼロから実践的に使いこなせるようになることを目的としています。すべての章を通して 1 つの Python 製ブックコレクションアプリを使用し、AI 支援ワークフローで段階的に改善します。最終的には、ターミナルからコードのレビュー、テスト生成、バグのデバッグ、ワークフローの自動化を自信を持って行えるようになります。 **AI 経験は不要です。** ターミナルが使えれば、このコースを学ぶことができます。 **最適な対象者:** 開発者、学生、ソフトウェア開発の経験がある方。 -## ✅ 前提条件 {#prerequisites} - +## ✅ 前提条件 開始前に、以下を準備してください。 - **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 ファミリーを理解する {#understanding-the-github-copilot-family} - +## 🤖 GitHub Copilot ファミリーを理解する GitHub Copilot は AI を活用したツールのファミリーへと進化しています。各ツールの位置づけは次のとおりです。 | 製品 | 実行環境 | 説明 | @@ -58,8 +55,7 @@ GitHub Copilot は AI を活用したツールのファミリーへと進化し このコースは **GitHub Copilot CLI** に焦点を当て、AI 支援機能をターミナルに直接提供します。 -## 📚 コース構成 {#course-structure} - +## 📚 コース構成 ![GitHub Copilot CLI 学習パス](../../images/learning-path.png) | 章 | タイトル | 作るもの | @@ -85,8 +81,7 @@ GitHub Copilot は AI を活用したツールのファミリーへと進化し **コード例は実行可能です。** このコースのすべての copilot テキストブロックは、コピーしてターミナルで実行できます。 -## 📋 GitHub Copilot CLI コマンドリファレンス {#-github-copilot-cli-command-reference} - +## 📋 GitHub Copilot CLI コマンドリファレンス [**GitHub Copilot CLI コマンドリファレンス**](https://docs.github.com/en/copilot/reference/cli-command-reference) では、Copilot CLI を効果的に使うためのコマンドやキーボードショートカットを確認できます。 ## 🙋 ヘルプを得るには From 10b741b56411f1db7e6c56ec4e046ce6ea184ec7 Mon Sep 17 00:00:00 2001 From: Justin Yoo Date: Wed, 13 May 2026 20:53:25 +0900 Subject: [PATCH 7/8] docs(l10n): localize 'Use Your Preferred Language' section in all 5 locale READMEs Mirror the new section added to the root README. Each locale's link list highlights the current language with ./README.md and points to the others via ..//README.md (English uses ../../README.md). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 8 +++++++- localization/es-es/README.md | 6 ++++++ localization/ja-jp/README.md | 6 ++++++ localization/ko-kr/README.md | 6 ++++++ localization/pt-br/README.md | 6 ++++++ localization/zh-cn/README.md | 6 ++++++ 6 files changed, 37 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 4f2cd85f..9e9ebebc 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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 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) +🎯 [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) # GitHub Copilot CLI for Beginners @@ -89,6 +89,12 @@ Each chapter follows the same pattern: The **[GitHub Copilot CLI command reference](https://docs.github.com/en/copilot/reference/cli-command-reference)** helps you find commands and keyboard shortcuts to help you use Copilot CLI effectively. +## 🌐 Use Your Preferred Language + +This material is available in the following languages. + +[English](./README.md) | [Español](./localization/es-es/README.md) | [日本語](./localization/ja-jp/README.md) | [한국어](./localization/ko-kr/README.md) | [Português](./localization/pt-br/README.md) | [中文(简体)](./localization/zh-cn/README.md) + ## 🙋 Getting Help - 🐛 **Found a bug?** [Open an Issue](https://github.com/github/copilot-cli-for-beginners/issues) diff --git a/localization/es-es/README.md b/localization/es-es/README.md index de8d7d90..7aac87b1 100644 --- a/localization/es-es/README.md +++ b/localization/es-es/README.md @@ -89,6 +89,12 @@ Cada capítulo sigue el mismo patrón: La [**referencia de comandos de GitHub Copilot CLI**](https://docs.github.com/en/copilot/reference/cli-command-reference) te ayuda a encontrar comandos y atajos de teclado para usar Copilot CLI de forma eficaz. +## 🌐 Usa tu idioma preferido + +Este material está disponible en los siguientes idiomas. + +[English](../../README.md) | [Español](./README.md) | [日本語](../ja-jp/README.md) | [한국어](../ko-kr/README.md) | [Português](../pt-br/README.md) | [中文(简体)](../zh-cn/README.md) + ## 🙋 Obtener ayuda - 🐛 **¿Encontraste un error?** [Abre un Issue](https://github.com/github/copilot-cli-for-beginners/issues) diff --git a/localization/ja-jp/README.md b/localization/ja-jp/README.md index ed9462cb..5f7582a2 100644 --- a/localization/ja-jp/README.md +++ b/localization/ja-jp/README.md @@ -84,6 +84,12 @@ GitHub Copilot は AI を活用したツールのファミリーへと進化し ## 📋 GitHub Copilot CLI コマンドリファレンス [**GitHub Copilot CLI コマンドリファレンス**](https://docs.github.com/en/copilot/reference/cli-command-reference) では、Copilot CLI を効果的に使うためのコマンドやキーボードショートカットを確認できます。 +## 🌐 お好みの言語で利用する + +この教材は以下の言語で提供されています。 + +[English](../../README.md) | [Español](../es-es/README.md) | [日本語](./README.md) | [한국어](../ko-kr/README.md) | [Português](../pt-br/README.md) | [中文(简体)](../zh-cn/README.md) + ## 🙋 ヘルプを得るには - 🐛 **バグを見つけた場合?** [Issue を開く](https://github.com/github/copilot-cli-for-beginners/issues) diff --git a/localization/ko-kr/README.md b/localization/ko-kr/README.md index e51ff72d..761c686e 100644 --- a/localization/ko-kr/README.md +++ b/localization/ko-kr/README.md @@ -89,6 +89,12 @@ GitHub Copilot은 AI 기반 도구의 제품군으로 발전했습니다. 각 [**GitHub Copilot CLI 명령어 참조**](https://docs.github.com/en/copilot/reference/cli-command-reference)에서 Copilot CLI를 효과적으로 사용하는 데 도움이 되는 명령어와 키보드 단축키를 찾아볼 수 있습니다. +## 🌐 선호하는 언어로 보기 + +이 자료는 다음 언어로 제공됩니다. + +[English](../../README.md) | [Español](../es-es/README.md) | [日本語](../ja-jp/README.md) | [한국어](./README.md) | [Português](../pt-br/README.md) | [中文(简体)](../zh-cn/README.md) + ## 🙋 도움 받기 - 🐛 **버그를 발견하셨나요?** [이슈 열기](https://github.com/github/copilot-cli-for-beginners/issues) diff --git a/localization/pt-br/README.md b/localization/pt-br/README.md index d7b54d8b..bc7e5dae 100644 --- a/localization/pt-br/README.md +++ b/localization/pt-br/README.md @@ -89,6 +89,12 @@ Cada capítulo segue o mesmo padrão: A [**referência de comandos do GitHub Copilot CLI**](https://docs.github.com/en/copilot/reference/cli-command-reference) ajuda você a encontrar comandos e atalhos de teclado para usar o Copilot CLI com eficiência. +## 🌐 Use seu idioma preferido + +Este material está disponível nos seguintes idiomas. + +[English](../../README.md) | [Español](../es-es/README.md) | [日本語](../ja-jp/README.md) | [한국어](../ko-kr/README.md) | [Português](./README.md) | [中文(简体)](../zh-cn/README.md) + ## 🙋 Obtendo ajuda - 🐛 **Encontrou um bug?** [Abra uma issue](https://github.com/github/copilot-cli-for-beginners/issues) diff --git a/localization/zh-cn/README.md b/localization/zh-cn/README.md index f5c2233d..0b18fd0c 100644 --- a/localization/zh-cn/README.md +++ b/localization/zh-cn/README.md @@ -89,6 +89,12 @@ GitHub Copilot 已经发展成为一系列 AI 驱动的工具。下面是各个 [**GitHub Copilot CLI 命令参考文档**](https://docs.github.com/en/copilot/reference/cli-command-reference) 可以帮你查找命令和键盘快捷键,从而更高效地使用 Copilot CLI。 +## 🌐 使用你的首选语言 + +本教程提供以下语言版本。 + +[English](../../README.md) | [Español](../es-es/README.md) | [日本語](../ja-jp/README.md) | [한국어](../ko-kr/README.md) | [Português](../pt-br/README.md) | [中文(简体)](./README.md) + ## 🙋 获取帮助 - 🐛 **发现 Bug?** [提交 Issue](https://github.com/github/copilot-cli-for-beginners/issues) From 669d7bc64db1b72cb1d04a9d9bf3684dbe523a82 Mon Sep 17 00:00:00 2001 From: Justin Yoo Date: Wed, 13 May 2026 21:15:50 +0900 Subject: [PATCH 8/8] docs(l10n): add 'Your Language' TOC link to all 5 locale READMEs Mirror the new TOC entry added to the root README. Each locale uses a short translation of 'Your Language' and points to the locale's own 'Use Your Preferred Language' heading slug. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 2 +- localization/es-es/README.md | 2 +- localization/ja-jp/README.md | 2 +- localization/ko-kr/README.md | 2 +- localization/pt-br/README.md | 2 +- localization/zh-cn/README.md | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9e9ebebc..5841e1fb 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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 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) +🎯 [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)   🌐 [Your Language](#-use-your-preferred-language) # GitHub Copilot CLI for Beginners diff --git a/localization/es-es/README.md b/localization/es-es/README.md index 7aac87b1..4de84798 100644 --- a/localization/es-es/README.md +++ b/localization/es-es/README.md @@ -5,7 +5,7 @@ [![Documentación oficial de 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)  [![Únete a Discord de AI Foundry](https://img.shields.io/badge/Discord-AI_Community-blue?style=flat-square&logo=discord&color=5865f2&logoColor=fff)](https://aka.ms/foundry/discord) -🎯 [Qué aprenderás](#-qué-aprenderás)   ✅ [Requisitos previos](#-requisitos-previos)   🤖 [Familia Copilot](#-entendiendo-la-familia-de-github-copilot)   📚 [Estructura del curso](#-estructura-del-curso)   📋 [Referencia de comandos](#-referencia-de-comandos-de-github-copilot-cli) +🎯 [Qué aprenderás](#-qué-aprenderás)   ✅ [Requisitos previos](#-requisitos-previos)   🤖 [Familia Copilot](#-entendiendo-la-familia-de-github-copilot)   📚 [Estructura del curso](#-estructura-del-curso)   📋 [Referencia de comandos](#-referencia-de-comandos-de-github-copilot-cli)   🌐 [Tu idioma](#-usa-tu-idioma-preferido) # GitHub Copilot CLI para principiantes diff --git a/localization/ja-jp/README.md b/localization/ja-jp/README.md index 5f7582a2..6697fec3 100644 --- a/localization/ja-jp/README.md +++ b/localization/ja-jp/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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) -🎯 [学習内容](#-学習内容)   ✅ [前提条件](#-前提条件)   🤖 [Copilot ファミリー](#-github-copilot-ファミリーを理解する)   📚 [コース構成](#-コース構成)   📋 [コマンドリファレンス](#-github-copilot-cli-コマンドリファレンス) +🎯 [学習内容](#-学習内容)   ✅ [前提条件](#-前提条件)   🤖 [Copilot ファミリー](#-github-copilot-ファミリーを理解する)   📚 [コース構成](#-コース構成)   📋 [コマンドリファレンス](#-github-copilot-cli-コマンドリファレンス)   🌐 [あなたの言語](#-お好みの言語で利用する) # GitHub Copilot CLI for Beginners diff --git a/localization/ko-kr/README.md b/localization/ko-kr/README.md index 761c686e..f666acc7 100644 --- a/localization/ko-kr/README.md +++ b/localization/ko-kr/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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) -🎯 [학습 목표](#-학습-목표)   ✅ [사전 요건](#-사전-요건)   🤖 [Copilot 제품군](#-github-copilot-제품군-이해하기)   📚 [강의 구성](#-강의-구성)   📋 [명령어 참조](#-github-copilot-cli-명령어-참조) +🎯 [학습 목표](#-학습-목표)   ✅ [사전 요건](#-사전-요건)   🤖 [Copilot 제품군](#-github-copilot-제품군-이해하기)   📚 [강의 구성](#-강의-구성)   📋 [명령어 참조](#-github-copilot-cli-명령어-참조)   🌐 [내 언어](#-선호하는-언어로-보기) # GitHub Copilot CLI for Beginners diff --git a/localization/pt-br/README.md b/localization/pt-br/README.md index bc7e5dae..1c58da0b 100644 --- a/localization/pt-br/README.md +++ b/localization/pt-br/README.md @@ -5,7 +5,7 @@ [![Documentação oficial do 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)  [![Entre na comunidade AI Foundry no Discord](https://img.shields.io/badge/Discord-AI_Community-blue?style=flat-square&logo=discord&color=5865f2&logoColor=fff)](https://aka.ms/foundry/discord) -🎯 [O que você vai aprender](#-o-que-você-vai-aprender)   ✅ [Pré-requisitos](#-pré-requisitos)   🤖 [Família Copilot](#-entendendo-a-família-github-copilot)   📚 [Estrutura do curso](#-estrutura-do-curso)   📋 [Referência de comandos](#-referência-de-comandos-do-github-copilot-cli) +🎯 [O que você vai aprender](#-o-que-você-vai-aprender)   ✅ [Pré-requisitos](#-pré-requisitos)   🤖 [Família Copilot](#-entendendo-a-família-github-copilot)   📚 [Estrutura do curso](#-estrutura-do-curso)   📋 [Referência de comandos](#-referência-de-comandos-do-github-copilot-cli)   🌐 [Seu idioma](#-use-seu-idioma-preferido) # GitHub Copilot CLI para Iniciantes diff --git a/localization/zh-cn/README.md b/localization/zh-cn/README.md index 0b18fd0c..ead2f87d 100644 --- a/localization/zh-cn/README.md +++ b/localization/zh-cn/README.md @@ -5,7 +5,7 @@ [![Official Copilot CLI documentation](https://img.shields.io/badge/GitHub-CLI_Documentation-00a3ee?style=flat-square&logo=github)](https://docs.github.com/en/copilot/how-tos/copilot-cli)  [![Join 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) -🎯 [你将学到什么](#-你将学到什么)   ✅ [先决条件](#-先决条件)   🤖 [Copilot 家族](#-了解-github-copilot-家族)   📚 [课程结构](#-课程结构)   📋 [命令参考](#-github-copilot-cli-命令参考) +🎯 [你将学到什么](#-你将学到什么)   ✅ [先决条件](#-先决条件)   🤖 [Copilot 家族](#-了解-github-copilot-家族)   📚 [课程结构](#-课程结构)   📋 [命令参考](#-github-copilot-cli-命令参考)   🌐 [你的语言](#-使用你的首选语言) # 面向初学者的 GitHub Copilot CLI