From 0e5838f566119b1a2ebd27b4573c1ae0274dc8fe Mon Sep 17 00:00:00 2001 From: Jen Carlucci Date: Mon, 21 Sep 2026 18:34:05 +0000 Subject: [PATCH 1/4] Recommend x-ratelimit-* headers as authoritative on the rate-limit endpoint page (#63132) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: ca058b37-ef99-4f0a-a409-21375c654f92 --- content/rest/rate-limit/rate-limit.md | 3 +++ .../rest/using-the-rest-api/rate-limits-for-the-rest-api.md | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/content/rest/rate-limit/rate-limit.md b/content/rest/rate-limit/rate-limit.md index aa67c7422341..15e5e9aff14c 100644 --- a/content/rest/rate-limit/rate-limit.md +++ b/content/rest/rate-limit/rate-limit.md @@ -18,6 +18,9 @@ category: You can check your current rate limit status at any time. For more information about rate limit rules, see [AUTOTITLE](/rest/using-the-rest-api/rate-limits-for-the-rest-api). +> [!NOTE] +> For real-time rate limit tracking, use the `x-ratelimit-*` response headers returned on each REST API request. These headers reflect the counters that govern enforcement for the request you just made and are the authoritative source for the remaining allowance in the current window. Use `GET /rate_limit` for a periodic overview of all resource families for the authenticated user, and treat the response headers as authoritative if the two disagree. For more information, see [AUTOTITLE](/rest/using-the-rest-api/rate-limits-for-the-rest-api#checking-the-status-of-your-rate-limit). + The REST API for searching items has a custom rate limit that is separate from the rate limit governing the other REST API endpoints. For more information, see [AUTOTITLE](/rest/search/search). The GraphQL API also has a custom rate limit that is separate from and calculated differently than rate limits in the REST API. For more information, see [AUTOTITLE](/graphql/overview/rate-limits-and-query-limits-for-the-graphql-api#primary-rate-limit). For these reasons, the API response categorizes your rate limit. Under `resources`, you'll see objects relating to different categories: * The `core` object provides your rate limit status for all non-search-related resources in the REST API. diff --git a/content/rest/using-the-rest-api/rate-limits-for-the-rest-api.md b/content/rest/using-the-rest-api/rate-limits-for-the-rest-api.md index ea3aea138a5a..c9d9f8a93a1a 100644 --- a/content/rest/using-the-rest-api/rate-limits-for-the-rest-api.md +++ b/content/rest/using-the-rest-api/rate-limits-for-the-rest-api.md @@ -96,7 +96,9 @@ Header name | Description `x-ratelimit-reset` | The time at which the current rate limit window resets, in UTC epoch seconds `x-ratelimit-resource` | The rate limit resource that the request counted against. For more information about the different resources, see [AUTOTITLE](/rest/rate-limit/rate-limit#get-rate-limit-status-for-the-authenticated-user). -You can also call the `GET /rate_limit` endpoint to check your rate limit. Calling this endpoint does not count against your primary rate limit, but it can count against your secondary rate limit. See [AUTOTITLE](/rest/rate-limit/rate-limit). When possible, you should use the rate limit response headers instead of calling the API to check your rate limit. +You can also call the `GET /rate_limit` endpoint to check your rate limit. Calling this endpoint does not count against your primary rate limit, but it can count against your secondary rate limit. See [AUTOTITLE](/rest/rate-limit/rate-limit). + +The `x-ratelimit-*` response headers are the authoritative source for your current rate limit status. Use them to pace and back off your requests. Use `GET /rate_limit` for a periodic overview of all resource families for the authenticated user, and treat the response headers as authoritative if the two disagree. There is not a way to check the status of your secondary rate limit. From ab55fe014e8c6c297df404565aa70aa0a7c969e3 Mon Sep 17 00:00:00 2001 From: docs-bot <77750099+docs-bot@users.noreply.github.com> Date: Mon, 21 Sep 2026 18:50:42 +0000 Subject: [PATCH 2/4] Add 2 translation correction patterns for zh and ko Liquid corruption (#63377) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../lib/correct-translation-content.ts | 25 ++++++++++++++ .../tests/correct-translation-content.ts | 34 +++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/src/languages/lib/correct-translation-content.ts b/src/languages/lib/correct-translation-content.ts index f76a8904d9fe..4458abb464f1 100644 --- a/src/languages/lib/correct-translation-content.ts +++ b/src/languages/lib/correct-translation-content.ts @@ -1348,6 +1348,19 @@ export function correctTranslatedContentStrings( '{% ifversion ghes %}在“检查、工作流运行、状态、工件、日志和缓存设置”部分的 **检查、工作流运行、状态、工件和日志保留** 下,输入一个新值。', '{% ifversion ghes %}在“检查、工作流运行、状态、工件、日志和缓存设置”部分的{% else %}在{% endif %} **检查、工作流运行、状态、工件和日志保留** 下,输入一个新值。', ) + + // filtering-and-searching-issues-and-pull-requests.md: the translator + // dropped the `{% endif %}` closing the `{% ifversion ghes < 3.18 %}` + // that wraps the "qualifiers within parentheses" sentence, leaving the + // outer `{% webui %}...{% endwebui %}` block unterminated + // (`tag "endwebui" not found`). English: `...up to five levels + // deep.{% ifversion ghes < 3.18 %} It's not currently possible to + // include the \`repo\`, \`org\`, or \`user\` qualifiers within + // parentheses.{% endif %}`. + content = content.replaceAll( + '你可以使用圆括号嵌套筛选器,最多可达五层深度。{% ifversion ghes < 3.18 %} 目前无法在括号中包含`repo`、`org`或`user`限定符。\n\n{% endwebui %}', + '你可以使用圆括号嵌套筛选器,最多可达五层深度。{% ifversion ghes < 3.18 %} 目前无法在括号中包含`repo`、`org`或`user`限定符。{% endif %}\n\n{% endwebui %}', + ) } if (context.code === 'ru') { @@ -2339,6 +2352,18 @@ export function correctTranslatedContentStrings( '퍼블릭 리포지토리(퍼블릭 패키지)에 패키지를 게시하여 {% else %}엔터프라이즈의 모든 사용자{% endif %}{% ifversion fpt or ghec %} 모두{% data variables.product.prodname_dotcom %}과(와) 공유하거나 프라이빗 리포지토리의 패키지(프라이빗 패키지)를 게시하여 협력자 또는 조직과 공유할 수 있습니다.', '퍼블릭 리포지토리(퍼블릭 패키지)에 패키지를 게시하여 {% ifversion fpt or ghec %}모두 {% data variables.product.prodname_dotcom %}과(와){% else %}엔터프라이즈의 모든 사용자와{% endif %} 공유하거나 프라이빗 리포지토리의 패키지(프라이빗 패키지)를 게시하여 협력자 또는 조직과 공유할 수 있습니다.', ) + + // pull-request-alert-metrics.md: translator moved `{% endif %}` right + // after the `{% data variables.copilot.copilot_autofix_short %}` mention, + // ahead of the `{% ifversion code-scanning-autofix %}` opener that should + // wrap it (`tag "endif" not found`). English: `...how many alerts were + // fixed{% ifversion code-scanning-autofix %} with and without + // {% data variables.copilot.copilot_autofix_short %} suggestions{% endif %}, + // how many were unresolved...` + content = content.replaceAll( + '{% data variables.copilot.copilot_autofix_short %} 제안{% endif %} 사용 여부에 따라 수정된 경고 수 {% ifversion code-scanning-autofix %}, 해결되지 않은 상태로 병합된 수', + '{% ifversion code-scanning-autofix %} {% data variables.copilot.copilot_autofix_short %} 제안 사용 여부에 따라{% endif %} 수정된 경고 수, 해결되지 않은 상태로 병합된 수', + ) } if (context.code === 'de') { diff --git a/src/languages/tests/correct-translation-content.ts b/src/languages/tests/correct-translation-content.ts index 843422219361..58ea5c187610 100644 --- a/src/languages/tests/correct-translation-content.ts +++ b/src/languages/tests/correct-translation-content.ts @@ -3431,4 +3431,38 @@ Para más información, consulta "[AUTOTITLE](/path)". expect(fix(fixed, 'fr')).toBe(fixed) }) }) + + // ─── filtering-and-searching-issues-and-pull-requests.md per-file fix ── + // The translator dropped the `{% endif %}` closing the + // `{% ifversion ghes < 3.18 %}` that wraps the "qualifiers within + // parentheses" sentence, leaving the outer `{% webui %}...{% endwebui %}` + // block unterminated (`tag "endwebui" not found`). + describe('zh: filtering-and-searching-issues-and-pull-requests.md per-file fix', () => { + test('restores the endif dropped before endwebui', () => { + const broken = + '你可以使用圆括号嵌套筛选器,最多可达五层深度。{% ifversion ghes < 3.18 %} 目前无法在括号中包含`repo`、`org`或`user`限定符。\n\n{% endwebui %}' + const fixed = + '你可以使用圆括号嵌套筛选器,最多可达五层深度。{% ifversion ghes < 3.18 %} 目前无法在括号中包含`repo`、`org`或`user`限定符。{% endif %}\n\n{% endwebui %}' + expect(fix(broken, 'zh')).toBe(fixed) + // idempotent: the fix only matches the broken form + expect(fix(fixed, 'zh')).toBe(fixed) + }) + }) + + // ─── pull-request-alert-metrics.md per-file fix ───────────────────── + // The translator moved `{% endif %}` right after the + // `{% data variables.copilot.copilot_autofix_short %}` mention, ahead of + // the `{% ifversion code-scanning-autofix %}` opener that should wrap it + // (`tag "endif" not found`). + describe('ko: pull-request-alert-metrics.md per-file fix', () => { + test('moves the ifversion opener back before its content', () => { + const broken = + '{% data variables.copilot.copilot_autofix_short %} 제안{% endif %} 사용 여부에 따라 수정된 경고 수 {% ifversion code-scanning-autofix %}, 해결되지 않은 상태로 병합된 수' + const fixed = + '{% ifversion code-scanning-autofix %} {% data variables.copilot.copilot_autofix_short %} 제안 사용 여부에 따라{% endif %} 수정된 경고 수, 해결되지 않은 상태로 병합된 수' + expect(fix(broken, 'ko')).toBe(fixed) + // idempotent: the fix only matches the broken form + expect(fix(fixed, 'ko')).toBe(fixed) + }) + }) }) From 871db5e8a4122d0c6d218f08a64e7e95b950c448 Mon Sep 17 00:00:00 2001 From: docs-bot <77750099+docs-bot@users.noreply.github.com> Date: Mon, 21 Sep 2026 19:31:16 +0000 Subject: [PATCH 3/4] Update OpenAPI Description (#63376) Co-authored-by: Sarita Iyer <66540150+saritai@users.noreply.github.com> --- src/github-apps/lib/config.json | 2 +- .../data/fpt-2022-11-28/interactions.json | 32 +++++++++++++++++-- .../data/fpt-2026-03-10/interactions.json | 32 +++++++++++++++++-- .../data/ghec-2022-11-28/interactions.json | 32 +++++++++++++++++-- .../data/ghec-2026-03-10/interactions.json | 32 +++++++++++++++++-- src/rest/lib/config.json | 2 +- src/webhooks/lib/config.json | 2 +- 7 files changed, 123 insertions(+), 11 deletions(-) diff --git a/src/github-apps/lib/config.json b/src/github-apps/lib/config.json index 15106af54316..044c0e8bafff 100644 --- a/src/github-apps/lib/config.json +++ b/src/github-apps/lib/config.json @@ -60,5 +60,5 @@ "2022-11-28" ] }, - "sha": "d4278c869e367f5d6d4e0f46878119128abba77b" + "sha": "338cb199baa4f326790b0b1c246d8d4f481a82a0" } \ No newline at end of file diff --git a/src/rest/data/fpt-2022-11-28/interactions.json b/src/rest/data/fpt-2022-11-28/interactions.json index daa7f6826411..f814cd1c0c87 100644 --- a/src/rest/data/fpt-2022-11-28/interactions.json +++ b/src/rest/data/fpt-2022-11-28/interactions.json @@ -318,6 +318,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -387,6 +391,11 @@ "type": "integer", "name": "max_open_pull_requests", "description": "

The maximum number of open pull requests a user can have at one time

" + }, + { + "type": "boolean", + "name": "include_drafts", + "description": "

Whether draft pull requests count toward the pull request creation cap

" } ], "descriptionHTML": "

Updates the pull request creation cap for an organization. The cap limits the total number\nof open pull requests a user can have across all public repositories in the organization\nat one time.

\n

Only users with admin access to the organization can configure the cap.

", @@ -398,7 +407,8 @@ "acceptHeader": "application/vnd.github.v3+json", "bodyParameters": { "enabled": true, - "max_open_pull_requests": 1 + "max_open_pull_requests": 1, + "include_drafts": true }, "parameters": { "org": "ORG" @@ -424,6 +434,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -1217,6 +1231,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -1295,6 +1313,11 @@ "type": "integer", "name": "max_open_pull_requests", "description": "

The maximum number of open pull requests a user can have at one time

" + }, + { + "type": "boolean", + "name": "include_drafts", + "description": "

Whether draft pull requests count toward the pull request creation cap

" } ], "descriptionHTML": "

Updates the pull request creation cap for a repository. The cap limits the number\nof open pull requests a user can have at one time.

\n

Only users with admin access to the repository can configure the cap.

", @@ -1306,7 +1329,8 @@ "acceptHeader": "application/vnd.github.v3+json", "bodyParameters": { "enabled": true, - "max_open_pull_requests": 1 + "max_open_pull_requests": 1, + "include_drafts": true }, "parameters": { "owner": "OWNER", @@ -1333,6 +1357,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ diff --git a/src/rest/data/fpt-2026-03-10/interactions.json b/src/rest/data/fpt-2026-03-10/interactions.json index daa7f6826411..f814cd1c0c87 100644 --- a/src/rest/data/fpt-2026-03-10/interactions.json +++ b/src/rest/data/fpt-2026-03-10/interactions.json @@ -318,6 +318,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -387,6 +391,11 @@ "type": "integer", "name": "max_open_pull_requests", "description": "

The maximum number of open pull requests a user can have at one time

" + }, + { + "type": "boolean", + "name": "include_drafts", + "description": "

Whether draft pull requests count toward the pull request creation cap

" } ], "descriptionHTML": "

Updates the pull request creation cap for an organization. The cap limits the total number\nof open pull requests a user can have across all public repositories in the organization\nat one time.

\n

Only users with admin access to the organization can configure the cap.

", @@ -398,7 +407,8 @@ "acceptHeader": "application/vnd.github.v3+json", "bodyParameters": { "enabled": true, - "max_open_pull_requests": 1 + "max_open_pull_requests": 1, + "include_drafts": true }, "parameters": { "org": "ORG" @@ -424,6 +434,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -1217,6 +1231,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -1295,6 +1313,11 @@ "type": "integer", "name": "max_open_pull_requests", "description": "

The maximum number of open pull requests a user can have at one time

" + }, + { + "type": "boolean", + "name": "include_drafts", + "description": "

Whether draft pull requests count toward the pull request creation cap

" } ], "descriptionHTML": "

Updates the pull request creation cap for a repository. The cap limits the number\nof open pull requests a user can have at one time.

\n

Only users with admin access to the repository can configure the cap.

", @@ -1306,7 +1329,8 @@ "acceptHeader": "application/vnd.github.v3+json", "bodyParameters": { "enabled": true, - "max_open_pull_requests": 1 + "max_open_pull_requests": 1, + "include_drafts": true }, "parameters": { "owner": "OWNER", @@ -1333,6 +1357,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ diff --git a/src/rest/data/ghec-2022-11-28/interactions.json b/src/rest/data/ghec-2022-11-28/interactions.json index daa7f6826411..f814cd1c0c87 100644 --- a/src/rest/data/ghec-2022-11-28/interactions.json +++ b/src/rest/data/ghec-2022-11-28/interactions.json @@ -318,6 +318,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -387,6 +391,11 @@ "type": "integer", "name": "max_open_pull_requests", "description": "

The maximum number of open pull requests a user can have at one time

" + }, + { + "type": "boolean", + "name": "include_drafts", + "description": "

Whether draft pull requests count toward the pull request creation cap

" } ], "descriptionHTML": "

Updates the pull request creation cap for an organization. The cap limits the total number\nof open pull requests a user can have across all public repositories in the organization\nat one time.

\n

Only users with admin access to the organization can configure the cap.

", @@ -398,7 +407,8 @@ "acceptHeader": "application/vnd.github.v3+json", "bodyParameters": { "enabled": true, - "max_open_pull_requests": 1 + "max_open_pull_requests": 1, + "include_drafts": true }, "parameters": { "org": "ORG" @@ -424,6 +434,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -1217,6 +1231,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -1295,6 +1313,11 @@ "type": "integer", "name": "max_open_pull_requests", "description": "

The maximum number of open pull requests a user can have at one time

" + }, + { + "type": "boolean", + "name": "include_drafts", + "description": "

Whether draft pull requests count toward the pull request creation cap

" } ], "descriptionHTML": "

Updates the pull request creation cap for a repository. The cap limits the number\nof open pull requests a user can have at one time.

\n

Only users with admin access to the repository can configure the cap.

", @@ -1306,7 +1329,8 @@ "acceptHeader": "application/vnd.github.v3+json", "bodyParameters": { "enabled": true, - "max_open_pull_requests": 1 + "max_open_pull_requests": 1, + "include_drafts": true }, "parameters": { "owner": "OWNER", @@ -1333,6 +1357,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ diff --git a/src/rest/data/ghec-2026-03-10/interactions.json b/src/rest/data/ghec-2026-03-10/interactions.json index daa7f6826411..f814cd1c0c87 100644 --- a/src/rest/data/ghec-2026-03-10/interactions.json +++ b/src/rest/data/ghec-2026-03-10/interactions.json @@ -318,6 +318,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -387,6 +391,11 @@ "type": "integer", "name": "max_open_pull_requests", "description": "

The maximum number of open pull requests a user can have at one time

" + }, + { + "type": "boolean", + "name": "include_drafts", + "description": "

Whether draft pull requests count toward the pull request creation cap

" } ], "descriptionHTML": "

Updates the pull request creation cap for an organization. The cap limits the total number\nof open pull requests a user can have across all public repositories in the organization\nat one time.

\n

Only users with admin access to the organization can configure the cap.

", @@ -398,7 +407,8 @@ "acceptHeader": "application/vnd.github.v3+json", "bodyParameters": { "enabled": true, - "max_open_pull_requests": 1 + "max_open_pull_requests": 1, + "include_drafts": true }, "parameters": { "org": "ORG" @@ -424,6 +434,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -1217,6 +1231,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ @@ -1295,6 +1313,11 @@ "type": "integer", "name": "max_open_pull_requests", "description": "

The maximum number of open pull requests a user can have at one time

" + }, + { + "type": "boolean", + "name": "include_drafts", + "description": "

Whether draft pull requests count toward the pull request creation cap

" } ], "descriptionHTML": "

Updates the pull request creation cap for a repository. The cap limits the number\nof open pull requests a user can have at one time.

\n

Only users with admin access to the repository can configure the cap.

", @@ -1306,7 +1329,8 @@ "acceptHeader": "application/vnd.github.v3+json", "bodyParameters": { "enabled": true, - "max_open_pull_requests": 1 + "max_open_pull_requests": 1, + "include_drafts": true }, "parameters": { "owner": "OWNER", @@ -1333,6 +1357,10 @@ "description": "The maximum number of open pull requests a user can have at one time", "minimum": 1, "maximum": 1000 + }, + "include_drafts": { + "type": "boolean", + "description": "Whether draft pull requests count toward the pull request creation cap" } }, "required": [ diff --git a/src/rest/lib/config.json b/src/rest/lib/config.json index c5102325a074..0f1025c61451 100644 --- a/src/rest/lib/config.json +++ b/src/rest/lib/config.json @@ -51,5 +51,5 @@ ] } }, - "sha": "d4278c869e367f5d6d4e0f46878119128abba77b" + "sha": "338cb199baa4f326790b0b1c246d8d4f481a82a0" } \ No newline at end of file diff --git a/src/webhooks/lib/config.json b/src/webhooks/lib/config.json index 3bbbdffbfe24..33beb61f3b4a 100644 --- a/src/webhooks/lib/config.json +++ b/src/webhooks/lib/config.json @@ -1,3 +1,3 @@ { - "sha": "d4278c869e367f5d6d4e0f46878119128abba77b" + "sha": "338cb199baa4f326790b0b1c246d8d4f481a82a0" } \ No newline at end of file From e69e757062188deff7ecfc8091d9876189c0fac6 Mon Sep 17 00:00:00 2001 From: hubwriter Date: Mon, 21 Sep 2026 19:40:12 +0000 Subject: [PATCH 4/4] Remove selected Copilot tutorials and preserve redirects (#63336) Co-authored-by: github-actions[bot] Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../concepts/prompting/prompt-engineering.md | 17 + .../get-started-with-chat-in-your-ide.md | 6 + .../use-copilot-to-create-or-update-issues.md | 5 +- .../reference/ai-models/model-comparison.md | 5 +- .../copilot/tutorials/compare-ai-models.md | 196 ------- .../generating-tables.md | 111 ---- .../communicate-effectively/index.md | 7 +- .../document-code/document-legacy-code.md | 156 ----- .../document-code/explain-complex-logic.md | 178 ------ .../document-code/explain-legacy-code.md | 124 ---- ...iling-issues-without-breaking-your-flow.md | 107 ---- .../copilot-cookbook/document-code/index.md | 20 - .../document-code/sync-documentation.md | 94 --- .../write-discussions-or-blog-posts.md | 106 ---- .../tutorials/copilot-cookbook/index.md | 2 - .../refactor-code/decouple-business-logic.md | 158 ------ .../refactor-code/fix-lint-errors.md | 82 --- .../refactor-code/improve-code-readability.md | 2 - .../copilot-cookbook/refactor-code/index.md | 8 +- .../refactor-code/refactor-design-patterns.md | 6 + .../refactor-for-optimization.md | 2 + .../refactor-for-sustainability.md | 64 --- .../refactor-code/translate-code.md | 8 +- .../testing-code/generate-unit-tests.md | 2 + .../copilot-cookbook/testing-code/index.md | 2 - .../testing-code/update-unit-tests.md | 123 ---- .../custom-instructions/concept-explainer.md | 3 + .../copilot/tutorials/explore-a-codebase.md | 12 + content/copilot/tutorials/index.md | 8 - .../copilot/tutorials/learn-a-new-language.md | 186 ------ .../copilot/tutorials/migrate-a-project.md | 534 ------------------ .../tutorials/modernize-java-applications.md | 138 ----- .../tutorials/modernize-legacy-code.md | 422 -------------- .../copilot/tutorials/optimize-ai-usage.md | 2 +- content/copilot/tutorials/plan-a-project.md | 114 ---- .../tutorials/reduce-technical-debt.md | 8 +- content/copilot/tutorials/refactor-code.md | 360 ------------ content/copilot/tutorials/upgrade-projects.md | 39 -- content/copilot/tutorials/use-an-ai-sme.md | 2 +- ...ting-with-maintainers-using-discussions.md | 6 - .../participating-in-a-discussion.md | 6 - .../using-github/communicating-on-github.md | 6 - .../organizing-information-with-tables.md | 2 + .../learning-about-issues/about-issues.md | 6 - 44 files changed, 82 insertions(+), 3363 deletions(-) delete mode 100644 content/copilot/tutorials/compare-ai-models.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/communicate-effectively/generating-tables.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/document-code/document-legacy-code.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/document-code/explain-complex-logic.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/document-code/explain-legacy-code.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/document-code/filing-issues-without-breaking-your-flow.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/document-code/index.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/document-code/sync-documentation.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/document-code/write-discussions-or-blog-posts.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/refactor-code/decouple-business-logic.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/refactor-code/fix-lint-errors.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-sustainability.md delete mode 100644 content/copilot/tutorials/copilot-cookbook/testing-code/update-unit-tests.md delete mode 100644 content/copilot/tutorials/learn-a-new-language.md delete mode 100644 content/copilot/tutorials/migrate-a-project.md delete mode 100644 content/copilot/tutorials/modernize-java-applications.md delete mode 100644 content/copilot/tutorials/modernize-legacy-code.md delete mode 100644 content/copilot/tutorials/plan-a-project.md delete mode 100644 content/copilot/tutorials/refactor-code.md delete mode 100644 content/copilot/tutorials/upgrade-projects.md diff --git a/content/copilot/concepts/prompting/prompt-engineering.md b/content/copilot/concepts/prompting/prompt-engineering.md index 3173dc8f2f0f..52ed13ccc3d2 100644 --- a/content/copilot/concepts/prompting/prompt-engineering.md +++ b/content/copilot/concepts/prompting/prompt-engineering.md @@ -9,6 +9,23 @@ redirect_from: - /copilot/using-github-copilot/copilot-chat/prompt-engineering-for-copilot-chat - /copilot/concepts/prompt-engineering-for-copilot-chat - /copilot/concepts/prompt-engineering + - /copilot/tutorials/copilot-cookbook/document-code + - /copilot/example-prompts-for-github-copilot-chat/documenting-code + - /copilot/copilot-chat-cookbook/documenting-code + - /copilot/tutorials/copilot-chat-cookbook/documenting-code + - /copilot/tutorials/copilot-chat-cookbook/document-code + - /copilot/tutorials/copilot-cookbook/document-code/document-legacy-code + - /copilot/example-prompts-for-github-copilot-chat/documenting-code/documenting-legacy-code + - /copilot/copilot-chat-cookbook/documenting-code/documenting-legacy-code + - /copilot/tutorials/copilot-chat-cookbook/documenting-code/documenting-legacy-code + - /copilot/tutorials/copilot-chat-cookbook/documenting-code/document-legacy-code + - /copilot/tutorials/copilot-chat-cookbook/document-code/document-legacy-code + - /copilot/tutorials/copilot-cookbook/document-code/sync-documentation + - /copilot/example-prompts-for-github-copilot-chat/documenting-code/syncing-documentation-with-code-changes + - /copilot/copilot-chat-cookbook/documenting-code/syncing-documentation-with-code-changes + - /copilot/tutorials/copilot-chat-cookbook/documenting-code/syncing-documentation-with-code-changes + - /copilot/tutorials/copilot-chat-cookbook/documenting-code/sync-documentation + - /copilot/tutorials/copilot-chat-cookbook/document-code/sync-documentation contentType: concepts category: - Configure Copilot diff --git a/content/copilot/how-tos/chat-with-copilot/get-started-with-chat-in-your-ide.md b/content/copilot/how-tos/chat-with-copilot/get-started-with-chat-in-your-ide.md index bffe36e3a0ec..1f92851d0709 100644 --- a/content/copilot/how-tos/chat-with-copilot/get-started-with-chat-in-your-ide.md +++ b/content/copilot/how-tos/chat-with-copilot/get-started-with-chat-in-your-ide.md @@ -13,6 +13,12 @@ redirect_from: - /copilot/how-tos/chat/get-started-with-chat - /copilot/how-tos/use-chat/get-started-with-chat - /copilot/how-tos/chat-with-copilot/get-started-with-chat + - /copilot/tutorials/copilot-cookbook/refactor-code/fix-lint-errors + - /copilot/example-prompts-for-github-copilot-chat/refactoring-code/fixing-lint-errors + - /copilot/copilot-chat-cookbook/refactoring-code/fixing-lint-errors + - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/fixing-lint-errors + - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/fix-lint-errors + - /copilot/tutorials/copilot-chat-cookbook/refactor-code/fix-lint-errors shortTitle: Get started with Chat in your IDE contentType: how-tos category: diff --git a/content/copilot/how-tos/copilot-on-github/copilot-for-github-tasks/use-copilot-to-create-or-update-issues.md b/content/copilot/how-tos/copilot-on-github/copilot-for-github-tasks/use-copilot-to-create-or-update-issues.md index e6a265155af3..48364349ad52 100644 --- a/content/copilot/how-tos/copilot-on-github/copilot-for-github-tasks/use-copilot-to-create-or-update-issues.md +++ b/content/copilot/how-tos/copilot-on-github/copilot-for-github-tasks/use-copilot-to-create-or-update-issues.md @@ -10,6 +10,10 @@ redirect_from: - /copilot/how-tos/github-flow/use-copilot-to-create-issues - /copilot/how-tos/use-copilot-for-common-tasks/use-copilot-to-create-issues - /copilot/how-tos/use-copilot-for-common-tasks/use-copilot-to-create-or-update-issues + - /copilot/tutorials/plan-a-project + - /copilot/tutorials/copilot-cookbook/document-code/filing-issues-without-breaking-your-flow + - /copilot/tutorials/copilot-chat-cookbook/document-code/creating-issues + - /copilot/tutorials/copilot-chat-cookbook/document-code/filing-issues-without-breaking-your-flow contentType: how-tos category: - Author and optimize with Copilot @@ -91,4 +95,3 @@ With {% data variables.copilot.copilot_cloud_agent %} enabled, you can assign an ## Further reading * [AUTOTITLE](/communities/using-templates-to-encourage-useful-issues-and-pull-requests/configuring-issue-templates-for-your-repository) -* [AUTOTITLE](/copilot/tutorials/plan-a-project) diff --git a/content/copilot/reference/ai-models/model-comparison.md b/content/copilot/reference/ai-models/model-comparison.md index 28b50a720059..e77e82800d8c 100644 --- a/content/copilot/reference/ai-models/model-comparison.md +++ b/content/copilot/reference/ai-models/model-comparison.md @@ -10,6 +10,10 @@ category: redirect_from: - /copilot/using-github-copilot/ai-models/choosing-the-right-ai-model-for-your-task - /copilot/reference/ai-models/choosing-the-right-ai-model-for-your-task + - /copilot/tutorials/compare-ai-models + - /copilot/using-github-copilot/ai-models/examples-for-ai-model-comparison + - /copilot/using-github-copilot/ai-models/comparing-ai-models-using-different-tasks + - /copilot/tutorials/comparing-ai-models-using-different-tasks contentType: reference --- @@ -149,6 +153,5 @@ Some models have behaviors, limitations, or safeguards that are useful to unders Choosing the right model helps you get the most out of {% data variables.product.prodname_copilot_short %}. If you're not sure which model to use, start with a general-purpose option like {% data variables.copilot.copilot_gpt_5_mini %}, then adjust based on your needs. * For detailed model specs and pricing, see [AUTOTITLE](/copilot/reference/ai-models/supported-models). -* For more examples of how to use different models, see [AUTOTITLE](/copilot/tutorials/compare-ai-models). * To switch between models, refer to [AUTOTITLE](/copilot/how-tos/use-ai-models/change-the-chat-model) or [AUTOTITLE](/copilot/how-tos/use-ai-models/change-the-completion-model). * To learn how {% data variables.copilot.copilot_chat_short %} serves different AI models, see [AUTOTITLE](/copilot/reference/ai-models/model-hosting). diff --git a/content/copilot/tutorials/compare-ai-models.md b/content/copilot/tutorials/compare-ai-models.md deleted file mode 100644 index 76739f238007..000000000000 --- a/content/copilot/tutorials/compare-ai-models.md +++ /dev/null @@ -1,196 +0,0 @@ ---- -title: Comparing AI models using different tasks -shortTitle: Compare AI models -intro: 'Explore real-world examples of common developer tasks along with sample prompts, responses, and guidance to help you choose the right AI model for your workflow.' -versions: - feature: copilot -redirect_from: - - /copilot/using-github-copilot/ai-models/examples-for-ai-model-comparison - - /copilot/using-github-copilot/ai-models/comparing-ai-models-using-different-tasks - - /copilot/tutorials/comparing-ai-models-using-different-tasks -contentType: tutorials -category: - - Rapid prototyping - - Author and optimize with Copilot ---- - -## Overview - -Each AI model supported in {% data variables.copilot.copilot_chat_short %} has different strengths. To help you decide which model to use, this article provides real-world examples of common developer tasks along with sample prompts, responses, and guidance on why a particular model is a good fit. - -These examples show how models vary in their reasoning style, response depth, and ability to handle visual input. Use them to compare output quality and choose the right model for your specific workflow. - -For a full list of supported models and side-by-side feature comparisons, see [AUTOTITLE](/copilot/reference/ai-models/model-comparison). - -## {% data variables.copilot.copilot_gpt_41 %} - -{% data reusables.copilot.model-use-cases.gpt-41 %} - -### Example scenario - -Consider a scenario where you are writing helper functions for access control in a Python service. You want to add docstrings to clarify the purpose of the function. - -Below is the helper function that grants editor access to a document: - -```python id=grant-editor-access -def grant_editor_access(user_id, doc_id): - access = AccessManager() - access.assign_role( - resource_type="document", - resource_id=doc_id, - role="editor", - user_id=user_id - ) -``` - -### Example prompt - -```copilot prompt copy ref=grant-editor-access -Add a docstring to the function that explains what it does. -``` - -### Example response - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -```python -def grant_editor_access(user_id, doc_id): - """ - Grants editor access to a specific document for a given user. - - This function uses the AccessManager to assign the "editor" role - to the specified user for the provided document ID. - - Args: - user_id (str): The ID of the user to grant access to. - doc_id (str): The ID of the document to which access is being granted. - """ - access = AccessManager() - access.assign_role( - resource_type="document", - resource_id=doc_id, - role="editor", - user_id=user_id - ) -``` - -### Why {% data variables.copilot.copilot_gpt_41 %} is a good fit - -* The function is short and self-contained, making it ideal for quick docstring generation. -* {% data variables.copilot.copilot_gpt_41 %} can recognize the pattern and provide a clear, concise explanation. -* The task doesn't require deep reasoning or complex logic. - -## {% data variables.copilot.copilot_gpt_5_mini %} - -OpenAI {% data variables.copilot.copilot_gpt_5_mini %} is a fast, cost-efficient model designed for simple or repetitive coding tasks. It delivers reliable, concise answers with very low latency, making it ideal for real-time suggestions and lightweight development workflows. {% data variables.copilot.copilot_gpt_5_mini %} is optimized for speed and responsiveness, so you can quickly iterate on small code changes or get instant feedback on straightforward prompts. - -### Example scenario - -Suppose you are building a utility script and need to filter a list of user records to include only active users, sorted by their signup date. The task is simple and doesn’t require deep reasoning or multi-step logic. - -Here’s a sample list of users: - -```python id=user-list -users = [ - {"name": "Alice", "active": True, "signup_date": "2023-12-10"}, - {"name": "Bob", "active": False, "signup_date": "2023-11-05"}, - {"name": "Charlie", "active": True, "signup_date": "2024-01-15"} -] -``` - -### Example prompt - -```copilot prompt copy ref=user-list -Filter the list of users to only include active users, and sort them by signup_date. -``` - -### Example response - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -```python -# Filter to only include active users -active_users = [user for user in users if user["active"]] - -# Sort active users by signup_date -active_users_sorted = sorted(active_users, key=lambda user: user["signup_date"]) - -print(active_users_sorted) -``` - -### Why {% data variables.copilot.copilot_gpt_5_mini %} is a good fit - -* The task is straightforward and benefits from fast, low-latency responses. -* {% data variables.copilot.copilot_gpt_5_mini %} is optimized for cost and speed, making it ideal for quick edits, prototyping, and utility code. -* Use this model when you want reliable answers for simple coding questions without waiting for unnecessary depth. - -## {% data variables.copilot.copilot_gpt_52 %} - -{% data reusables.copilot.model-use-cases.gpt-52 %} - -### Example scenario - -You’re designing a shopping cart system and have a UML class diagram that outlines the relationships between `Cart`, `Product`, `User`, and `Order`. Instead of writing out the system from scratch, you want to upload the image of the diagram and ask {% data variables.product.prodname_copilot_short %} to generate the classes. - -![Screenshot of a shopping cart UML diagram, showing the class details for Cart, Product, User, and Order.](/assets/images/help/copilot/shopping-cart-uml.png) - -### Example prompt - -```copilot copy -Use this UML diagram to generate the classes for a shopping cart system. -``` - -### Example response - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -{% data variables.product.prodname_copilot_short %} will generate a class for each of the classes in the diagram, including the relationships between them. Here’s the example code generated for the `Cart` class: - -```python -from cart_item import CartItem -from order import Order - -class Cart: - def __init__(self, cart_id, user_id): - self.cart_id = cart_id - self.user_id = user_id - self.items = [] - - def add_item(self, item): - self.items.append(item) - - def remove_item(self, item): - self.items = [i for i in self.items if i != item] - - def calculate_total(self): - return sum(item.quantity * item.product.price for item in self.items) - - def place_order(self): - # Implementation for placing an order - return Order("", None, 0) -``` - -### Why {% data variables.copilot.copilot_gpt_52 %} is a good fit - -* It can interpret visual assets, such as UML diagrams, wireframes, or flowcharts, to generate code scaffolding or suggest architecture. -* It can be useful for reviewing screenshots of UI layouts or form designs and generating. - -## {% data variables.copilot.copilot_claude_haiku_45 %} - -{% data reusables.copilot.model-use-cases.claude-haiku-45 %} - -### Example scenario - -Consider a scenario where you are implementing both unit tests and integration tests for an application. You want to ensure that the tests are comprehensive and cover any edge cases that you may and may not have thought of. - -For a complete walkthrough of the scenario, see [AUTOTITLE](/copilot/tutorials/write-tests). - -### Why {% data variables.copilot.copilot_claude_haiku_45 %} is a good fit - -* It performs well on everyday coding tasks like test generation, boilerplate scaffolding, and validation logic. -* The task leans into multi-step reasoning, but still stays within the confidence zone of a less advanced model because the logic isn’t too deep. - -## Further reading - -* [AUTOTITLE](/copilot/reference/ai-models/model-comparison) -* [AUTOTITLE](/copilot/tutorials/copilot-cookbook) diff --git a/content/copilot/tutorials/copilot-cookbook/communicate-effectively/generating-tables.md b/content/copilot/tutorials/copilot-cookbook/communicate-effectively/generating-tables.md deleted file mode 100644 index 8c3339b539c8..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/communicate-effectively/generating-tables.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: Generating tables -shortTitle: Generate tables -intro: '{% data variables.copilot.copilot_chat_short %} can help you create tables to organize information and present it clearly.' -versions: - feature: copilot -surface: - - Chat -octicon: copilot -category: - - Communicate effectively - - Author and optimize with Copilot - - Scale institutional knowledge -contentType: tutorials -redirect_from: - - /copilot/tutorials/copilot-chat-cookbook/communicate-effectively/generating-tables ---- - -{% data variables.copilot.copilot_chat %} can help you create tables for various purposes, such as organizing data, comparing options, or summarizing information. By using tables, you can present information in a clear and structured way that is easy to read and understand. You can ask {% data variables.copilot.copilot_chat_short %} to generate tables based on existing data or to create empty tables based on your specific requirements. - -## Example scenario - -You want to create a reference table for the people on your team, including their roles and availability. You can ask {% data variables.copilot.copilot_chat_short %} to generate a table that summarizes this information in a clear and organized way. - -## Example prompt 1 - -```text copy -Convert the following information into a markdown table: - -Name: Alice -Age: 30 -Occupation: Engineer -Timezone: PST -Availability: Mon-Fri, 9am-5pm - -Name: Bob -Age: 25 -Occupation: Designer -Timezone: EST -Availability: Mon-Thu, 10am-6pm - -Name: Carol -Age: 27 -Occupation: Writer -Timezone: CST -Availability: Mon-Thu, 8am-4pm - -Name: Dave -Age: 35 -Occupation: Manager -Timezone: PST -Availability: Mon-Fri, 10am-6pm - -Name: Eve -Age: 28 -Occupation: Analyst -Timezone: CST -Availability: Mon-Fri, 9am-5pm - -Name: Frank -Age: 32 -Occupation: Developer -Timezone: CST -Availability: Mon-Thu, 11am-7pm - -Name: Grace -Age: 29 -Occupation: Researcher -Timezone: EST -Availability: Mon-Fri, 9am-5pm - -Name: Heidi -Age: 31 -Occupation: Consultant -Timezone: PST -Availability: Mon-Fri, 9am-5pm - -Name: Ivan -Age: 26 -Occupation: Intern -Timezone: CST -Availability: Mon-Thu, 10am-6pm -``` - -## Example response 1 - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -{% data variables.product.prodname_copilot_short %} will provide you with a markdown table that organizes the information clearly. You can copy the table {% data variables.copilot.copilot_chat_short %} provides and use it in your documentation or project. - -```markdown -| Name | Age | Occupation | Timezone | Availability | -|--------|-----|-------------|----------|-----------------------| -| Alice | 30 | Engineer | PST | Mon-Fri, 9am-5pm | -| Bob | 25 | Designer | EST | Mon-Thu, 10am-6pm | -| Carol | 27 | Writer | CST | Mon-Thu, 8am-4pm | -| Dave | 35 | Manager | PST | Mon-Fri, 10am-6pm | -| Eve | 28 | Analyst | CST | Mon-Fri, 9am-5pm | -| Frank | 32 | Developer | CST | Mon-Thu, 11am-7pm | -| Grace | 29 | Researcher | EST | Mon-Fri, 9am-5pm | -| Heidi | 31 | Consultant | PST | Mon-Fri, 9am-5pm | -| Ivan | 26 | Intern | CST | Mon-Thu, 10am-6pm | -``` - -## Next steps - -You can experiment with different types of visualizations and data to see how {% data variables.copilot.copilot_chat_short %} can help you create organized and easy-to-read information. For example, you could ask {% data variables.copilot.copilot_chat_short %} to use the `Timezone` and `Availability` columns to create a Mermaid graph that shows overlapping working hours for team members in different time zones. See [AUTOTITLE](/copilot/tutorials/copilot-cookbook/communicate-effectively/creating-diagrams) for more information. - -## Further reading - -{% data reusables.copilot.example-prompts.further-reading-items %} diff --git a/content/copilot/tutorials/copilot-cookbook/communicate-effectively/index.md b/content/copilot/tutorials/copilot-cookbook/communicate-effectively/index.md index a100c2b65dde..27417c4d93ec 100644 --- a/content/copilot/tutorials/copilot-cookbook/communicate-effectively/index.md +++ b/content/copilot/tutorials/copilot-cookbook/communicate-effectively/index.md @@ -8,9 +8,12 @@ children: - /summarize-repository-activity - /synthesizing-research - /creating-diagrams - - /generating-tables contentType: tutorials redirect_from: - /copilot/tutorials/copilot-chat-cookbook/communicate-effectively + - /copilot/tutorials/copilot-cookbook/document-code/write-discussions-or-blog-posts + - /copilot/copilot-chat-cookbook/documenting-code/writing-discussions-or-blog-posts + - /copilot/tutorials/copilot-chat-cookbook/documenting-code/writing-discussions-or-blog-posts + - /copilot/tutorials/copilot-chat-cookbook/documenting-code/write-discussions-or-blog-posts + - /copilot/tutorials/copilot-chat-cookbook/document-code/write-discussions-or-blog-posts --- - diff --git a/content/copilot/tutorials/copilot-cookbook/document-code/document-legacy-code.md b/content/copilot/tutorials/copilot-cookbook/document-code/document-legacy-code.md deleted file mode 100644 index 84c1ce4fb606..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/document-code/document-legacy-code.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: Documenting legacy code -shortTitle: Document legacy code -intro: '{% data variables.copilot.copilot_chat_short %} can help with documenting legacy code.' -redirect_from: - - /copilot/example-prompts-for-github-copilot-chat/documenting-code/documenting-legacy-code - - /copilot/copilot-chat-cookbook/documenting-code/documenting-legacy-code - - /copilot/tutorials/copilot-chat-cookbook/documenting-code/documenting-legacy-code - - /copilot/tutorials/copilot-chat-cookbook/documenting-code/document-legacy-code - - /copilot/tutorials/copilot-chat-cookbook/document-code/document-legacy-code -versions: - feature: copilot -category: - - Documenting code - - Author and optimize with Copilot - - Scale institutional knowledge -surface: - - Chat -octicon: book -contentType: tutorials ---- -Working with legacy code can be challenging for developers, especially when the code is complex or not well-documented. In such cases, it can be helpful to use Copilot Chat to explain unclear or complex code to other developers or to document it for future reference. - -## Example scenario - -The block of COBOL below connects to a database and inserts a record. The code lacks documentation, which makes it difficult to understand what it does and how it works. - -```text id=cobol-insert-record -IDENTIFICATION DIVISION. -PROGRAM-ID. INSERT-RECORD. - -ENVIRONMENT DIVISION. - -DATA DIVISION. -WORKING-STORAGE SECTION. -01 WS-STATUS-FLAGS. - 05 WS-DB-STATUS PIC X(2). - 88 WS-SUCCESS VALUE "00". - 05 WS-SQLCODE PIC S9(9) COMP. - 05 WS-ERROR-MSG PIC X(50). - -LINKAGE SECTION. -01 LS-PARAMETERS. - 05 LS-PERSON-RECORD. - 10 PERSON-ID PIC 9(6). - 10 PERSON-NAME PIC X(50). - 10 PERSON-AGE PIC 9(3). - 05 LS-RESULT PIC X. - 88 SUCCESS VALUE 'T'. - 88 FAILED VALUE 'F'. - -PROCEDURE DIVISION USING LS-PARAMETERS. - PERFORM INSERT-AND-VALIDATE - GOBACK - . - -INSERT-AND-VALIDATE. - EXEC SQL - INSERT INTO persons (id, name, age) - VALUES (:PERSON-ID, :PERSON-NAME, :PERSON-AGE) - END-EXEC - - IF SQLCODE = 0 - EXEC SQL COMMIT END-EXEC - SET SUCCESS TO TRUE - ELSE - EXEC SQL ROLLBACK END-EXEC - SET FAILED TO TRUE - STRING "DB Error: " SQLCODE - DELIMITED BY SIZE - INTO WS-ERROR-MSG - DISPLAY WS-ERROR-MSG - END-IF - . -``` - -## Example prompt - -We can use a simple prompt to ask {% data variables.copilot.copilot_chat_short %} to add documentation to the code. - -```copilot copy prompt ref=cobol-insert-record -Comment this code thoroughly -``` - -> [!NOTE] If you want the documentation generated in another format like Markdown, you can specify the desired output format in the prompt. For example: `Document this code in Markdown`. - -## Example response - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -Copilot will provide a text overview of the code block, and an updated version with comments explaining the logic and purpose of each section. - -For example: - -```text -***************************************************************** -* Program: INSERT-RECORD -* Purpose: Inserts a person record into the database with -* transaction management and error handling -***************************************************************** - IDENTIFICATION DIVISION. - PROGRAM-ID. INSERT-RECORD. - - ENVIRONMENT DIVISION. - - DATA DIVISION. - WORKING-STORAGE SECTION. -* Status flags and error handling variables - 01 WS-STATUS-FLAGS. - 05 WS-DB-STATUS PIC X(2). *> Database status - 88 WS-SUCCESS VALUE "00". *> Success flag - 05 WS-SQLCODE PIC S9(9) COMP. *> SQL return code - 05 WS-ERROR-MSG PIC X(50). *> Error message - - LINKAGE SECTION. -* Input/Output parameters - 01 LS-PARAMETERS. - 05 LS-PERSON-RECORD. - 10 PERSON-ID PIC 9(6). *> Person ID - 10 PERSON-NAME PIC X(50). *> Person name - 10 PERSON-AGE PIC 9(3). *> Person age - 05 LS-RESULT PIC X. *> Operation result - 88 SUCCESS VALUE 'T'. *> Success flag - 88 FAILED VALUE 'F'. *> Failure flag - - PROCEDURE DIVISION USING LS-PARAMETERS. - PERFORM INSERT-AND-VALIDATE - GOBACK - . - -***************************************************************** -* Handles database insertion with transaction management -***************************************************************** - INSERT-AND-VALIDATE. - EXEC SQL - INSERT INTO persons (id, name, age) - VALUES (:PERSON-ID, :PERSON-NAME, :PERSON-AGE) - END-EXEC - - IF SQLCODE = 0 - EXEC SQL COMMIT END-EXEC *> Commit if successful - SET SUCCESS TO TRUE - ELSE - EXEC SQL ROLLBACK END-EXEC *> Rollback if failed - SET FAILED TO TRUE - STRING "DB Error: " SQLCODE - DELIMITED BY SIZE - INTO WS-ERROR-MSG - DISPLAY WS-ERROR-MSG - END-IF - . -``` - -## Further reading - -{% data reusables.copilot.example-prompts.further-reading-items %} diff --git a/content/copilot/tutorials/copilot-cookbook/document-code/explain-complex-logic.md b/content/copilot/tutorials/copilot-cookbook/document-code/explain-complex-logic.md deleted file mode 100644 index 5eb0744b042d..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/document-code/explain-complex-logic.md +++ /dev/null @@ -1,178 +0,0 @@ ---- -title: Explaining complex algorithms or logic -shortTitle: Explain complex logic -intro: '{% data variables.copilot.copilot_chat_short %} can help add clear and concise documentation on complex algorithms or logic.' -redirect_from: - - /copilot/example-prompts-for-github-copilot-chat/documenting-code/explaining-complex-algorithms-or-logic - - /copilot/copilot-chat-cookbook/documenting-code/explaining-complex-algorithms-or-logic - - /copilot/tutorials/copilot-chat-cookbook/documenting-code/explaining-complex-algorithms-or-logic - - /copilot/tutorials/copilot-chat-cookbook/documenting-code/explain-complex-logic - - /copilot/tutorials/copilot-chat-cookbook/document-code/explain-complex-logic -versions: - feature: copilot -category: - - Documenting code - - Author and optimize with Copilot - - Scale institutional knowledge -surface: - - Chat -octicon: book -contentType: tutorials ---- - -There may be times where you need to explain complex algorithms or logic in your code. This can be challenging, especially when you're trying to make it understandable to others. {% data variables.copilot.copilot_chat_short %} can help you with this task by providing you with suggestions on how to explain the algorithm or logic in a clear and concise manner. - -## Example scenario - -In the C# code below, we have a method which fetches data, retries if there's an error, and updates a status label. You might want to explain, in comments in the code, how the method works and how it handles retries and cancellations. - -```csharp id=fetch-data-with-retry -private static readonly HttpClient _client = new HttpClient(); - -public async Task FetchDataFromApiWithRetryAsync(string apiUrl, CancellationToken cancellationToken, int maxRetries, int cancellationDelay, Label statusLabel) -{ - var retryCount = 0; - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - - while (retryCount < maxRetries) - { - try - { - cts.CancelAfter(cancellationDelay); - return await FetchDataFromApiAsync(cts.Token, statusLabel); - } - catch (Exception ex) when (!(ex is OperationCanceledException)) - { - if (retryCount < maxRetries - 1) { - retryCount++; - int delay = (int)Math.Pow(2, retryCount) * 1000; - await Task.Delay(delay, cancellationToken); - UpdateStatusLabel($"Retrying ({retryCount}/{maxRetries})...", statusLabel); - } else { - throw new Exception($"Failed to fetch data after {maxRetries} retries: {ex.Message}", ex); - } - } - } - - throw new OperationCanceledException("The operation was cancelled.", cts.Token); -} - -private async Task FetchDataFromApiAsync(string apiUrl, CancellationToken cancellationToken, Label statusLabel) -{ - UpdateStatusLabel("Fetching data...", statusLabel); - - HttpResponseMessage response = await _client.GetAsync(apiUrl, cancellationToken); - response.EnsureSuccessStatusCode(); - string data = await response.Content.ReadAsStringAsync(); - - UpdateStatusLabel("Data fetched.", statusLabel); - return data; -} - -private void UpdateStatusLabel(string message, Label statusLabel) -{ - if (statusLabel.InvokeRequired) { - statusLabel.BeginInvoke(new Action(UpdateStatusLabel), message, statusLabel); - } else { - statusLabel.Text = message; - } -} -``` - -## Example prompt - -We can ask {% data variables.copilot.copilot_chat_short %} to make this code easier to understand using comments. - -```copilot copy prompt ref=fetch-data-with-retry -Add comments to this code to make it more understandable -``` - -## Example response - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -{% data variables.product.prodname_copilot_short %} responds with an overview of the update it suggests, and the code snippet with the comments added: - -```csharp -// Shared HttpClient instance for making HTTP requests (best practice for reuse) -private static readonly HttpClient _client = new HttpClient(); - -/// -/// Fetches data from an API with retry mechanism and timeout functionality -/// -/// The URL to fetch data from -/// Token to cancel the operation -/// Maximum number of retry attempts -/// Timeout duration in milliseconds -/// UI label to show status updates -public async Task FetchDataFromApiWithRetryAsync(string apiUrl, CancellationToken cancellationToken, int maxRetries, int cancellationDelay, Label statusLabel) -{ - var retryCount = 0; - // Create a linked cancellation token that combines user cancellation and timeout - using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); - - while (retryCount < maxRetries) - { - try - { - // Set timeout for this attempt - cts.CancelAfter(cancellationDelay); - return await FetchDataFromApiAsync(cts.Token, statusLabel); - } - catch (Exception ex) when (!(ex is OperationCanceledException)) - { - // If not the last retry attempt, implement exponential backoff - if (retryCount < maxRetries - 1) { - retryCount++; - // Exponential backoff: 2^retryCount seconds (1s, 2s, 4s, 8s, etc.) - int delay = (int)Math.Pow(2, retryCount) * 1000; - await Task.Delay(delay, cancellationToken); - UpdateStatusLabel($"Retrying ({retryCount}/{maxRetries})...", statusLabel); - } else { - // If all retries failed, throw exception with details - throw new Exception($"Failed to fetch data after {maxRetries} retries: {ex.Message}", ex); - } - } - } - - // This is reached if maxRetries is 0 or some other unexpected case - throw new OperationCanceledException("The operation was cancelled.", cts.Token); -} - -/// -/// Makes the actual API call to fetch data -/// -private async Task FetchDataFromApiAsync(string apiUrl, CancellationToken cancellationToken, Label statusLabel) -{ - UpdateStatusLabel("Fetching data...", statusLabel); - - // Perform HTTP GET request with cancellation support - HttpResponseMessage response = await _client.GetAsync(apiUrl, cancellationToken); - response.EnsureSuccessStatusCode(); // Throws if response is not successful - string data = await response.Content.ReadAsStringAsync(); - - UpdateStatusLabel("Data fetched.", statusLabel); - return data; -} - -/// -/// Updates UI label text safely across threads -/// -/// The message to display -/// The label control to update -private void UpdateStatusLabel(string message, Label statusLabel) -{ - // Check if we need to invoke on UI thread - if (statusLabel.InvokeRequired) { - // Use BeginInvoke to update label on UI thread - statusLabel.BeginInvoke(new Action(UpdateStatusLabel), message, statusLabel); - } else { - // Direct update if already on UI thread - statusLabel.Text = message; - } -} -``` - -## Further reading - -{% data reusables.copilot.example-prompts.further-reading-items %} diff --git a/content/copilot/tutorials/copilot-cookbook/document-code/explain-legacy-code.md b/content/copilot/tutorials/copilot-cookbook/document-code/explain-legacy-code.md deleted file mode 100644 index 89c07c2349e5..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/document-code/explain-legacy-code.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Explaining legacy code -shortTitle: Explain legacy code -intro: '{% data variables.copilot.copilot_chat_short %} can help with explaining unfamiliar code.' -redirect_from: - - /copilot/example-prompts-for-github-copilot-chat/documenting-code/explaining-legacy-code - - /copilot/copilot-chat-cookbook/documenting-code/explaining-legacy-code - - /copilot/tutorials/copilot-chat-cookbook/documenting-code/explaining-legacy-code - - /copilot/tutorials/copilot-chat-cookbook/documenting-code/explain-legacy-code - - /copilot/tutorials/copilot-chat-cookbook/document-code/explain-legacy-code -versions: - feature: copilot -category: - - Documenting code - - Author and optimize with Copilot - - Scale institutional knowledge -surface: - - Chat -octicon: book -contentType: tutorials ---- - -One of the biggest challenges with legacy code is helping developers understand it who aren't familiar with the languages or frameworks. With {% data variables.copilot.copilot_chat_short %}, you can explain the background you have and ask for an explanation. - -## Example scenario - -Consider the following COBOL code. If you're a Python developer (as an example), you might not be familiar with COBOL, so you could ask {% data variables.copilot.copilot_chat_short %} to explain the code to you. - -```text id=cobol-insert-record -IDENTIFICATION DIVISION. -PROGRAM-ID. INSERT-RECORD. - -ENVIRONMENT DIVISION. - -DATA DIVISION. -WORKING-STORAGE SECTION. -01 WS-STATUS-FLAGS. - 05 WS-DB-STATUS PIC X(2). - 88 WS-SUCCESS VALUE "00". - 05 WS-SQLCODE PIC S9(9) COMP. - 05 WS-ERROR-MSG PIC X(50). - -LINKAGE SECTION. -01 LS-PARAMETERS. - 05 LS-PERSON-RECORD. - 10 PERSON-ID PIC 9(6). - 10 PERSON-NAME PIC X(50). - 10 PERSON-AGE PIC 9(3). - 05 LS-RESULT PIC X. - 88 SUCCESS VALUE 'T'. - 88 FAILED VALUE 'F'. - -PROCEDURE DIVISION USING LS-PARAMETERS. - PERFORM INSERT-AND-VALIDATE - GOBACK - . - -INSERT-AND-VALIDATE. - EXEC SQL - INSERT INTO persons (id, name, age) - VALUES (:PERSON-ID, :PERSON-NAME, :PERSON-AGE) - END-EXEC - - IF SQLCODE = 0 - EXEC SQL COMMIT END-EXEC - SET SUCCESS TO TRUE - ELSE - EXEC SQL ROLLBACK END-EXEC - SET FAILED TO TRUE - STRING "DB Error: " SQLCODE - DELIMITED BY SIZE - INTO WS-ERROR-MSG - DISPLAY WS-ERROR-MSG - END-IF - . -``` - -## Example prompt - -You can ask for an explanation of the COBOL code from the point of view of a Python developer. - -```copilot copy prompt ref=cobol-insert-record -I'm a Python developer. Help me better understand this code. Please provide analogies. -``` - -## Example response - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -{% data variables.product.prodname_copilot_short %} provides a high-level overview of the code, before walking through the various operations and explaining them in a way that Python developers can understand. It uses analogies to make the explanation more accessible. The response might start with the following: - -```text -Let me explain this COBOL code using Python analogies: - -High-Level Overview -This is similar to a Python function that inserts a person's record into a database with error handling. -``` - -```python -# In Python, the COBOL divisions would be like: - -# IDENTIFICATION DIVISION = module/file name -# PROGRAM-ID = function name -def insert_record(): - pass - -# DATA DIVISION would be like declaring these variables: -class WorkingStorage: - db_status = "" # WS-DB-STATUS - sqlcode = 0 # WS-SQLCODE - error_msg = "" # WS-ERROR-MSG - -# LINKAGE SECTION is like function parameters -class PersonRecord: - def __init__(self, person_id: int, person_name: str, person_age: int): - self.person_id = person_id # PERSON-ID - self.person_name = person_name # PERSON-NAME - self.person_age = person_age # PERSON-AGE - self.success = False # LS-RESULT -``` - -## Further reading - -{% data reusables.copilot.example-prompts.further-reading-items %} diff --git a/content/copilot/tutorials/copilot-cookbook/document-code/filing-issues-without-breaking-your-flow.md b/content/copilot/tutorials/copilot-cookbook/document-code/filing-issues-without-breaking-your-flow.md deleted file mode 100644 index cc7a73f964de..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/document-code/filing-issues-without-breaking-your-flow.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Filing issues without breaking your flow -shortTitle: File issues without breaking flow -intro: When something catches your attention mid-task, use {% data variables.copilot.copilot_cli_short %} to file a GitHub issue with code context, linked PRs, and labels, then get back to what you were doing. -redirect_from: - - /copilot/tutorials/copilot-chat-cookbook/document-code/creating-issues - - /copilot/tutorials/copilot-chat-cookbook/document-code/filing-issues-without-breaking-your-flow -versions: - feature: copilot -category: - - Documenting code - - Author and optimize with Copilot -surface: - - CLI -octicon: issue-opened -contentType: tutorials ---- - -{% data variables.copilot.copilot_cli_short %} can open GitHub issues for you from the terminal. Instead of switching to a browser and filling out an issue by hand, you describe what you want and Copilot gathers context from your repository and GitHub, then creates the issue so you can keep working. - -## Example scenario 1: Filing an issue from a CI failure - -Your CI is failing or you've spotted errors in production logs. Rather than manually tracing the stack trace back to a commit, you ask {% data variables.copilot.copilot_cli_short %} to investigate and file the issue for you. - -### Example prompt - -```text copy -The CI workflow on main has been failing since yesterday. Look at the failing -run, figure out what's breaking and which commit likely introduced it, then -create an issue with the stack trace, a link to the failing run, and the -suspected PR that caused it. Label it "bug" and "regression". -``` - -### Example response - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -{% data variables.copilot.copilot_cli_short %} uses its GitHub MCP tools to: - - -1. **Fetch the failing workflow run** and extract the stack trace from the logs. -1. **Identify the responsible code** — for example, `src/services/payment.ts:94`. -1. **Search recent commits** touching that file and find the PR that introduced the change. -1. **Create an issue** with all the context assembled: - - ```text - Created issue #421: Regression: PaymentService throws TypeError after #398 - - What's failing: - The `build` job on main has failed since commit `a3f7c21`. Stack trace: - - TypeError: Cannot read properties of undefined (reading 'amount') at processRefund (src/services/payment.ts:94:22) - - Introduced by: PR #398 (merged 2 days ago) refactored the payment types but missed updating `processRefund` to handle the new nullable `transaction` field. - - Failing run: Actions run #2847 - - Suggested fix: Add a null check for `transaction` before accessing `transaction.amount` on line 94. - - Labels: `bug`, `regression` - ``` - -## Example scenario 2: Turning TODOs into tracked work - -Over time, TODO and FIXME comments accumulate in a codebase with no visibility. You can ask {% data variables.copilot.copilot_cli_short %} to scan for these comments, assess priority, and create issues so the work is tracked. - -### Example prompt - -```text copy -Scan this repo for TODO and FIXME comments. Group them by area, pick the 5 -most important ones based on the surrounding code context, and create an issue -for each. Include the code snippet, file location, and suggest a label. -``` - -### Example response - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -{% data variables.copilot.copilot_cli_short %} searches the codebase, reads the context around each comment, and prioritizes based on severity: - -```text -Found 23 TODO/FIXME comments across the repo. Here are the 5 I'd prioritize: - -Created issue #422: FIXME: SQL injection risk in search query builder -- src/db/search.ts:34 — user input concatenated directly into query string -- Label: security, priority:high - -Created issue #423: TODO: Rate limiter bypassed for internal routes -- src/middleware/rate_limit.ts:12 — comment says "temporary bypass, remove before launch" -- Label: security, technical-debt - -Created issue #424: FIXME: Memory leak in WebSocket handler -- src/ws/handler.ts:87 — listeners are added on each connection but never cleaned up -- Label: bug, performance - -Created issue #425: TODO: Retry logic missing for payment webhook -- src/webhooks/payment.ts:56 — failures silently dropped, no retry queue -- Label: reliability, priority:medium - -Created issue #426: TODO: Migrate to new auth token format -- src/auth/token.ts:3 — comment references a closing down API version -- Label: technical-debt -``` - -## Further reading - -* [AUTOTITLE](/copilot/how-tos/copilot-cli) diff --git a/content/copilot/tutorials/copilot-cookbook/document-code/index.md b/content/copilot/tutorials/copilot-cookbook/document-code/index.md deleted file mode 100644 index 6bb0d4037ed9..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/document-code/index.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: Document code -intro: Discover ways that you can use {% data variables.copilot.copilot_chat %} to document your code. -redirect_from: - - /copilot/example-prompts-for-github-copilot-chat/documenting-code - - /copilot/copilot-chat-cookbook/documenting-code - - /copilot/tutorials/copilot-chat-cookbook/documenting-code - - /copilot/tutorials/copilot-chat-cookbook/document-code -versions: - feature: copilot -children: - - /filing-issues-without-breaking-your-flow - - /document-legacy-code - - /explain-legacy-code - - /explain-complex-logic - - /sync-documentation - - /write-discussions-or-blog-posts -contentType: tutorials ---- - diff --git a/content/copilot/tutorials/copilot-cookbook/document-code/sync-documentation.md b/content/copilot/tutorials/copilot-cookbook/document-code/sync-documentation.md deleted file mode 100644 index b5f884f2f5e3..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/document-code/sync-documentation.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Syncing documentation with code changes -shortTitle: Sync documentation -intro: '{% data variables.copilot.copilot_chat_short %} can help with keeping code documentation up-to-date.' -redirect_from: - - /copilot/example-prompts-for-github-copilot-chat/documenting-code/syncing-documentation-with-code-changes - - /copilot/copilot-chat-cookbook/documenting-code/syncing-documentation-with-code-changes - - /copilot/tutorials/copilot-chat-cookbook/documenting-code/syncing-documentation-with-code-changes - - /copilot/tutorials/copilot-chat-cookbook/documenting-code/sync-documentation - - /copilot/tutorials/copilot-chat-cookbook/document-code/sync-documentation -versions: - feature: copilot -category: - - Documenting code - - Author and optimize with Copilot - - Scale institutional knowledge -surface: - - Chat -octicon: book -contentType: tutorials ---- - -It can be difficult to keep documentation up to date with changes to code. However, good documentation is essential for maintaining codebases and ensuring that developers can work effectively with the code. {% data variables.copilot.copilot_chat_short %} can assist in updating existing code documentation. - -## Example scenario - - Imagine a scenario where you have a TypeScript function that retrieves products by category name, but the documentation is out of date. - -```typescript id=fetch-products-by-category -/** - * Retrieves all products belonging to a specific category. - * - * @param categoryId - The unique identifier of the product category - * @returns Promise that resolves to an array of Product objects - * - * @example - * const products = await getByCategoryName(5); - * // Returns: [{id: 1, name: "Product 1", categoryId: 5}, ...] - * - * @throws {PrismaClientKnownRequestError} If database query fails - * @see {@link https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#findmany} - */ -async getByCategoryName(categoryId: number, page = 1, pageSize = 10): Promise { - return await prisma.products.findMany({ - where: { categoryId }, - skip: (page - 1) * pageSize, - take: pageSize, - include: { - reviews: { - orderBy: { date: 'desc' }, - take: 5, - }, - }, - }); -} -``` - -## Example prompt - -You can ask {% data variables.copilot.copilot_chat_short %} to update the documentation according to the current code. - -```copilot copy prompt ref=fetch-products-by-category -Update the existing documentation for the getByCategoryName function to reflect the current implementation. -``` - -## Example response - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -{% data variables.product.prodname_copilot_short %} explains it will create the updated documentation for the `getByCategoryName` function. It then provides the updated documentation, which now includes the `page` and `pageSize` parameters, as well as the `PrismaClientKnownRequestError` error that can be thrown. - -For example: - -```typescript -/** - * Retrieves all products belonging to a specific category with pagination and recent reviews. - * - * @param categoryId - The unique identifier of the product category - * @param page - The page number for pagination (default: 1) - * @param pageSize - Number of products per page (default: 10) - * @returns Promise that resolves to an array of Product objects with their 5 most recent reviews - * - * @example - * const products = await getByCategoryName(5, 2, 20); - * // Returns: [{id: 1, name: "Product 1", categoryId: 5, reviews: [...5 recent reviews]}, ...] - * - * @throws {PrismaClientKnownRequestError} If database query fails - * @see {@link https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#findmany} - */ -``` - -## Further reading - -{% data reusables.copilot.example-prompts.further-reading-items %} diff --git a/content/copilot/tutorials/copilot-cookbook/document-code/write-discussions-or-blog-posts.md b/content/copilot/tutorials/copilot-cookbook/document-code/write-discussions-or-blog-posts.md deleted file mode 100644 index 4bd58f2d02c4..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/document-code/write-discussions-or-blog-posts.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Writing discussions or blog posts -shortTitle: Write discussions or blog posts -intro: '{% data variables.copilot.copilot_chat_short %} can help you generate ideas, outline, or draft discussions or blog posts.' -versions: - feature: copilot -category: - - Documenting code - - Author and optimize with Copilot - - Scale institutional knowledge -surface: - - Chat -octicon: book -redirect_from: - - /copilot/copilot-chat-cookbook/documenting-code/writing-discussions-or-blog-posts - - /copilot/tutorials/copilot-chat-cookbook/documenting-code/writing-discussions-or-blog-posts - - /copilot/tutorials/copilot-chat-cookbook/documenting-code/write-discussions-or-blog-posts - - /copilot/tutorials/copilot-chat-cookbook/document-code/write-discussions-or-blog-posts -contentType: tutorials ---- - -When you're working on code, you often need to quickly create accurate and comprehensive explanations to share your work with teammates or the broader community. {% data variables.copilot.copilot_chat_short %} can help by suggesting ideas, outlines, or complete drafts for discussions or blog posts—enabling you to document and communicate clearly, so you can spend more time focused on coding. - ->[!TIP] You can include links to specific pull requests or issues in your prompts to give {% data variables.copilot.copilot_chat_short %} more context. If you're not getting the results you expect, try specifying the repository in your prompt to help {% data variables.copilot.copilot_chat_short %} focus on the right project. - -## Generating ideas - -When you're working on a project, you may need to write a discussion or blog post to share your ideas, get feedback, or communicate with your team. {% data variables.copilot.copilot_chat_short %} can help you generate ideas. - -### Brainstorming topics from recent work - -If you're looking for ideas for a discussion post, you can ask {% data variables.copilot.copilot_chat_short %} to suggest topics based on your recent work. - -#### Example prompts - -`I’ve worked on three major PRs (#21, #27, and #44) in the last month. Could you suggest five potential blog topics that highlight the unique challenges or solutions from each PR?` - -`We improved backend performance in PR #16 and addressed user feedback in Issues #10 and #12. What interesting blog ideas can you propose that tie these updates together for a developer audience?` - -`We released a major version upgrade in PR #99 for our library. Could you suggest three blog angles that highlight the major changes, the lessons we learned, and how the community can benefit from it?` - -`We’ve been working on a new AI-driven feature in PR #120. Please propose some blog post titles and short descriptions that will catch developers’ attention while explaining how this feature fits into our product roadmap.` - -### Writing technical deep dives - -When you're working on a complex feature or system, you may need to write a technical deep dive to share your work with your team or the broader community. {% data variables.copilot.copilot_chat_short %} can help you generate ideas for technical deep dives by suggesting topics based on your recent work. - -#### Example prompts - -`I just finished implementing a complex authentication flow in PR #30. Could you outline a blog post explaining the challenges we faced, the approach we took to solve them, and a brief code example highlighting key sections?` - -`Generate a blog outline that discusses our shift to a more modular architecture in PR #55. I want to explain why we made the switch, how it impacts scalability, and any trade-offs we faced along the way.` - -`Propose a developer-focused blog post centered on the new caching mechanism we built in PR #64. Highlight key aspects of the implementation, show code snippets, and explain the performance improvements.` - -### Sharing best practices - -When you're working on a project, you may need to write a discussion post to share best practices or lessons learned. {% data variables.copilot.copilot_chat_short %} can help you generate ideas for discussion posts. - -#### Example prompt - -`I just finished implementing a complex authentication flow in PR #30. Could you outline a blog post explaining the challenges we faced, the approach we took to solve them, and a brief code summary highlighting best practices?` - -## Drafting content - -Once you have an idea for a discussion or blog post, you can ask {% data variables.copilot.copilot_chat_short %} to help you draft the content. {% data variables.copilot.copilot_chat_short %} can provide you with a detailed outline, a rough draft, or a polished draft, depending on your needs. - -### Outlining a blog post - -If you're looking for help outlining a blog post, you can ask {% data variables.copilot.copilot_chat_short %} to suggest a detailed outline for your post. - -#### Example prompt - -`Please propose an outline for a blog post based on PR #16 and Issues #10 and #12. Include new features introduced, user-facing improvements, and next steps.` - -### Drafting a blog post - -If you're looking for help drafting a blog post, you can ask {% data variables.copilot.copilot_chat_short %} to suggest a rough draft for your post. - -#### Example prompts - -`Please write a short blog post describing how we integrated a new logging module from PR #40. Highlight how it benefits users, and suggest next steps.` - -`I’d like a draft paragraph summarizing exciting new features or important changes introduced in recent commits. Please explain clearly what changed and why it's significant for users.` - -`Generate a brief ‘shout-out’ paragraph that highlights the contributors who submitted PRs #33 and #37, explaining their impact and thanking them for their work.` - -## Refining your draft - -Once you have a draft, you can ask {% data variables.copilot.copilot_chat_short %} to help you refine it. {% data variables.copilot.copilot_chat_short %} can provide you with suggestions for improving your writing, making it more engaging, or clarifying complex concepts. - -### Improving tone and style - -If you're looking to improve the tone and style of your writing, you can ask {% data variables.copilot.copilot_chat_short %} to suggest ways to make your writing more engaging or accessible. - -#### Example prompt - -`Please rewrite the conclusion in a more informal, conversational style. The original conclusion was: ‘Our team successfully launched a groundbreaking update.’ Make it feel more personal and celebratory.` - -### Including next steps - -If you're looking to include next steps in your blog post, you can ask {% data variables.copilot.copilot_chat_short %} to suggest ways to make your writing more actionable. - -#### Example prompt - -`Draft a final section on upcoming milestones and open issues labeled ‘enhancement.’ Show what's coming next, and mention opportunities for community engagement.` diff --git a/content/copilot/tutorials/copilot-cookbook/index.md b/content/copilot/tutorials/copilot-cookbook/index.md index 75e1fedb14b1..464e57f45c3f 100644 --- a/content/copilot/tutorials/copilot-cookbook/index.md +++ b/content/copilot/tutorials/copilot-cookbook/index.md @@ -25,9 +25,7 @@ children: - /analyze-functionality - /generate-code - /refactor-code - - /document-code - /testing-code - /analyze-security contentType: tutorials --- - diff --git a/content/copilot/tutorials/copilot-cookbook/refactor-code/decouple-business-logic.md b/content/copilot/tutorials/copilot-cookbook/refactor-code/decouple-business-logic.md deleted file mode 100644 index 51841f583ab7..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/refactor-code/decouple-business-logic.md +++ /dev/null @@ -1,158 +0,0 @@ ---- -title: Decoupling business logic from UI components -shortTitle: Decouple business logic -intro: '{% data variables.copilot.copilot_chat_short %} can help you separate your business logic from your user interface code, making it easier to maintain and scale your application.' -redirect_from: - - /copilot/example-prompts-for-github-copilot-chat/refactoring-code/decoupling-business-logic-from-ui-components - - /copilot/copilot-chat-cookbook/refactoring-code/decoupling-business-logic-from-ui-components - - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/decoupling-business-logic-from-ui-components - - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/decouple-business-logic - - /copilot/tutorials/copilot-chat-cookbook/refactor-code/decouple-business-logic -versions: - feature: copilot -category: - - Refactoring code - - Author and optimize with Copilot - - Improve quality and maintainability -surface: - - Chat -octicon: rocket -contentType: tutorials ---- - -In many front-end frameworks, business logic can become embedded within user interface (UI) components, making the code hard to maintain or extend, especially as the application grows. - -{% data variables.copilot.copilot_chat_short %} can help you refactor your code to extract business logic into separate services or state management solutions. This allows the business logic to be reused across different UI components. It also makes the code easier to scale by separating concerns and reducing interdependencies, and it simplifies unit testing by allowing business logic to be tested independently from UI components. - -## Example scenario - -In this JavaScript code, the `Counter` component configures the business logic for the component and also defines UI code for using the component in a web page. - -```javascript id=counter-component -import React, { useState } from 'react'; - -const Counter = () => { - const [count, setCount] = useState(0); - - const increment = () => { - if (count >= 10) { - alert('Count cannot exceed 10'); - return; - } - setCount(count + 1); - }; - - return ( -
-

Count: {count}

- -
- ); -}; - -export default Counter; -``` - -## Example prompt - -```copilot copy prompt ref=counter-component -Use Redux to separate the UI code from the Counter component in this code. -``` - -## Example response - -{% data variables.product.prodname_copilot_short %} provides step-by-step instructions for refactoring the code. - -The suggested changes refactor the `Counter` component to use Redux for state management. This includes setting up a Redux store with an initial state and a reducer, defining an increment action, and modifying the `Counter` component to connect to the Redux store. Finally, the application is wrapped with a `Provider` component to make the Redux store available to the `Counter` component. This separates the UI logic from state management. - -The proposed changes separate the code into five separate files. - -> [!NOTE] {% data variables.copilot.copilot_chat_short %} responses are non-deterministic, so you may get a different response from the one described here. - -### actions.js - -```javascript -export const increment = () => ({ - type: 'INCREMENT' -}); -``` - -### reducer.js - -```javascript -const initialState = { - count: 0 -}; - -const counterReducer = (state = initialState, action) => { - switch (action.type) { - case 'INCREMENT': - if (state.count >= 10) { - alert('Count cannot exceed 10'); - return state; - } - return { - ...state, - count: state.count + 1 - }; - default: - return state; - } -}; - -export default counterReducer; -``` - -### store.js - -```javascript -import { createStore } from 'redux'; -import counterReducer from './reducer'; - -const store = createStore(counterReducer); - -export default store; -``` - -### counter.js - -```javascript -import React from 'react'; -import { useSelector, useDispatch } from 'react-redux'; -import { increment } from './actions'; - -const Counter = () => { - const count = useSelector(state => state.count); - const dispatch = useDispatch(); - - return ( -
-

Count: {count}

- -
- ); -}; - -export default Counter; -``` - -### index.js - -```javascript -import React from 'react'; -import ReactDOM from 'react-dom'; -import { Provider } from 'react-redux'; -import store from './store'; -import Counter from './counter'; - -ReactDOM.render( - - - , - document.getElementById('root') -); -``` - -## Further reading - -{% data reusables.copilot.example-prompts.further-reading-items %} diff --git a/content/copilot/tutorials/copilot-cookbook/refactor-code/fix-lint-errors.md b/content/copilot/tutorials/copilot-cookbook/refactor-code/fix-lint-errors.md deleted file mode 100644 index 68dfe4943c08..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/refactor-code/fix-lint-errors.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Fixing lint errors -shortTitle: Fix lint errors -intro: '{% data variables.copilot.copilot_chat_short %} can suggest ways to fix issues identified by a code linter.' -redirect_from: - - /copilot/example-prompts-for-github-copilot-chat/refactoring-code/fixing-lint-errors - - /copilot/copilot-chat-cookbook/refactoring-code/fixing-lint-errors - - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/fixing-lint-errors - - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/fix-lint-errors - - /copilot/tutorials/copilot-chat-cookbook/refactor-code/fix-lint-errors -versions: - feature: copilot -category: - - Refactoring code - - Author and optimize with Copilot - - Improve quality and maintainability -surface: - - Chat -octicon: rocket -contentType: tutorials ---- - -It's good practice to use a linter to check your code for potential errors, style violations, or deviations from best practices. Linters can help you to catch bugs early, improve the readability of your code, and ensure that your code is consistent and maintainable. - -## Example scenario - -You have run a linter on your code and it has identified some issues that need to be fixed. Rather than fixing these manually, you can ask {% data variables.copilot.copilot_chat_short %} to fix them for you. - -## Example prompts - -* Select all of the code in the editor, then type: - - ```copilot copy - Fix the lint errors - ``` - -* You can specify a particular set of coding guidelines for a language, such as PEP8 for Python: - - ```copilot copy - Use PEP8 to fix the lint errors - ``` - -* If you have a local file that defines your coding conventions and rules, you can drag the file into the chat window to add it as an attachment, then type: - - ```copilot copy - Use the attached style guide to fix the lint errors - ``` - -* Alternatively, you can ask {% data variables.copilot.copilot_chat_short %} to fix only a specific type of lint error: - - ```copilot copy - Make sure all functions use snake_case naming style - ``` - -## Example response - -{% data variables.product.prodname_copilot_short %} tells you what needs to be changed, and then gives you the corrected code. You should review the suggested code thoroughly before using it. The code that {% data variables.product.prodname_copilot_short %} suggests may not fix all of the issues identified by your linter, so you should always run the linter again if you choose to use the suggested code. - -Linting issues that {% data variables.product.prodname_copilot_short %} can help you fix include: - -* Adding necessary imports that are missing. -* Removing imports that are not used in the code. -* Splitting import statements into separate lines. -* Using method and function names that follow style guidelines. -* Adding spaces around operators. -* Ensuring consistent indentation. -* Removing trailing whitespace. -* Splitting multiple statements that are on a single line into separate lines. -* Breaking long line into multiple lines. -* Removing unused variables. -* Adding or removing blank lines to adhere to style guidelines. -* Adding docstrings to functions, classes, and modules. -* Removing code that will never be executed. -* Ensuring that all return statements in a function either return a value or none. -* Reducing or eliminating the use of global variables. -* Ensuring that functions are called with the correct number and type of arguments. -* Ensuring that comments are placed correctly and are meaningful. -* Replacing print statements with proper logging. - -## Further reading - -{% data reusables.copilot.example-prompts.further-reading-items %} diff --git a/content/copilot/tutorials/copilot-cookbook/refactor-code/improve-code-readability.md b/content/copilot/tutorials/copilot-cookbook/refactor-code/improve-code-readability.md index 369c4bd3f406..08ca4b3de46f 100644 --- a/content/copilot/tutorials/copilot-cookbook/refactor-code/improve-code-readability.md +++ b/content/copilot/tutorials/copilot-cookbook/refactor-code/improve-code-readability.md @@ -27,8 +27,6 @@ Code with poor readability is difficult for other developers to maintain and ext * [Reducing nested logic](#reducing-nested-logic) * [Splitting large methods into smaller, more readable ones](#splitting-up-large-methods) -Documenting your code is another way to improve the maintainability of your code. For information about using {% data variables.copilot.copilot_chat_short %} to help you add useful comments to your code, see the example prompts in [Documenting code](/copilot/tutorials/copilot-cookbook/document-code). - > [!NOTE] The responses shown in this article are examples. {% data variables.copilot.copilot_chat_short %} responses are non-deterministic, so you may get different responses from the ones shown here. ## Improving variable names diff --git a/content/copilot/tutorials/copilot-cookbook/refactor-code/index.md b/content/copilot/tutorials/copilot-cookbook/refactor-code/index.md index 51024a58008b..f13fec670871 100644 --- a/content/copilot/tutorials/copilot-cookbook/refactor-code/index.md +++ b/content/copilot/tutorials/copilot-cookbook/refactor-code/index.md @@ -6,20 +6,20 @@ redirect_from: - /copilot/copilot-chat-cookbook/refactoring-code - /copilot/tutorials/copilot-chat-cookbook/refactoring-code - /copilot/tutorials/copilot-chat-cookbook/refactor-code + - /copilot/tutorials/refactor-code + - /copilot/using-github-copilot/example-use-cases/refactoring-code-with-github-copilot + - /copilot/using-github-copilot/guides-on-using-github-copilot/refactoring-code-with-github-copilot + - /copilot/tutorials/refactoring-code-with-github-copilot versions: feature: copilot children: - /improve-code-readability - - /fix-lint-errors - /refactor-for-optimization - - /refactor-for-sustainability - /refactor-design-patterns - /refactor-data-access-layers - - /decouple-business-logic - /handle-cross-cutting - /simplify-inheritance-hierarchies - /fix-database-deadlocks - /translate-code contentType: tutorials --- - diff --git a/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-design-patterns.md b/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-design-patterns.md index 77fc180549ce..00d209238bbf 100644 --- a/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-design-patterns.md +++ b/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-design-patterns.md @@ -8,6 +8,12 @@ redirect_from: - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/refactoring-to-implement-a-design-pattern - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/refactor-design-patterns - /copilot/tutorials/copilot-chat-cookbook/refactor-code/refactor-design-patterns + - /copilot/tutorials/copilot-cookbook/refactor-code/decouple-business-logic + - /copilot/example-prompts-for-github-copilot-chat/refactoring-code/decoupling-business-logic-from-ui-components + - /copilot/copilot-chat-cookbook/refactoring-code/decoupling-business-logic-from-ui-components + - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/decoupling-business-logic-from-ui-components + - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/decouple-business-logic + - /copilot/tutorials/copilot-chat-cookbook/refactor-code/decouple-business-logic versions: feature: copilot category: diff --git a/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-optimization.md b/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-optimization.md index 0b52d65054cf..f78cd5ad804b 100644 --- a/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-optimization.md +++ b/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-optimization.md @@ -8,6 +8,8 @@ redirect_from: - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/refactoring-for-performance-optimization - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/refactor-for-optimization - /copilot/tutorials/copilot-chat-cookbook/refactor-code/refactor-for-optimization + - /copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-sustainability + - /copilot/tutorials/copilot-chat-cookbook/refactor-code/refactor-for-sustainability versions: feature: copilot category: diff --git a/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-sustainability.md b/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-sustainability.md deleted file mode 100644 index 02a9677b78fa..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-sustainability.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Refactoring for environmental sustainability -shortTitle: Refactor for sustainability -intro: '{% data variables.copilot.copilot_chat_short %} can suggest ways to make code more environmentally friendly.' -versions: - feature: copilot -category: - - Refactoring code - - Improve quality and maintainability - - Author and optimize with Copilot -surface: - - Chat -octicon: rocket -contentType: tutorials -redirect_from: - - /copilot/tutorials/copilot-chat-cookbook/refactor-code/refactor-for-sustainability ---- - -Code that is inefficient in its use of computational resources can lead to higher energy consumption, which has a negative impact on the environment. Examples of such code include algorithms with high time complexity, excessive memory usage, and unnecessary processing. - -{% data variables.copilot.copilot_chat_short %} can help identify inefficient algorithms or resource-intensive operations in your code that contribute to higher energy consumption. By suggesting more efficient alternatives, it can help reduce the environmental impact of your software. - -## Example scenario - -The following Python code reads a large text file and counts the number of lines. However, it loads the entire file into memory, which can be inefficient for large files and lead to higher energy consumption. It also manually counts the lines instead of using built-in functions. - -```python id=inefficient-code -def count_lines(filename): - with open(filename, 'r') as f: - data = f.read() - lines = data.split('\n') - count = 0 - for line in lines: - count += 1 - return count - -print(count_lines('largefile.txt')) -``` - -## Example prompt - -Here is an example prompt you can use with {% data variables.copilot.copilot_chat_short %} to refactor the above code for better environmental sustainability: - -```copilot copy prompt ref=inefficient-code -Refactor this code to improve its environmental sustainability by reducing memory usage and computational overhead. -``` - -## Example response - -> [!NOTE] {% data variables.copilot.copilot_chat_short %} responses are non-deterministic, so you may get a different response from the one shown here. - -{% data variables.product.prodname_copilot_short %} suggests using a generator expression to read the file line by line, which reduces memory usage. It also uses the built-in `sum` function to count the lines more efficiently. - -```python -def count_lines(filename): - with open(filename, 'r') as f: - return sum(1 for _ in f) # Efficiently counts lines without loading all into memory - -print(count_lines('largefile.txt')) -``` - -## Further reading - -{% data reusables.copilot.example-prompts.further-reading-items %} diff --git a/content/copilot/tutorials/copilot-cookbook/refactor-code/translate-code.md b/content/copilot/tutorials/copilot-cookbook/refactor-code/translate-code.md index a89e02439cd0..56efda2f03f0 100644 --- a/content/copilot/tutorials/copilot-cookbook/refactor-code/translate-code.md +++ b/content/copilot/tutorials/copilot-cookbook/refactor-code/translate-code.md @@ -16,6 +16,12 @@ redirect_from: - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/translating-code-to-a-different-programming-language - /copilot/tutorials/copilot-chat-cookbook/refactoring-code/translate-code - /copilot/tutorials/copilot-chat-cookbook/refactor-code/translate-code + - /copilot/tutorials/modernize-legacy-code + - /copilot/using-github-copilot/guides-on-using-github-copilot/modernizing-legacy-code-with-github-copilot + - /copilot/tutorials/modernizing-legacy-code-with-github-copilot + - /copilot/tutorials/migrate-a-project + - /copilot/using-github-copilot/guides-on-using-github-copilot/using-copilot-to-migrate-a-project + - /copilot/tutorials/using-copilot-to-migrate-a-project contentType: tutorials --- @@ -25,8 +31,6 @@ For ease of maintaining code, you might want to move code to a language that is {% data variables.product.prodname_copilot_short %} can help you translate code from one language to another. Translating a standalone file, such as a script, is straightforward. This process is described in this article. -Translating a project containing multiple files is a more complex process, and is described in [AUTOTITLE](/copilot/tutorials/migrate-a-project). - ## Example scenario The following Perl script prompts the user to enter the path to a text file. It checks what the user enters and if a text file is found at that path, it outputs a word count and character count for the contents of the file. diff --git a/content/copilot/tutorials/copilot-cookbook/testing-code/generate-unit-tests.md b/content/copilot/tutorials/copilot-cookbook/testing-code/generate-unit-tests.md index 8cf3cd633378..7c5b5dfc6919 100644 --- a/content/copilot/tutorials/copilot-cookbook/testing-code/generate-unit-tests.md +++ b/content/copilot/tutorials/copilot-cookbook/testing-code/generate-unit-tests.md @@ -6,6 +6,8 @@ redirect_from: - /copilot/example-prompts-for-github-copilot-chat/testing-code/generate-unit-tests - /copilot/copilot-chat-cookbook/testing-code/generate-unit-tests - /copilot/tutorials/copilot-chat-cookbook/testing-code/generate-unit-tests + - /copilot/tutorials/copilot-cookbook/testing-code/update-unit-tests + - /copilot/tutorials/copilot-chat-cookbook/testing-code/update-unit-tests versions: feature: copilot category: diff --git a/content/copilot/tutorials/copilot-cookbook/testing-code/index.md b/content/copilot/tutorials/copilot-cookbook/testing-code/index.md index ea48cf460929..d3e4823f4a53 100644 --- a/content/copilot/tutorials/copilot-cookbook/testing-code/index.md +++ b/content/copilot/tutorials/copilot-cookbook/testing-code/index.md @@ -11,7 +11,5 @@ children: - /generate-unit-tests - /create-mock-objects - /create-end-to-end-tests - - /update-unit-tests contentType: tutorials --- - diff --git a/content/copilot/tutorials/copilot-cookbook/testing-code/update-unit-tests.md b/content/copilot/tutorials/copilot-cookbook/testing-code/update-unit-tests.md deleted file mode 100644 index 3a523a883914..000000000000 --- a/content/copilot/tutorials/copilot-cookbook/testing-code/update-unit-tests.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Updating unit tests to match code changes -shortTitle: Update unit tests -intro: '{% data variables.copilot.copilot_chat_short %} can help with updating your tests.' -versions: - feature: copilot -category: - - Testing code - - Author and optimize with Copilot - - Improve quality and maintainability -surface: - - Chat -octicon: beaker -contentType: tutorials -redirect_from: - - /copilot/tutorials/copilot-chat-cookbook/testing-code/update-unit-tests ---- - -When you make changes to your code, it's important to update any tests to verify the new behavior and catch any bugs that the new code has introduced. {% data variables.copilot.copilot_chat_short %} can help you quickly update tests to match your code changes, ensuring your test suite stays in sync with your implementation. - -## Example scenario - -Imagine you have a Python function, `calculate_discount`, that determines the discount for a given purchase amount. In the original code, you get a 10% discount for amounts over $100. You're making changes to the logic of the function, so that only prices over $150 get a 10% discount, and there's now a 20% discount for amounts over $200. - -### Original code - -In the original code, purchase prices above $100 get a 10% discount. - -```python -def calculate_discount(amount: float) -> float: - if amount > 100: - return amount * 0.1 # 10% discount - return 0.0 -``` - -### Updated code - -In the changed code, only amounts above $150 get 10% discount, and amounts above $200 now get a 20% discount. - -```python id=calculate_discount -def calculate_discount(amount: float) -> float: - if amount > 200: - return amount * 0.2 - elif amount > 150: - return amount * 0.1 - return 0.0 -``` - -### Existing tests - -This example shows the existing tests that were written for the original code. - -```python -import unittest -from discount import calculate_discount - -class TestCalculateDiscount(unittest.TestCase): - def test_discount_above_100(self): - # $140 should get a $14 discount (10%) - self.assertAlmostEqual(calculate_discount(140), 14.0) - - def test_discount_below_100(self): - # $80 should get no discount - self.assertEqual(calculate_discount(80), 0.0) - - def test_discount_exactly_100(self): - # $100 is not above 100, so no discount - self.assertEqual(calculate_discount(100), 0.0) - -if __name__ == '__main__': - unittest.main() -``` - -## Example prompt - -You can ask {% data variables.copilot.copilot_chat_short %} to identify and update any tests affected by your logic change. - -```copilot -Given the update to the `calculate_discount` function, update the unit tests that may fail or become outdated as a result. -``` - -## Example response - -{% data reusables.copilot.example-prompts.response-is-an-example %} - -{% data variables.copilot.copilot_chat_short %} analyzes your code and existing tests, and identifies which tests will fail or are now misleading following your code change. - -For example, {% data variables.copilot.copilot_chat_short %} explains that: -* `test_discount_above_100` will now **fail** -* `test_discount_below_100` and `test_discount_exactly_100` will pass, but they are now **misleading**, since the threshold for the 10% discount is now $150, and not $100. - -In addition, {% data variables.copilot.copilot_chat_short %} identifies any **missing test coverage**, such as the new 20% discount tier for amounts over $200. - -{% data variables.copilot.copilot_chat_short %} proposes an updated set of tests. - -### Updated tests - -```python -import unittest -from discount import calculate_discount - -class TestCalculateDiscount(unittest.TestCase): - def test_discount_above_200(self): - # $250 should get a $50 discount (20%) - self.assertAlmostEqual(calculate_discount(250), 50.0) - - def test_discount_above_150(self): - # $175 should get a $17.50 discount (10%) - self.assertAlmostEqual(calculate_discount(175), 17.5) - - def test_discount_at_or_below_150(self): - # $150 is not above 150, so no discount - self.assertEqual(calculate_discount(150), 0.0) - # $80 should get no discount - self.assertEqual(calculate_discount(80), 0.0) - -if __name__ == '__main__': - unittest.main() -``` - -## Further reading - -{% data reusables.copilot.example-prompts.further-reading-items %} diff --git a/content/copilot/tutorials/customization-library/custom-instructions/concept-explainer.md b/content/copilot/tutorials/customization-library/custom-instructions/concept-explainer.md index d95f6176ae23..454ec0af4b69 100644 --- a/content/copilot/tutorials/customization-library/custom-instructions/concept-explainer.md +++ b/content/copilot/tutorials/customization-library/custom-instructions/concept-explainer.md @@ -3,6 +3,9 @@ title: Concept explainer intro: 'Instructions for breaking down complex technical concepts.' versions: feature: copilot +redirect_from: + - /copilot/tutorials/learn-a-new-language + - /copilot/tutorials/learning-a-new-programming-language-with-github-copilot category: - Custom instructions - Getting started diff --git a/content/copilot/tutorials/explore-a-codebase.md b/content/copilot/tutorials/explore-a-codebase.md index 1a76426f1a51..47a381b72157 100644 --- a/content/copilot/tutorials/explore-a-codebase.md +++ b/content/copilot/tutorials/explore-a-codebase.md @@ -7,6 +7,18 @@ versions: redirect_from: - /copilot/using-github-copilot/guides-on-using-github-copilot/using-copilot-to-explore-a-codebase - /copilot/tutorials/using-copilot-to-explore-a-codebase + - /copilot/tutorials/copilot-cookbook/document-code/explain-complex-logic + - /copilot/example-prompts-for-github-copilot-chat/documenting-code/explaining-complex-algorithms-or-logic + - /copilot/copilot-chat-cookbook/documenting-code/explaining-complex-algorithms-or-logic + - /copilot/tutorials/copilot-chat-cookbook/documenting-code/explaining-complex-algorithms-or-logic + - /copilot/tutorials/copilot-chat-cookbook/documenting-code/explain-complex-logic + - /copilot/tutorials/copilot-chat-cookbook/document-code/explain-complex-logic + - /copilot/tutorials/copilot-cookbook/document-code/explain-legacy-code + - /copilot/example-prompts-for-github-copilot-chat/documenting-code/explaining-legacy-code + - /copilot/copilot-chat-cookbook/documenting-code/explaining-legacy-code + - /copilot/tutorials/copilot-chat-cookbook/documenting-code/explaining-legacy-code + - /copilot/tutorials/copilot-chat-cookbook/documenting-code/explain-legacy-code + - /copilot/tutorials/copilot-chat-cookbook/document-code/explain-legacy-code contentType: tutorials category: - Scale institutional knowledge diff --git a/content/copilot/tutorials/index.md b/content/copilot/tutorials/index.md index 2d2804addc0b..1027a13a4a0b 100644 --- a/content/copilot/tutorials/index.md +++ b/content/copilot/tutorials/index.md @@ -12,27 +12,19 @@ children: - /customize-code-review - /use-copilot-code-review-across-the-pull-request-lifecycle - /enhance-agent-mode-with-mcp - - /compare-ai-models - /speed-up-development-work - /roll-out-at-scale - /explore-a-codebase - /explore-issues-and-discussions - /explore-pull-requests - /write-tests - - /refactor-code - /optimize-ai-usage - /optimize-chat-usage - /optimize-code-reviews - /reduce-technical-debt - /stack-ai-generated-code-in-pull-requests - /review-ai-generated-code - - /learn-a-new-language - - /modernize-legacy-code - - /modernize-java-applications - - /migrate-a-project - - /plan-a-project - /vibe-coding - - /upgrade-projects - /copilot-cli-hooks - /use-an-ai-sme - /create-an-extension diff --git a/content/copilot/tutorials/learn-a-new-language.md b/content/copilot/tutorials/learn-a-new-language.md deleted file mode 100644 index 232f02bc218f..000000000000 --- a/content/copilot/tutorials/learn-a-new-language.md +++ /dev/null @@ -1,186 +0,0 @@ ---- -title: Learning a new programming language with GitHub Copilot -shortTitle: Learn a new language -intro: '{% data variables.copilot.copilot_chat %} can help you extend your programming skills by learning how to code in a new programming language.' -versions: - feature: copilot -redirect_from: - - /copilot/tutorials/learning-a-new-programming-language-with-github-copilot -contentType: tutorials -category: - - Scale institutional knowledge - - Author and optimize with Copilot ---- - -## Introduction - -{% data variables.product.prodname_copilot %} can help you learn how to code: whether you have no prior programming experience, or when you are learning an additional programming language. This guide is all about the latter use case: you already have a good knowledge of how to code in one or more programming languages, but now you want to learn a new language. - -### Prerequisites - -This guide assumes that you know how to use {% data variables.copilot.copilot_chat_short %} and {% data variables.product.prodname_copilot_short %} inline suggestions in your IDE. See [AUTOTITLE](/copilot/how-tos/chat-with-copilot/chat-in-ide) and [AUTOTITLE](/copilot/how-tos/get-code-suggestions/get-ide-code-suggestions). - -## Start with the basics - -Use {% data variables.copilot.copilot_chat_short %} to research the basics of the new language. Find out how this language differs from the languages you already know. Ask {% data variables.product.prodname_copilot_short %} to tell you the main things you need to be aware of before you start coding in the new language. - -### Example prompts: language basics - -These are some prompts that you can use in {% data variables.copilot.copilot_chat_short %} to help you learn the basics of a new programming language. Change `NEW-LANGUAGE` to the name of the language you want to find out about. - - - -* {% prompt %}What is NEW-LANGUAGE best suited for? I am an experienced Python programmer, but I don't know anything about NEW-LANGUAGE.{% endprompt %} - -* {% prompt %}What are the main ways in which NEW-LANGUAGE differs from other languages? Explain the most essential things I need to know as an experienced programmer who wants to learn to code in NEW-LANGUAGE.{% endprompt %} - -* {% prompt %}How can I install NEW-LANGUAGE?{% endprompt %} - -* {% prompt %}How does error handling work in NEW-LANGUAGE?{% endprompt %} - -* {% prompt %}How do you manage dependencies and packages in NEW-LANGUAGE?{% endprompt %} - -* {% prompt %}What are the most essential libraries or frameworks I should know about for NEW-LANGUAGE?{% endprompt %} - -* {% prompt %}What testing frameworks does the NEW-LANGUAGE community typically use?{% endprompt %} - -* {% prompt %}What are the biggest mistakes newcomers to NEW-LANGUAGE typically make with this language?{% endprompt %} - -* {% prompt %}As an experienced programmer learning NEW-LANGUAGE, what are the things I should focus on first?{% endprompt %} - -## Use {% data variables.product.prodname_copilot_short %} as your personal trainer - -{% data variables.product.prodname_copilot %} can write code for you. You can ask it to create chunks of code, functions, or even entire programs. However, when you are learning a new language, you should avoid relying on {% data variables.product.prodname_copilot_short %} to write much of the code for you—especially if you accept the code it suggests without making sure you understand it. If you don't know the language, you won't know if the code {% data variables.product.prodname_copilot_short %} suggests is as good as it could be. Instead, you should treat {% data variables.product.prodname_copilot_short %} as your personalized training assistant. - -When you ask {% data variables.product.prodname_copilot_short %} how to code something specific in the new language, you should ask it to explain the code it suggests. If you don't completely understand the code, or {% data variables.product.prodname_copilot_short %}'s description of it, ask for a simplified explanation—or ask for more detail—until you are sure you understand the code. Always avoid using any code that you are not completely confident that you understand. - -### Example prompts: asking for an explanation - -Change `NEW-LANGUAGE` to the name of the language you want to find out about. - - - -* `Explain your previous suggestion in more detail. I am new to NEW-LANGUAGE and I don't understand the code you suggested.` - -* {% prompt %}Show me how to write the following Ruby code in NEW-LANGUAGE: `people_over_50 = people.select { |person| person.age > 50 }`. Explain each part of the NEW-LANGUAGE code that you suggest.{% endprompt %} - -* `Add comprehensive comments to this NEW-LANGUAGE file to explain what each part of the code does.` - -## Write a simple program in the new language - -To get started, write a simple program that you would be able to write easily in a language you already know. Ask {% data variables.product.prodname_copilot_short %} for help. If you prefer, you can ask {% data variables.product.prodname_copilot_short %} to write a very simple program for you, just to get you started. You can then examine the code, learn how it works, and then extend the program yourself. - -### Example prompts: writing a simple program - - - -* {% prompt %}Show me the Rust code for a simple, useful command line tool that asks for user input and returns some useful information based on what was entered.{% endprompt %} - -* `Comment the suggested code more thoroughly. I want to understand what every part of this code does.` - -* {% prompt %}Give me the code for a very small Android app written in Kotlin.{% endprompt %} - -* `Suggests ways I could enhance this app.` - -### Use comments and {% data variables.product.prodname_copilot_short %} inline suggestions - -As an alternative to asking {% data variables.copilot.copilot_chat_short %} to suggest the basic code for a new program, you can write comments in the editor and see what code {% data variables.product.prodname_copilot_short %} suggests. - -For example: - -1. In your IDE, create a file with an appropriate file name extension for the language you are using. For example, if you are learning Rust, create a file called `example.rs`. -1. Copy and paste the following comment lines. - - ```rust copy - // NEW-LANGUAGE command line program to find the day of the week for a date. - // The program does the following: - // Prompt user to input string in format YYYYMMDD - // Parse the string to check that it is a valid date. - // If it's not, print an error message and exit. - // Calculate the day of the week for the given date. - // Print the day of the week to the user. - ``` - -1. If necessary, change the comment syntax to match the language you are using. -1. Change `NEW-LANGUAGE` to the name of the language you are using. This, and the file name extension, will tell {% data variables.product.prodname_copilot_short %} which language to use. -1. Press return and tab to see and accept the inline suggestions that {% data variables.product.prodname_copilot_short %} offers. Continue accepting suggestions until you have a complete program. -1. Read through the code to see how it works. If you don't understand any part of the code, ask {% data variables.product.prodname_copilot_short %} to explain it. For example: - - 1. Select one or more lines of code that you don't understand. - 1. **In {% data variables.product.prodname_vscode_shortname %}:** - - Right-click the selected code and choose **{% data variables.product.prodname_copilot_short %}** > **Explain**. - - **In JetBrains IDEs:** - - Right-click the selected code and choose **{% data variables.product.prodname_copilot %}** > **Explain This**. - - **In {% data variables.product.prodname_vs %}:** - - Open the {% data variables.copilot.copilot_chat_short %} panel and enter the prompt `Explain this code`. - -## Ask {% data variables.product.prodname_copilot_short %} specific questions - -While you are learning a new language, you should work on small units of code that perform a specific task. Ask {% data variables.product.prodname_copilot_short %} well-defined, narrowly scoped questions to help you become familiar with the syntax and idioms of the new language. - -### Example prompts: specific questions - -Change `NEW-LANGUAGE` to the name of the language you want to find out about. - - - -* {% prompt %}Explain all of the various ways that conditionals can be coded in NEW-LANGUAGE.{% endprompt %} - -* {% prompt %}In JavaScript I'd write: `The ${numCats === 1 ? 'cat is' : 'cats are'} hungry.`. How do I write this in NEW-LANGUAGE?{% endprompt %} - -* {% prompt %}In NEW-LANGUAGE, how do I convert a string to all lowercase?{% endprompt %} - -* {% prompt %}What is the equivalent of num++ in NEW-LANGUAGE?{% endprompt %} - -* {% prompt %}How do I run a program written in the NEW-LANGUAGE programming language?{% endprompt %} - -* {% prompt %}How can I compile a single executable file for my NEW-LANGUAGE project, that I can distribute as a release?{% endprompt %} - -## Convert existing code to the new language - -One effective way of leveraging your existing programming knowledge is to take some code you are familiar with in one language, convert it to the new language, and then examine how the same operation is done in the new language. - -1. Find a self-contained piece of code. For example, a function. -1. Ask {% data variables.copilot.copilot_chat_short %} to convert it into the language you are learning. -1. Copy and paste the suggested code into a new file in your editor. -1. View the two pieces of code side by side and analyze how the same operation is done in the new language. What are the similarities and differences? -1. Get {% data variables.product.prodname_copilot_short %} to explain any of the code you don't understand. - -## Read existing code in the new language - -After you feel comfortable with the basics of the new language, spend time reading existing code written in that language. - -Find a project that uses the new language and take a look at the code. Open a file and ask {% data variables.copilot.copilot_chat_short %} for a brief overview of the purpose of the file. Then read through the code line by line. Do you understand the techniques that have been used? Do you know how the library and built-in functions work? Can you follow the data flow through the code? - -Ask {% data variables.product.prodname_copilot_short %} to explain any parts of the code that you don't understand. - -When you have finished reading through the code, ask {% data variables.product.prodname_copilot_short %} whether it can suggest any ways to improve the code. - -## Avoid assuming that {% data variables.product.prodname_copilot_short %} is always right - -{% data variables.product.prodname_copilot_short %} is a tool that can help you learn a new language, but—like all AI assistants—it is not infallible. It can make mistakes, and it can suggest code that is not optimal. - -{% data variables.product.prodname_copilot_short %} is trained on a large body of code but, for each language, the quality of suggestions you receive may depend on the volume and diversity of training data for that language. For example, JavaScript is well-represented in public repositories and {% data variables.product.prodname_copilot_short %} will therefore typically be able to provide accurate and helpful suggestions. The quality of {% data variables.product.prodname_copilot_short %}'s suggestions may be lower for languages that are less well-represented in public repositories. - -Always check the code that {% data variables.product.prodname_copilot_short %} suggests, and make sure you understand it before you use it. When you're checking code suggested by {% data variables.product.prodname_copilot_short %}, you should look for ways you could make the code more performant, simpler, or easier to maintain. - -If you think {% data variables.product.prodname_copilot_short %} has not suggested the best way of coding something you can ask it to try a different approach. - -If you run the code and it generates an error, give {% data variables.product.prodname_copilot_short %} the details of the error and ask it to fix the code. - -You should also check that {% data variables.product.prodname_copilot_short %} is following your coding style guidelines. If it is not, you can alter the repository's custom instructions to prompt {% data variables.product.prodname_copilot_short %} to adhere to your guidelines in future. See [AUTOTITLE](/copilot/how-tos/copilot-on-github/customize-copilot/add-custom-instructions/add-repository-instructions). - -### Example prompts: checking your work - - - -* `Check this code for syntax errors.` - -* `Assess whether this code is optimally performant.` - -* `Suggest alternative ways this code could have been written.` diff --git a/content/copilot/tutorials/migrate-a-project.md b/content/copilot/tutorials/migrate-a-project.md deleted file mode 100644 index 1d4f87f0b61c..000000000000 --- a/content/copilot/tutorials/migrate-a-project.md +++ /dev/null @@ -1,534 +0,0 @@ ---- -title: Using GitHub Copilot to migrate a project to another programming language -allowTitleToDifferFromFilename: true -intro: '{% data variables.copilot.copilot_chat %} can help you move a project to a different language. This guide describes what''s involved in a migration process and gives an example of a PHP to Python migration.' -versions: - feature: copilot -shortTitle: Migrate a project -redirect_from: - - /copilot/using-github-copilot/guides-on-using-github-copilot/using-copilot-to-migrate-a-project - - /copilot/tutorials/using-copilot-to-migrate-a-project -contentType: tutorials -category: - - Burn down tech debt - - Author and optimize with Copilot ---- - -## Introduction - -Migrating a project to a new programming language can be a difficult and time-consuming task. {% data variables.product.prodname_copilot %} can help you with this process by explaining the changes you need to make and suggesting replacement code in the new language. - -## Principles of migrating a project to a new language - -Consider the points before you start a migration process: - -* **Coding knowledge** - - Make sure you have a good understanding of both programming languages. Although {% data variables.product.prodname_copilot_short %} can translate code for you, you need to understand the choices it proposes and decide whether you want to use its suggestions or ask for an alternative suggestion. - -* **Knowledge of the system you are migrating** - - Make sure you understand the architecture and logic of the current system, in addition to the functionality and features it provides to users. You must be able to check that the translated code performs all of the same operations as the original code and produces the same results. - -* **Use AI to help you** - - If you don't understand a particular part of the code you are about to translate, use {% data variables.product.prodname_copilot_short %}'s "explain" feature, either on the whole file, or a selected portion of the code within a file. See [AUTOTITLE](/copilot/how-tos/chat-with-copilot/chat-in-ide). - -* **Schedule time to complete the migration** - - Conversion is a multi-stage process. The larger the project you are converting the greater the number of steps you will need to take. Make sure you allow plenty of time to complete the entire process. - -* **Work iteratively** - - Aim to convert discreet parts of your project separately. Make sure you have verified all of the changes you've made before moving on to another part of the project. Write tests for the individual parts of the project as you proceed so that you can confirm that each of the new components works as expected. - -* **Avoid introducing complexity to the process** - - Initially you should aim to do a like-for-like conversion. This won't be possible for all of the code in your project. However, to avoid adding complexity to the migration task, you should try to limit the number of new changes you introduce, other than translating the code and using a new framework and the appropriate dependencies. - -* **Benchmark and refactor the translated code** - - After you've completed the initial conversion, and you have a working system, you can perform benchmarking to compare the old and new systems. You can now refactor the code in the new language. This is an opportunity to optimize the code and reduce technical debt. - -## Using {% data variables.product.prodname_copilot_short %} to help you migrate a project to a new language - -Assuming you've already familiarized yourself with the existing project, a good way to start a migration is to open a branch of the repository in your editor and ask {% data variables.product.prodname_copilot_short %} for help. - -1. In your editor, open the {% data variables.copilot.copilot_chat_short %} panel. See [AUTOTITLE](/copilot/how-tos/chat-with-copilot/chat-in-ide). -1. Ask {% data variables.product.prodname_copilot_short %} to outline the steps you need to take to migrate the project to the new language. - - For example, for a migration from PHP to Python, you could ask: - - ```copilot copy - @workspace I want to migrate this project from PHP to Python. Give me a high-level overview of the steps I need to take. Don't go into detail at this stage. - ``` - - > [!NOTE] - > The `@workspace` chat participant sets the files in the current workspace as the context for the question you ask. - - {% data variables.product.prodname_copilot_short %} will typically come back with a list of steps that you need to take to migrate the project. - -1. Copy {% data variables.product.prodname_copilot_short %}'s response and save this somewhere to refer to throughout the process. -1. Work through each step of the process, asking for detailed help from {% data variables.product.prodname_copilot_short %} as you need it. - - Consider each suggestion from {% data variables.product.prodname_copilot_short %} carefully. Make sure you understand the code that it is suggesting and assess whether it's appropriate for your project. If you are not sure, ask {% data variables.product.prodname_copilot_short %} to explain the code to you. - - If you think a change suggested by {% data variables.product.prodname_copilot_short %} is not right in some way, ask for an alternative suggestion. - -1. As soon as you've migrated a component to a state that you can run, check that it works as expected. If it generates an error, copy the error into the {% data variables.copilot.copilot_chat_short %} view, and ask {% data variables.product.prodname_copilot_short %} to help you fix it. -1. After you've completed the initial conversion, use {% data variables.product.prodname_copilot_short %} to help you refactor the code in the new language. For more information, see [AUTOTITLE](/copilot/tutorials/refactor-code). - -## Example: migrating a PHP project to Python - -The following example describes the migration of a simple web application from PHP to Python. Even if these are not the programming languages you are using for your migration, you may find it helpful to follow along with the steps described here to familiarize yourself with a project migration. The steps will be similar for migrating other small projects from one language to another. - -![Screenshot of the 'Simple PHP Website' prior to migration from PHP to Python.](/assets/images/help/copilot/migration-original-website.png) - -This example assumes: -* You are working in {% data variables.product.prodname_vscode %}. -* You have both languages installed: PHP and Python version 3.12 or later. - -### Migrating a simple website project - -We are going to migrate the code in this public repository on {% data variables.product.github %}: [docs/simple-php-website](https://github.com/docs/simple-php-website). - -The repository consists of the following files. - -```text -.gitignore -.htaccess -LICENSE -content -├── 404.phtml -├── about-us.phtml -├── contact.phtml -├── home.phtml -└── products.phtml -includes -├── config.php -└── functions.php -index.php -readme.md -template -├── style.css -└── template.php -``` - -This example gives the prompts you can enter into {% data variables.copilot.copilot_chat_short %} to complete the migration, and the responses {% data variables.product.prodname_copilot_short %} returned for one instance of this migration. The {% data variables.copilot.copilot_gpt_41 %} model was used to generate these responses. {% data variables.copilot.copilot_chat_short %} responses are non-deterministic, so you will probably get slightly different responses to the ones shown here. - -During a migration process you are likely to get errors that you need to fix before moving ahead. {% data variables.product.prodname_copilot_short %} can help you with this. The example includes some errors and shows how you can get {% data variables.product.prodname_copilot_short %} to help you fix them. - -Because the responses you'll get from {% data variables.copilot.copilot_chat_short %} are likely to be different to those shown here, you may encounter different errors. You may, therefore, find it easier to step through this example migration using the responses shown here, rather than those you get from {% data variables.product.prodname_copilot_short %} yourself. - -After completing this example migration you can then use the same methodology on your own project. - -1. Start by cloning a copy of the repository to your local machine. -1. Run the application to check it works. - - To do this, in a terminal, navigate to the root of the cloned repository and run the following command: - - ```shell copy - php -S localhost:8000 - ``` - - Then in a browser, go to: http://localhost:8000. -1. Click around the website, to get to know it, so that you'll be able to verify that the migration has been successful. -1. Create a working branch in your repository and open it as a new workspace in {% data variables.product.prodname_vscode %}. -1. Familiarize yourself with the contents and architecture of the existing project. {% data variables.product.prodname_copilot_short %} can help you with this: - - 1. Open the {% data variables.copilot.copilot_chat_short %} view. - 1. Enter a prompt such as: - - ```copilot copy - @workspace Describe this project in detail, explaining what the various components do and how they interact. - ``` - -1. Ask {% data variables.product.prodname_copilot_short %} for a high-level overview of the migration process: - - ```copilot copy - @workspace I want to migrate this project from PHP to Python. Give me a high-level overview of the steps I need to take. Don't go into detail at this stage. - ``` - - {% data variables.product.prodname_copilot_short %} will reply with instructions such as: - - ```text - To migrate this project from PHP to Python, follow these high-level steps: - - 1. Set Up Python Environment: - - Install Python and set up a virtual environment. - - Install necessary packages (e.g., Flask for web framework). - - 2. Convert Configuration: - - Translate the configuration settings from config.php to a Python configuration file. - - 3. Rewrite Functions: - - Convert PHP functions in functions.php to Python functions. - - 4. Create Flask Application: - - Set up a Flask application to handle routing and views. - - Map the routes to corresponding views. - - 5. Convert Templates: - - Translate template.php to a Jinja2 template. - - Update the CSS file path in the template. - - 6. Convert Content Pages: - - Convert .phtml content files to HTML or Jinja2 templates. - - 7. Update .htaccess Rules: - - Translate .htaccess rewrite rules to Flask route handling. - - 8. Run and Test: - - Run the Flask application and test all routes and functionalities. - - Ensure the site works as expected and fix any issues. - - 9. Documentation: - - Update the readme.md with new instructions for running the Python project. - ``` - -1. Copy {% data variables.product.prodname_copilot_short %}'s response and save this somewhere to refer to throughout the remainder of this process. You'll work through each of these steps, asking {% data variables.product.prodname_copilot_short %} for help as you proceed. - -1. If you haven't already decided which Python framework you want to use, you can ask {% data variables.product.prodname_copilot_short %} for advice: - - ```copilot copy - @workspace What Python frameworks can I use for this project once it is migrated to Python? Give me a selection of options, with a brief summary of the pros and cons of each in relation to this website project. Which framework would you recommend? - ``` - - {% data variables.product.prodname_copilot_short %} replies with information about various frameworks, and concludes: - - ```text - For a project like yours - which is a simple, content-driven website - Flask is highly recommended. Its simplicity, flexibility, and ease of use (especially with its templating system that can easily replace your current PHP template structure) make it a great fit. - ``` - - We'll take {% data variables.product.prodname_copilot_short %}'s advice and use Flask. - -1. Returning to {% data variables.product.prodname_copilot_short %}'s high-level overview, the first step is to set up a Python environment and install the necessary packages. To find out how to do this, in {% data variables.copilot.copilot_chat_short %}, enter: - - ```copilot copy - @workspace I want to use Flask. Tell me how to set up a virtual environment and install the necessary packages. - ``` - - {% data variables.product.prodname_copilot_short %} will reply with instructions such as: - - ```text - 1. Create a virtual environment: - - Open a terminal and navigate to your project directory. - - Run the following command to create a virtual environment: - python3 -m venv venv - - 2. Activate the virtual environment: - - On macOS and Linux: - source venv/bin/activate - - - On Windows: - venv\Scripts\activate - - 3. Install Flask and necessary packages: - - With the virtual environment activated, run the following command - to install Flask and other necessary packages: - pip install Flask - - 4. Verify the installation: - - You can verify that Flask is installed by running: - pip list - ``` - -1. Follow {% data variables.product.prodname_copilot_short %}'s instructions and use `pip list` to verify that Flask is installed. -1. Returning to {% data variables.product.prodname_copilot_short %}'s overview for the migration process, the next step is to convert the configuration. Ask {% data variables.product.prodname_copilot_short %} for help with this. For example: - - ```copilot copy - @workspace As the first step in migrating this project from PHP to Python, create a Python configuration file by converting the functions in functions.php to Python functions. Tell me where to locate the Python config file in the project. - ``` - - {% data variables.product.prodname_copilot_short %} suggests that you create a file called `config.py` in the `includes` directory, containing the following code. - - ```python copy - config = { - 'name': 'Simple Python Website', - 'site_url': '', - 'pretty_uri': False, - 'nav_menu': { - '': 'Home', - 'about-us': 'About Us', - 'products': 'Products', - 'contact': 'Contact', - }, - 'template_path': 'template', - 'content_path': 'content', - 'version': 'v3.1', - } - - def get_config(key=''): - return config.get(key, None) - - def site_name(): - return get_config('name') - - def site_url(): - return get_config('site_url') - - def site_version(): - return get_config('version') - - def nav_menu(sep=' | '): - nav_menu = '' - nav_items = get_config('nav_menu') - - for uri, name in nav_items.items(): - query_string = request.args.get('page', '') - class_active = ' active' if query_string == uri else '' - url = f"{get_config('site_url')}/{'' if get_config('pretty_uri') or uri == '' else '?page='}{uri}" - - nav_menu += f'{name}{sep}' - - return nav_menu.strip(sep) - - def page_title(): - page = request.args.get('page', 'Home') - return ' '.join(word.capitalize() for word in page.split('-')) - - def page_content(): - page = request.args.get('page', 'home') - path = os.path.join(os.getcwd(), get_config('content_path'), f'{page}.phtml') - - if not os.path.exists(path): - path = os.path.join(os.getcwd(), get_config('content_path'), '404.phtml') - - with open(path, 'r') as file: - return file.read() - - def init(): - template_path = os.path.join(get_config('template_path'), 'template.html') - with open(template_path, 'r') as file: - return file.read() - ``` - -1. Create the `includes/config.py` file and delete the existing `includes/config.php` file. -1. Returning to the overview again, ask {% data variables.product.prodname_copilot_short %} to help you rewrite the PHP functions. - - ```copilot copy - @workspace Continuing the migration of this project from PHP to Python, create Python functions to replace the existing PHP functions. Tell me where to locate the Python functions in the project. - ``` - - {% data variables.product.prodname_copilot_short %} suggests you create a file called `functions.py` in the `includes` directory, containing the following code. - - ```python copy - import os - from flask import request - from .config import get_config - - def site_name(): - return get_config('name') - - def site_url(): - return get_config('site_url') - - def site_version(): - return get_config('version') - - def nav_menu(sep=' | '): - nav_menu = '' - nav_items = get_config('nav_menu') - - for uri, name in nav_items.items(): - query_string = request.args.get('page', '') - class_active = ' active' if query_string == uri else '' - url = f"{get_config('site_url')}/{'' if get_config('pretty_uri') or uri == '' else '?page='}{uri}" - - nav_menu += f'{name}{sep}' - - return nav_menu.strip(sep) - - def page_title(): - page = request.args.get('page', 'Home') - return ' '.join(word.capitalize() for word in page.split('-')) - - def page_content(): - page = request.args.get('page', 'home') - path = os.path.join(os.getcwd(), get_config('content_path'), f'{page}.phtml') - - if not os.path.exists(path): - path = os.path.join(os.getcwd(), get_config('content_path'), '404.phtml') - - with open(path, 'r') as file: - return file.read() - - def init(): - template_path = os.path.join(get_config('template_path'), 'template.html') - with open(template_path, 'r') as file: - return file.read() - ``` - -1. Create the `includes/functions.py` file and delete the existing `includes/functions.php` file. -1. Continuing with the overview, the next step is to create a Flask application. Ask {% data variables.product.prodname_copilot_short %} to help you with this: - - ```copilot copy - @workspace Set up a Flask application to handle routing and views, and map the routes to corresponding views. Tell me the location of any files that need to be created or changed. - ``` - - {% data variables.product.prodname_copilot_short %} suggests you create a file called `app.py` in the root of the project, containing the following code. - - ```python copy - from flask import Flask, render_template, request - import os - - app = Flask(__name__) - - config = { - 'name': 'Simple Python Website', - 'site_url': '', - 'pretty_uri': False, - 'nav_menu': { - '': 'Home', - 'about-us': 'About Us', - 'products': 'Products', - 'contact': 'Contact', - }, - 'template_path': 'template', - 'content_path': 'content', - 'version': 'v3.1', - } - - def get_config(key=''): - return config.get(key, None) - - @app.route('/') - @app.route('/') - def index(page='home'): - page_content = get_page_content(page) - page_title = get_page_title(page) - nav_menu = get_nav_menu() - return render_template('template.html', page_title=page_title, page_content=page_content, nav_menu=nav_menu) - - def get_page_title(page): - return ' '.join(word.capitalize() for word in page.split('-')) - - def get_page_content(page): - path = os.path.join(os.getcwd(), get_config('content_path'), f'{page}.phtml') - if not os.path.exists(path): - path = os.path.join(os.getcwd(), get_config('content_path'), '404.phtml') - with open(path, 'r') as file: - return file.read() - - def get_nav_menu(sep=' | '): - nav_menu = '' - nav_items = get_config('nav_menu') - for uri, name in nav_items.items(): - query_string = request.args.get('page', '') - class_active = ' active' if query_string == uri else '' - url = f"{get_config('site_url')}/{'' if get_config('pretty_uri') or uri == '' else '?page='}{uri}" - nav_menu += f'{name}{sep}' - return nav_menu.strip(sep) - - if __name__ == '__main__': - app.run(debug=True) - ``` - - {% data variables.product.prodname_copilot_short %} also suggests renaming `template/template.php` to `template/template.html` and updating the file to use Jinja2 templating syntax: - - ```html copy - {% raw %} - - - - - - - {{ page_title }} | {{ get_config('name') }} - - - -
- -
-

{{ get_config('name') }}

- -
- -
-

{{ page_title }}

- {{ page_content|safe }} -
- -
- ©{{ get_config('version') }} {{ get_config('name') }}.
{{ get_config('version') }}
-
- -
- - - {% endraw %} - ``` - -1. Create the `app.py` and `template/template.html` files as suggested. -1. {% data variables.product.prodname_copilot_short %} may also suggest that, having created these files, you now run `python app.py` in the terminal, from the root of the repository, and then browse to [http://127.0.0.1:5000](http://127.0.0.1:5000). - - > [!NOTE] - > Depending on how Python is installed on your computer, you may need to use the command `python3 app.py` instead of `python app.py` to ensure the correct version of Python is used. - - When you do this you will see error messages in the browser. - -1. Copy the initial `TemplateNotFound` error message to the {% data variables.copilot.copilot_chat_short %} view and ask how you can fix this. For example: - - ```copilot copy - @workspace When I run `python3 app.py`, I get the following error in the browser: `jinja2.exceptions.TemplateNotFound: template.html`. How can I fix this? - ``` - - {% data variables.product.prodname_copilot_short %} replies that the error indicates that Flask is unable to locate the `template.html` file. - - It tells you that, by default, Flask looks for templates in a folder named `templates` in the root directory of your project. However, your `template.html` file is located in the `template` directory. To fix this, you need to specify the correct template folder when creating the Flask app. It advises you to update your `app.py` file, changing the assignment `app = Flask(__name__)` to include the `template_folder` parameter: - - ```python copy - app = Flask(__name__, template_folder='template') - ``` - -1. Assuming the Flask development server is still running, if you refresh the browser page at [http://127.0.0.1:5000/](http://127.0.0.1:5000/), you will now see a new error relating to the `get_config` function. - - Copy this error message to the {% data variables.copilot.copilot_chat_short %} view and ask for help. - - ```copilot copy - @workspace When I run `python3 app.py`, I get the following error in the browser: `jinja2.exceptions.UndefinedError: 'get_config' is undefined.` How can I fix this? - ``` - - {% data variables.product.prodname_copilot_short %} replies that the error occurs because `get_config` is not available in the Jinja2 template context. It advises you to add the following code to the `app.py` file, directly before the line `@app.route('/')`: - - ```python copy - app.jinja_env.globals.update(get_config=get_config) - ``` - -1. Refresh your browser and you should now see the website. - - ![Screenshot of the 'Simple Python Website' without CSS styling.](/assets/images/help/copilot/migration-no-css-website.png) - - However, none of the CSS styles are being applied. We'll fix this next. - -1. Ask {% data variables.product.prodname_copilot_short %}: - - ```copilot copy - @workspace The deployed website does not use the CSS styles. How can I fix this? - ``` - - {% data variables.product.prodname_copilot_short %} tells you that Flask expects your CSS file to be in a directory called `static`. It suggests moving the existing `style.css` file from the `template` directory into a new `static` directory, and then updating the path to the `style.css` file within the `head` portion of the `template.html` file. Change this to: - - ```html copy - {% raw %} - - {% endraw %} - ``` - - When you refresh the browser, the website should now render correctly. - - To complete the initial migration, continue working through the steps in the high-level overview that {% data variables.product.prodname_copilot_short %} gave you, asking for help as you need it. - -### Completing the migration - -Further work to successfully complete the migration process would involve: - -* **Checking** the initial migration thoroughly. -* **Bug fixing**. For example, at present in the example described here, the page links only work if you set `pretty_uri` to `True` in the `config` section of the `app.py` file. If you want the option of using query string parameters in the page URLs, or if you want to remove this option from the code, you can ask {% data variables.product.prodname_copilot_short %} to help you do this. -* **Writing tests** for the migrated project. -* **Cleaning up** the project by removing any files that are no longer needed. -* **Refactoring** the code in the new language. The migration process has resulted in a Python project whose architecture is based on that of the original PHP project. Having done the initial migration, you can now refactor the code to make best use of features of the Python language and the Flask framework. -* **Updating the documentation**. The `readme.md` file is now out of date and needs to be rewritten. diff --git a/content/copilot/tutorials/modernize-java-applications.md b/content/copilot/tutorials/modernize-java-applications.md deleted file mode 100644 index 74592eb8a9fa..000000000000 --- a/content/copilot/tutorials/modernize-java-applications.md +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: Modernizing Java applications with GitHub Copilot -shortTitle: Modernize Java applications -intro: '{% data variables.product.prodname_copilot %} can help modernize and migrate Java applications by assessing your codebase, identifying upgrade paths, and automating remediation and containerization tasks.' -versions: - feature: copilot -contentType: tutorials -category: - - Modernize applications - - Author and optimize with Copilot ---- - - - - - -The {% data variables.product.prodname_copilot %} app modernization extension in {% data variables.product.prodname_vscode %} automates Java upgrades by identifying outdated frameworks, deprecated APIs, and upgrade blockers. {% data variables.copilot.copilot_cloud_agent %} applies code changes, updates build files, and resolves build and CVE issues for you. - -The recommendations and reporting produced by the extension can help your teams adopt new technologies quickly and reduce technical debt. {% data variables.product.prodname_copilot_short %} guides you through upgrades with actionable steps and summaries, accelerating and securing your migrations while reducing manual effort. - -For extension capabilities, setup, and user interface instructions, see [The GitHub Copilot app modernization documentation](https://learn.microsoft.com/en-us/azure/developer/github-copilot-app-modernization/) in the Microsoft documentation. - -## Modernization framework - -When you start an agent session using the [Java upgrade extension](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-upgrade), the extension will help you modernize your Java application using the following framework. - -* **Perform assessment tasks**. The extension can analyze code, configuration, and dependencies, providing an assessment of your application's current state. -* **Create a customizable modernization plan**. Based on the assessment, the extension can suggest a modernization path, including necessary framework and library updates. -* **Early identification of issues**. The extension identifies dependencies, outdated libraries and language features, and potential migration issues. The extension provides actionable strategies to remediate problems. -* **Customize your plan**. Edit the modernization plan to your application's specific needs, such as incorporating organizational standards and practices, excluding certain components, or prioritizing specific features or design patterns. -* **Implement your plan**. The extension can assist in applying code changes, updating build files, refactoring deprecated APIs, and resolving build and syntax issues. The extension will automatically fix build errors and perform test validations after each step to ensure stability and error-free changes. -* **Review your changes**. The extension can produce a detailed upgrade report, summarizing the changes applied, and listing any unaddressed issues and remaining steps for your modernization. -* **Generate unit tests**. The extension automatically evaluates existing tests, and generates new test files and adds them to the workspace. A report is produced summarizing the pre- and post-generation test results. -* **Containerize your application**. The extension can automatically generate Dockerfiles, build images, and validate everything for your modernized application to run within the container services such as Azure Kubernetes Service (AKS), Azure Container Apps (ACA), and AKS Automatic, enabling easier deployment and scalability. -* **Prepare for deployment**. The extension can help you prepare your application for containerization and deployment, by generating deployment artifacts such as scripts and configurations. -* **Automate deployment to Azure**. The extension can help you deploy or provision your modernized application to Azure, generating necessary artifacts and Azure resources, and performing execution steps. - -You can improve your team's understanding of the application codebase, and save time and effort by using {% data variables.product.prodname_copilot_short %} to help with complex modernization tasks such as: - -* Reverse engineering and code transformation -* Vulnerability and dependency analysis, and code behavior checks and remediation -* Automated generation of assets, documentation, and upgrade reports -* Test generation and evaluation -* Deployment automation - -## Modernization workflow overview - -In this example, we'll walk through the high-level steps to modernize a Java application using the {% data variables.product.prodname_copilot %} app modernization extension in {% data variables.product.prodname_vscode %}. - -For detailed prerequisites and instructions, see [Quickstart: upgrade a Java project with {% data variables.product.prodname_copilot %} app modernization](https://learn.microsoft.com/en-us/java/upgrade/quickstart-upgrade) in the Microsoft documentation. - -> [!NOTE] -> During the modernization workflow, you may frequently be prompted by {% data variables.copilot.copilot_cloud_agent %} for confirmation before it performs specific actions. - -### 1. Open your Java project - -Use {% data variables.product.prodname_vscode_shortname %} to open your project folder. - -#### Suggested actions - -* Ensure your project builds successfully before proceeding. -* If you encounter build issues, you can use {% data variables.product.prodname_copilot_short %} to help resolve them before starting the modernization process. - -### 2. Start a modernization workspace - -Launch {% data variables.copilot.copilot_chat_short %} and start a new session in agent mode. Choose **{% data variables.product.prodname_copilot %} app modernization – upgrade for Java** from the available tools. - -### 3. Analyze your project for upgrade opportunities - -{% data variables.product.prodname_copilot_short %} will scan your codebase. The analysis includes: - -* Detection of outdated frameworks (for example, Spring Boot, Jakarta EE, Java SE versions). -* Identification of deprecated APIs and obsolete patterns. -* Suggestions for upgrade opportunities. - -You can review the findings and a structured upgrade plan in the editor, which will display: - -* Current and recommended versions for frameworks and dependencies. -* Code locations requiring migration or refactoring. -* Upgrade blockers or incompatible dependencies. - -#### Suggested actions - -* Review and customize the modernization plan before proceeding with the upgrade. - -### 4. Apply {% data variables.product.prodname_copilot_short %} upgrade recommendations - -Use {% data variables.product.prodname_copilot_short %} to apply or review code changes, update build files, and refactor APIs. - -If build errors are found, {% data variables.product.prodname_copilot_short %} can enter a fix-and-test loop until the project compiles cleanly. - -{% data variables.copilot.copilot_cloud_agent %} automated changes can include: - -* Updating `pom.xml` or `build.gradle` files for new dependency versions. -* Generating pull requests or committing changes directly. -* Refactoring code for API changes. For example, migrating from `javax.*` to `jakarta.*` namespaces. -* Suggesting or applying code transformations to address breaking changes. - -{% data variables.product.prodname_copilot_short %} will iterate and continue to fix errors until the project builds successfully and there are no more issues that require fixing. It's possible that minor issues that don't require immediate fixes may remain. These will not prevent the upgrade from completing. - -#### Suggested actions - -* Review all code changes in your diff editor before accepting. -* Use {% data variables.product.prodname_copilot_short %} to further explain and document code changes. -* When the extension prompts you to, accept the options to check modified dependencies for known CVEs, and to validate code behavior for consistency. -* Review any issues remaining and evaluate their importance. - -### 5. View the upgrade report and suggested next steps - -After the upgrade process is complete, {% data variables.product.prodname_copilot_short %} will generate a summary upgrade report that includes: - -* Project information. -* Lines of code changed. -* Updated dependencies. -* Summarized code changes. -* Fixed CVE security and code inconsistency issues, if any. -* Unaddressed minor CVE issues. - -#### Suggested actions - -* Review the report to understand the changes made. -* Follow any suggested next steps to finalize your modernization. - -### Completing the modernization - -Further work to support your modernization may include: - -* **Checking** the initial modernization and code changes thoroughly. Ensure your company's coding standards and best practices are met. -* **Reviewing** modified code closely. For example, check that the generated code fits the purpose and architecture of your project. For more suggestions, see [AUTOTITLE](/copilot/tutorials/review-ai-generated-code). -* **Bug fixing**. Check specific content for subtle errors, and use your own debugging and linting tools to evaluate new content. -* **Writing tests** and identifying gaps in testing for the upgraded project. -* **Cleaning up** the project by removing any files that are no longer needed. -* **Refactoring** the code in the new language. The modernization process may have resulted in a project whose architecture was based on that of your original project, but that is no longer the ideal or optimum solution for your needs. You may now want to refactor the code to make best use of features of the language and the framework used. -* **Updating documentation**. Your project information and contributing files may now be out of date and need to be rewritten. -* **Containerization**. Update your application code, generate containerization files like Dockerfiles, and build the image to test the validity. If needed, {% data variables.product.prodname_copilot_short %} can perform these containerization tasks, and also create a comprehensive plan detailing the next steps. -* **Deploying** the modernized application to your target environments, including cloud platforms such as Microsoft Azure. - - diff --git a/content/copilot/tutorials/modernize-legacy-code.md b/content/copilot/tutorials/modernize-legacy-code.md deleted file mode 100644 index 64427d4e16fb..000000000000 --- a/content/copilot/tutorials/modernize-legacy-code.md +++ /dev/null @@ -1,422 +0,0 @@ ---- -title: Modernizing legacy code with GitHub Copilot -shortTitle: Modernize legacy code -intro: '{% data variables.copilot.copilot_chat_short %} helps modernize legacy code by suggesting refactors and creating tests to catch potential issues.' -versions: - feature: copilot -redirect_from: - - /copilot/using-github-copilot/guides-on-using-github-copilot/modernizing-legacy-code-with-github-copilot - - /copilot/tutorials/modernizing-legacy-code-with-github-copilot -contentType: tutorials -category: - - Modernize applications - - Author and optimize with Copilot ---- - -> [!NOTE] The responses shown in this article are examples. {% data variables.copilot.copilot_chat_short %} responses are non-deterministic, so you may get different responses from the ones shown here. - -Legacy code is code that is old, outdated, or no longer supported by the original developers. It can be difficult to maintain and extend because it may not follow modern best practices, such as using consistent naming conventions or writing clear documentation. - -Modernizing legacy code can help you: - -* Improve performance and scalability. -* Make the code easier to maintain and extend. -* Reduce the risk of introducing bugs when making changes. -* Make the code easier to test. - -{% data variables.product.prodname_copilot_short %} can help you modernize your legacy code by: - -* **Providing suggestions** for refactoring the code to follow modern best practices. -* **Generating documentation** to help you understand how the code works. -* **Generating tests** to help you verify that your changes haven't introduced bugs. - -## Example scenario - -In this example, we’ll be looking at an account management system written in COBOL and modernizing it into Node.js. You can find the COBOL code in the [`modernize-legacy-cobol-app` repository](https://github.com/continuous-copilot/modernize-legacy-cobol-app). - -The account management system consists of three key files: - -* `main.cob`: The main program that reads input from the user and calls the appropriate subprogram. -* `operations.cob`: A subprogram that performs operations on the account data, such as credit, debit, and view balance. -* `data.cob`: A subprogram that manages the storage of the account balance. - -## Step 1: Get a local copy of the repository - -Before you compile and run the program, you need to have the code locally. If you haven't already cloned the repository, navigate to the directory where you want to store the project and run the following command: - -```shell copy -git clone https://github.com/continuous-copilot/modernize-legacy-cobol-app.git -``` - -## Step 2: Compile and run the program - -You can either install a COBOL compiler in your preferred development environment (for example, the open source GnuCOBOL compiler), or use {% data variables.copilot.copilot_chat_short %} in {% data variables.product.prodname_github_codespaces %}. - -If you use MacOS, you can install GnuCOBOL using [Homebrew](https://brew.sh/): - -```shell copy -brew install gnu-cobol -``` - -If you use {% data variables.product.prodname_codespaces %} or an Ubuntu Linux system, you can install GnuCOBOL using `apt`: - -```shell copy -sudo apt-get update && \ -sudo apt-get install gnucobol -``` - -To compile the code, link the files, and create an executable, run the following command from the root of the repository: - -```shell copy -cobc -x main.cob operations.cob data.cob -o accountsystem -``` - -To run the program, use the following command: - -```shell copy -./accountsystem -``` - -## Step 3: Explain the files and code - -The first step in modernizing the code is to understand how it works. You can ask {% data variables.copilot.copilot_chat_short %} to explain the code in each file. - -Open the repository in your IDE then, in the {% data variables.copilot.copilot_chat_short %} panel, enter the following prompt. - -### Example prompt 1 - -```copilot copy -/explain #file:main.cob #file:operations.cob #file:data.cob. Create a high level overview of the app. Explain each file in detail and how they are linked. -``` - -### Example response 1 - -This is an excerpt from the response to the prompt above: - -`Sure! Here's a high-level overview of the COBOL application, along with detailed explanations of each file and how they are linked together.` - -`High-Level Overview` - -`This COBOL application simulates an account management system. It allows users to view the current balance, credit the account, debit the account, and exit the application. The application is divided into three main COBOL source files: main.cob, operations.cob, and data.cob. ...` - -## Step 4: Chart out the data flow between the files - -The next step is to understand how the files are linked together. You can use `@workspace` to create a data flow diagram for the application. - -> [!NOTE] -> The `@workspace` chat participant in {% data variables.product.prodname_vscode_shortname %} and {% data variables.product.prodname_vs %} provides {% data variables.product.prodname_copilot_short %} with context about all of the code in your workspace. You can use `@workspace` when you want {% data variables.product.prodname_copilot_short %} to consider the structure of your project and how different parts of your code interact. If you're using a JetBrains IDE, use `@project` rather than `@workspace`. - -### Example prompt 2 - -```copilot copy -@workspace Create a sequence diagram of the app showing the data flow of the app. Create this in mermaid format so that I can render this in a markdown file. -``` - -{% data variables.product.prodname_copilot_short %} outputs the Mermaid markup for a full sequence diagram that shows how the application works. You can copy and paste this markup into a Mermaid application to generate the diagram. - -## Step 5: Generate a test plan - -Create a test plan to ensure that the application works as expected after you make changes. You can use `@workspace` to generate a test plan that covers all of the files in the project. - -### Example prompt 3 - -```copilot copy -@workspace The current COBOL app has no tests. Create a test plan of current business logic that I can use to validate with business stakeholders about the current implementation. - -Later I would like to use this test plan to create unit and integration tests in a node.js app. I am in the middle of transforming the current COBOL app to a node.js app. - -The test plan should include the following: - -1. Test Case ID -2. Test Case Description -3. Pre-conditions -4. Test Steps -5. Expected Result -6. Actual Result -7. Status (Pass/Fail) -8. Comments - -Create the test plan in a markdown table format. The test plan should cover all the business logic in the current COBOL app. - -Convert this to markdown syntax to insert as a new file -``` - -{% data variables.product.prodname_copilot_short %} outputs a test plan in Markdown format that you can use to validate the application. To use this plan later in the process, create a file called `TESTPLAN.md` and copy the suggested plan into it. This will allow you to reference the test plan when generating test cases in the next steps. - -## Step 6: Convert the files from COBOL to Node.js - -The next step is to convert the COBOL files to Node.js. It's important to keep the following prompt practices in mind: - -* Provide context -* Give clear directions -* Be specific about the outcome you want to achieve - -Start by creating a temporary directory within your project, in which to save the JavaScript files you're going to create. - -```shell copy -mkdir temp-JS-project-directory -``` - -Then, iteratively convert the COBOL files to Node.js. - -### Example prompt 4 - -```copilot copy -Convert the code in #file:main.cob to node.js -``` - -### Example response 4 - -```shell -Sure! Here is the equivalent Node.js code for the main.cob file. This code will simulate the same account management system functionality. - -### COBOL Code: - -main.cob - - -```COBOL -IDENTIFICATION DIVISION. - PROGRAM-ID. MainProgram. - - DATA DIVISION. - WORKING-STORAGE SECTION. - 01 CONTINUE-FLAG PIC X VALUE 'Y'. - 01 USER-CHOICE PIC 9. - 01 FINAL-BALANCE PIC 9(6)V99 VALUE 1000.00. - - PROCEDURE DIVISION. - PERFORM UNTIL CONTINUE-FLAG = 'N' - DISPLAY "1. View Balance" - DISPLAY "2. Credit Account" - DISPLAY "3. Debit Account" - DISPLAY "4. Exit" - ACCEPT USER-CHOICE - - EVALUATE USER-CHOICE - WHEN 1 - CALL 'Operations' USING 'TOTAL' - WHEN 2 - CALL 'Operations' USING 'CREDIT' - WHEN 3 - CALL 'Operations' USING 'DEBIT' - WHEN 4 - MOVE 'N' TO CONTINUE-FLAG - DISPLAY "Exiting the program. Goodbye!" - WHEN OTHER - DISPLAY "Invalid choice. Please try again." - END-EVALUATE - END-PERFORM - STOP RUN. - - -### Node.js Code: `main.js` -```javascript -const readline = require('readline'); - -let continueFlag = 'Y'; -let finalBalance = 1000.00; - -const rl = readline.createInterface({ - input: process.stdin, - output: process.stdout -}); - -function displayMenu() { - console.log("1. View Balance"); - console.log("2. Credit Account"); - console.log("3. Debit Account"); - console.log("4. Exit"); -} - -function handleUserChoice(choice) { - switch (choice) { - case '1': - viewBalance(); - break; - case '2': - creditAccount(); - break; - case '3': - debitAccount(); - break; - case '4': - continueFlag = 'N'; - console.log("Exiting the program. Goodbye!"); - rl.close(); - break; - default: - console.log("Invalid choice. Please try again."); - promptUser(); - break; - } -} - -function viewBalance() { - console.log(`Current balance: ${finalBalance.toFixed(2)}`); - promptUser(); -} - -function creditAccount() { - rl.question("Enter credit amount: ", (amount) => { - amount = parseFloat(amount); - if (!isNaN(amount) && amount > 0) { - finalBalance += amount; - console.log(`Amount credited. New balance: ${finalBalance.toFixed(2)}`); - } else { - console.log("Invalid amount. Please try again."); - } - promptUser(); - }); -} - -function debitAccount() { - rl.question("Enter debit amount: ", (amount) => { - amount = parseFloat(amount); - if (!isNaN(amount) && amount > 0) { - if (finalBalance >= amount) { - finalBalance -= amount; - console.log(`Amount debited. New balance: ${finalBalance.toFixed(2)}`); - } else { - console.log("Insufficient funds for this debit."); - } - } else { - console.log("Invalid amount. Please try again."); - } - promptUser(); - }); -} - -function promptUser() { - if (continueFlag === 'Y') { - displayMenu(); - rl.question("Select an option: ", handleUserChoice); - } -} - -promptUser(); - -This Node.js code replicates the functionality of the COBOL main.cob file, providing a simple command-line interface for viewing the balance, crediting the account, debiting the account, and exiting the application. -``` - -You should review the suggested code thoroughly before using it. Once you're satisfied with the generated code, follow these steps to save it locally and complete the conversion: - -1. In the temporary directory you created earlier, create a new file called `main.js`. -1. Copy the generated code from the {% data variables.copilot.copilot_chat_short %} panel and paste it into `main.js`. -1. Save the file. -1. Use similar prompts to convert `operations.cob` and `data.cob` to Node.js. -1. Create corresponding JavaScript files, `operations.js` and `data.js`, in the same temporary directory. -1. Copy and paste the generated code into each file, then save them. - -## Step 7: Link the files together and set up a working Node.js project - -Once you have converted all of the files to Node.js, you need to link them together and set up a working Node.js project. - -1. Navigate to the temporary directory in your terminal. -1. Run the following command to create a `package.json` file: - - ```shell copy - npm init -y - ``` - -1. If your application requires external packages, install them by running: - - ```shell copy - npm install - ``` - -1. Start the app by running: - - ```shell copy - npm start - ``` - -At this point, the Node.js application may not fully replicate the functionality of the original COBOL program. For example, balances may not update correctly, or calculations might not match the COBOL logic. - -To refine the application, you will need to: - -* **Identify incorrect behavior** by running the program and comparing it to the COBOL version. -* **Work iteratively with {% data variables.product.prodname_copilot_short %}** to adjust the logic until the Node.js program behaves as expected. -* **Use targeted prompts** to debug and improve specific parts of the code, such as: - - ```copilot copy - @workspace - analyze main.js and ensure the account balance updates correctly when crediting an account. - ``` - -Refactoring legacy code isn’t always a one-step process—{% data variables.product.prodname_copilot_short %} can assist in debugging and improving functionality as you refine your new Node.js implementation. - -## Step 8: Generate unit and integration tests - -The next step is to generate unit and integration tests to ensure that the application works as expected. You can use `@workspace` to generate a test plan that covers all of the files in the project. - -### Example prompt 5 - -```copilot copy -@workspace I would like to create unit and integration tests cases from the test plan mentioned in #file:TESTPLAN.md file. The node.js code is in the node-accounting-app folder and I am looking to generate tests for #file:operations.js file. Use a popular testing framework and also provide all the dependencies required to run the tests. -``` - -### Example response 5 - -{% data variables.product.prodname_copilot_short %} generates a number of tests in Jest, a JavaScript testing framework, with a full, step-by-step guide on how to implement and run them. - -This is an excerpt from the response to the prompt above: - -`“This test plan covers the main functionalities of the COBOL application, including viewing the balance, crediting the account, debiting the account, and exiting the application. The test cases are implemented using Jest, a popular testing framework for Node.js. Validate this test plan with the business stakeholders to ensure it meets the business requirements. Once validated, you can use this plan to create corresponding unit tests and integration tests for the Node.js application.”` - -## Step 9: Run tests and refine the code - -After generating the test plan and writing the tests, you’ll need to run them and fix any failing tests. Testing is an iterative process, you may need to modify the code to resolve issues, then re-run the tests until everything passes. - -If a test fails, use {% data variables.product.prodname_copilot_short %} to help debug and refine the implementation. - -### Example prompt 6 - -```copilot copy -@workspace - analyze test failures in operations.test.js and suggest fixes to match the expected behavior. -``` - -Even if all tests pass, the program may still have issues. Automated tests don’t always catch missing functionality or logic errors, so manual testing is required to ensure the application behaves as expected. - -## Step 10: Move the JavaScript project to a new location - -Once the application is working as expected, move the new JavaScript project out of the COBOL directory to keep it separate. - -1. Navigate to the parent directory of the COBOL project. -1. Move the JavaScript project to a new location: - - ```shell copy - mv modernize-legacy-cobol-app new-js-project - ``` - -1. Navigate to the new project directory and confirm everything runs correctly: - - ```shell copy - cd new-js-project - npm start - ``` - -Now, the refactored Node.js application is in its own standalone project folder, separate from the original COBOL files. - -## Conclusion - -In this example, we looked at an account management system written in COBOL and modernized it into Node.js. We used {% data variables.copilot.copilot_chat_short %} to explain the code, chart out the data flow, generate a test plan, and convert the code to Node.js. By following these steps, you can modernize your legacy code and make it easier to maintain and extend. Here are some additional tips for modernizing legacy code: - -* **Prompting best practices are key**: The quality of your prompts determines the quality of {% data variables.product.prodname_copilot_short %}'s suggestions. Provide clear context, break down complex tasks into smaller steps, provide examples, and give {% data variables.product.prodname_copilot_short %} specific goals to work toward. This makes your workflow smoother and your results more precise -* **Review the code before using it**: Make sure you understand the code that {% data variables.product.prodname_copilot_short %} provides before using it in your application. This will help you catch any potential issues and ensure that the code meets your requirements. -* **Validate your changes**: After making changes to the code, it's important to validate that the application still works as expected. You can use the test plan generated by {% data variables.product.prodname_copilot_short %} to create unit and integration tests for the application. - -## Hands-on practice - -Practice modernizing legacy code with the [Modernizing your legacy code with {% data variables.product.prodname_copilot %}](https://github.com/skills/modernize-your-legacy-code-with-github-copilot) Skills exercise. - -In this exercise, you will learn how to: - -* Analyze legacy COBOL code with {% data variables.copilot.copilot_chat %} to understand business logic. -* Generate documentation, such as Mermaid data flow diagrams and test plans. -* Transform a COBOL codebase to Node.js with {% data variables.product.prodname_copilot_short %}. -* Create unit tests based on the generated test plan. - -## Further reading - -* [AUTOTITLE](/copilot/tutorials/copilot-cookbook/document-code/document-legacy-code) -* [Modernizing legacy code with {% data variables.product.prodname_copilot %}: Tips and examples](https://github.blog/ai-and-ml/github-copilot/modernizing-legacy-code-with-github-copilot-tips-and-examples/) on the {% data variables.product.github %} Blog diff --git a/content/copilot/tutorials/optimize-ai-usage.md b/content/copilot/tutorials/optimize-ai-usage.md index c66cea8436dc..afd08196ce39 100644 --- a/content/copilot/tutorials/optimize-ai-usage.md +++ b/content/copilot/tutorials/optimize-ai-usage.md @@ -29,7 +29,7 @@ Choose the model based on the work involved: Use as much capability as the task requires, and as little as necessary. Matching capability to task improves outcomes and directly controls costs at scale. -For a breakdown by model and task type, see [AUTOTITLE](/copilot/tutorials/compare-ai-models). +For a breakdown by model and task type, see [AUTOTITLE](/copilot/reference/ai-models/model-comparison#recommended-models-by-task). ### Configure the reasoning level of the model diff --git a/content/copilot/tutorials/plan-a-project.md b/content/copilot/tutorials/plan-a-project.md deleted file mode 100644 index a0f302772c84..000000000000 --- a/content/copilot/tutorials/plan-a-project.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Planning a project with GitHub Copilot -shortTitle: Plan a project -intro: 'Plan your next project by using {% data variables.product.prodname_copilot %} to turn your ideas into issues.' -permissions: 'Anyone with a {% data variables.product.prodname_copilot_short %} license can use {% data variables.product.prodname_copilot_short %} to create issues.
Try {% data variables.product.prodname_copilot_short %} for free {% octicon "link-external" height:16 %}' -versions: - feature: copilot -contentType: tutorials -category: - - Unblock complex work - - Author and optimize with Copilot ---- - -> [!NOTE] -> * This feature is in {% data variables.release-phases.public_preview %} and subject to change. -> * The responses shown in this article are examples. {% data variables.copilot.copilot_chat_short %} responses are non-deterministic, so you may get different responses from the ones shown here. - -Manage your project with {% data variables.product.prodname_github_issues %} using {% data variables.product.prodname_copilot_short %}. In this tutorial, you’ll use {% data variables.product.prodname_copilot_short %}’s agentic issue creation features to turn your product idea into epics, features, and tasks. Epics represent large bodies of work, while features and tasks break the work into smaller, actionable pieces. By the end, you’ll have a structured backlog ready to share with your team. - -## Project overview - -It’s important to define what you want your product to do. In the planning phase of the software development lifecycle (SDLC), you turn ideas into actionable tasks by breaking down your project into epics, features, and smaller pieces of work. This helps you organize your thoughts, set priorities, and prepare your team for development. - -When you use {% data variables.product.prodname_copilot_short %}, you drive this process. {% data variables.product.prodname_copilot_short %} can suggest a structure and fill in details, but the best results come when you have a sense of how you want the work to be organized. {% data variables.product.prodname_copilot_short %} works with your input to help you refine, expand, and document your plan. - -In this scenario you’ll plan a new shopping website that will allow users to: -* Browse a product catalog with categories and search -* Add items to a shopping cart -* Complete secure checkouts - -Your goal is to use {% data variables.product.prodname_copilot_short %} to quickly turn this vision into a structured project plan, creating epics and detailed issues that capture each part of your site. - -## Set up repository - -Set up a repository with {% data variables.product.prodname_github_issues %} enabled. See [AUTOTITLE](/repositories/creating-and-managing-repositories/creating-a-new-repository). - -By default, issues are enabled for new repositories. If you would like to use an existing repository but don’t see the **Issues** tab, follow these steps to enable issues: -1. From the repository, select **Settings**. -1. Under "Features", check the **Issues** box. - -## Generate project issues - -With the repository set up, you can use {% data variables.product.prodname_copilot_short %} to turn your project vision into a set of actionable issues. - -### Start in {% data variables.product.prodname_copilot_short %} in {% data variables.product.github %} - -{% data reusables.copilot.access-chat-instructions %} -1. Using the chat panel, attach the repository for the shopping website. This allows {% data variables.product.prodname_copilot_short %} to access the repository and create issues directly within it. - -### Create an epic issue - -1. Enter a detailed project description as your prompt. For example: - ```I’m planning to create a shopping website in React and Node.js. The site should allow users to browse products by category, search for items, add products to a cart, and complete checkout. Please help me plan the project by creating issues and breaking it down into epics, features, and tasks.``` -1. Submit your prompt. {% data variables.product.prodname_copilot_short %} will generate an issue tree, typically with an epic at the top and sub-issues for each main feature or task - -![Screenshot of Copilot Chat. Copilot chat displays a list of issues with an epic at the top and several sub-issues beneath it.](/assets/images/help/copilot/copilot-creates-sub-issues.png) - -## Navigate the issue tree - -1. Click the epic to view its details in the workbench. Navigate through the workbench to explore the issue tree. -1. Each issue typically includes a title and description. Additional metadata such as labels or assignees, can be edited directly in the workbench. -1. You can expand or collapse sub-issues to focus on specific parts of the project. - - The issue tree provides a clear overview of your project structure, making it easy to navigate between epics, features, and tasks. - -1. In this first iteration of the draft, {% data variables.product.prodname_copilot_short %} may generate only high-level issues. You can refine these issues further by breaking them down into smaller tasks or features. Let's refine the issue "Feature: UI Skeleton and Navigation". - - Prompt {% data variables.product.prodname_copilot_short %} with: - ```Can you break down the issue "Feature: UI Skeleton and Navigation" into smaller tasks?``` - - {% data variables.product.prodname_copilot_short %} will generate multiple new sub-issues such as: - * Task: Set up React project structure and initial files - * Task: Create placeholder pages for main routes - * Task: Implement site-wide navigation bar component - * Task: Integrate navigation with routing - * Task: Add basic responsive layout - -1. Repeat this process for the remaining feature issues in the epic. - -![Screenshot of the Copilot Chat workbench. The workbench displays an issue tree with an epic at the top and several sub-issues beneath it.](/assets/images/help/copilot/copilot-creates-sub-issues-workbench.png) - -### Improve issue descriptions - -After you finish generating the issue tree you may notice that {% data variables.product.prodname_copilot_short %}’s issue descriptions may be brief or unclear. To make them actionable, refine each issue as needed. - -1. Start with the newly generated issue such as "Task: Create placeholder pages for main routes". - - Prompt {% data variables.product.prodname_copilot_short %} with: - ```Can you improve the description for “Task: Create placeholder pages for main routes”? Please provide a detailed technical summary, list the main routes to be included, outline the steps for implementation, and specify what should be delivered for this task. Please add any relevant code snippets.``` - -1. {% data variables.product.prodname_copilot_short %} will generate a new version of the draft issue "Task: Create placeholder pages for main routes." - - At the top-left of the issue, click the versioning drop-down and select **Version 2** to review the new changes. -1. Review and decide whether to keep {% data variables.product.prodname_copilot_short %}’s revised version, edit further, or prompt again for more detail. {% data variables.product.prodname_copilot_short %} can add code snippets into the draft to improve clarity and provide immediate context for these issues. -1. Repeat this process for other issues in the epic, refining descriptions and breaking down tasks as needed. -1. Once you’re satisfied with the issue descriptions, click **Create all** to create the issues in your repository. - -## Unlink issues - -If {% data variables.product.prodname_copilot_short %} generates a sub-issue that doesn't belong to the issue tree, you can unlink it from the issue tree. - -1. In the workbench issue tree, click {% octicon "kebab-horizontal" aria-label="More options" %} next to the sub-issue, then click **Unlink sub-issue**. -1. The issue will be unlinked from its parent and will no longer appear under that epic in the tree. - -## Next steps - -Now that you’ve generated and refined your project issues, you can assign them to the right team members or even to {% data variables.product.prodname_copilot_short %} itself for further assistance. To learn more about how to assign {% data variables.product.prodname_copilot_short %} or contributors to issues, and how to continue planning and implementing your project with {% data variables.product.prodname_copilot_short %}’s agentic features, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/cloud-agent/start-copilot-sessions). - -## Further reading - -* [AUTOTITLE](/copilot/how-tos/copilot-on-github/copilot-for-github-tasks/use-copilot-to-create-or-update-issues) -* [AUTOTITLE](/copilot/tutorials/cloud-agent/pilot-cloud-agent) -* [AUTOTITLE](/copilot/tutorials/cloud-agent/get-the-best-results) -* [AUTOTITLE](/copilot/tutorials/speed-up-development-work) diff --git a/content/copilot/tutorials/reduce-technical-debt.md b/content/copilot/tutorials/reduce-technical-debt.md index 6c8d8a2db55d..54de72d88163 100644 --- a/content/copilot/tutorials/reduce-technical-debt.md +++ b/content/copilot/tutorials/reduce-technical-debt.md @@ -4,6 +4,12 @@ shortTitle: Reduce technical debt intro: 'Use {% data variables.product.prodname_copilot_short %} to automate refactoring and maintenance tasks, freeing your team to focus on feature development.' versions: feature: copilot +redirect_from: + - /copilot/tutorials/modernize-java-applications + - /copilot/tutorials/upgrade-projects + - /copilot/using-github-copilot/guides-on-using-github-copilot/upgrading-java-projects-with-github-copilot + - /copilot/tutorials/upgrading-java-projects-with-github-copilot + - /copilot/tutorials/upgrading-projects-with-github-copilot contentType: tutorials category: - Burn down tech debt @@ -374,6 +380,6 @@ After reading this tutorial, do you feel confident you can use {% data variables ## Further reading * [AUTOTITLE](/copilot/how-tos/use-copilot-agents/cloud-agent) -* [AUTOTITLE](/copilot/tutorials/refactor-code) +* [AUTOTITLE](/copilot/tutorials/copilot-cookbook/refactor-code) * [How to use GitHub Copilot in your IDE: Tips, tricks, and best practices](https://github.blog/developer-skills/github/how-to-use-github-copilot-in-your-ide-tips-tricks-and-best-practices/) in the {% data variables.product.company_short %} blog * [5 ways to integrate GitHub {% data variables.copilot.copilot_cloud_agent %} into your workflow](https://github.blog/ai-and-ml/github-copilot/5-ways-to-integrate-github-copilot-coding-agent-into-your-workflow/) in the {% data variables.product.company_short %} blog diff --git a/content/copilot/tutorials/refactor-code.md b/content/copilot/tutorials/refactor-code.md deleted file mode 100644 index 405a6865973c..000000000000 --- a/content/copilot/tutorials/refactor-code.md +++ /dev/null @@ -1,360 +0,0 @@ ---- -title: Refactoring code with GitHub Copilot -intro: 'Leverage {% data variables.product.prodname_copilot_short %} artificial intelligence to help you refactor your code quickly and effectively.' -versions: - feature: copilot -redirect_from: - - /copilot/using-github-copilot/example-use-cases/refactoring-code-with-github-copilot - - /copilot/using-github-copilot/guides-on-using-github-copilot/refactoring-code-with-github-copilot - - /copilot/tutorials/refactoring-code-with-github-copilot -shortTitle: Refactor code -contentType: tutorials -category: - - Modernize applications - - Author and optimize with Copilot ---- - -## Introduction - -Refactoring code is the process of restructuring existing code without changing its behavior. The benefits of refactoring include improving code readability, reducing complexity, making the code easier to maintain, and allowing new features to be added more easily. - -This article gives you some ideas for using {% data variables.product.prodname_copilot_short %} to refactor code in your IDE. - -> [!NOTE] Example responses are included in this article. {% data variables.copilot.copilot_chat %} may give you different responses from the ones shown here. - -## Understanding code - -Before you modify existing code you should make sure you understand its purpose and how it currently works. {% data variables.product.prodname_copilot_short %} can help you with this. - -1. Select the relevant code in your IDE's editor. -{% data reusables.copilot.open-inline-chat-vscode %} -1. In the input box for inline chat, type a forward slash (`/`). -1. In the dropdown list, select **/explain** and press Enter. -1. If the explanation that {% data variables.product.prodname_copilot_short %} returns is more than a few lines, click **View in Chat** to allow you to read the explanation more easily. - -## Optimizing inefficient code - -{% data variables.product.prodname_copilot_short %} can help you to optimize code - for example, to make the code run more quickly. - -### Example code - -In the two sections below, we'll use the following example bash script to demonstrate how to optimize inefficient code: - -```bash -#!/bin/bash - -# Find all .txt files and count lines in each -for file in $(find . -type f -name "*.txt"); do - wc -l "$file" -done -``` - -### Use the {% data variables.copilot.copilot_chat_short %} panel - -{% data variables.product.prodname_copilot_short %} can tell you whether code, like the example bash script, can be optimized. - -1. Select either the `for` loop or the entire contents of the file. -1. Open {% data variables.copilot.copilot_chat_short %} by clicking the chat icon in the activity bar or by using the keyboard shortcut: - - * **{% data variables.product.prodname_vscode_shortname %} and {% data variables.product.prodname_vs %}:** Control+Command+i (Mac) / Ctrl+Alt+i (Windows/Linux) - * **JetBrains:** Control+Shift+c - -1. In the input box at the bottom of the chat panel, type: `Can this script be improved?` - - {% data variables.product.prodname_copilot_short %} replies with a suggestion that will make the code more efficient. - -1. To apply the suggested change: - - * **In {% data variables.product.prodname_vscode_shortname %} and JetBrains:** Hover over the suggestion in the chat panel and click the **Insert At Cursor** icon. - - ![Screenshot of the 'Insert at cursor' icon in the {% data variables.copilot.copilot_chat_short %} panel.](/assets/images/help/copilot/insert-at-cursor.png) - - * **In {% data variables.product.prodname_vs %}:** Click **Preview** then, in the comparison view, click **Accept**. - -### Use {% data variables.product.prodname_copilot_short %} inline chat - -Alternatively, if you already know that existing code, like the example bash script, is inefficient: - -1. Select either the `for` loop or the entire contents of the file. -{% data reusables.copilot.open-inline-chat-vscode %} -1. Type `optimize` and press Enter. - - {% data variables.product.prodname_copilot_short %} suggests revised code. For example: - - ```bash - find . -type f -name "*.txt" -exec wc -l {} + - ``` - - This is more efficient than the original code, shown earlier in this article, because using `-exec ... +` allows `find` to pass multiple files to `wc` at once rather than calling `wc` once for each `*.txt` file that's found. - -{% data reusables.copilot.assess-copilot-suggestion %} - -{% data reusables.copilot.check-copilot-suggestion %} - -## Cleaning up repeated code - -Avoiding repetition will make your code easier to revise and debug. For example, if the same calculation is performed more than once at different places in a file, you could move the calculation to a function. - -In the following very simple JavaScript example, the same calculation (item price multiplied by number of items sold) is performed in two places. - -```javascript -let totalSales = 0; - -let applePrice = 3; -let applesSold = 100; -totalSales += applePrice * applesSold; - -let orangePrice = 5; -let orangesSold = 50; -totalSales += orangePrice * orangesSold; - -console.log(`Total: ${totalSales}`); -``` - -You can ask {% data variables.product.prodname_copilot_short %} to move the repeated calculation into a function. - -1. Select the entire contents of the file. -{% data reusables.copilot.open-inline-chat-vscode %} -1. Type: `move repeated calculations into functions` and press Enter. - - {% data variables.product.prodname_copilot_short %} suggests revised code. For example: - - ```javascript - function calculateSales(price, quantity) { - return price * quantity; - } - - let totalSales = 0; - - let applePrice = 3; - let applesSold = 100; - totalSales += calculateSales(applePrice, applesSold); - - let orangePrice = 5; - let orangesSold = 50; - totalSales += calculateSales(orangePrice, orangesSold); - - console.log(`Total: ${totalSales}`); - ``` - -{% data reusables.copilot.assess-copilot-suggestion %} - -{% data reusables.copilot.check-copilot-suggestion %} - -## Making code more concise - -If code is unnecessarily verbose it can be difficult to read and maintain. {% data variables.product.prodname_copilot_short %} can suggest a more concise version of selected code. - -In the following example, this Python code outputs the area of a rectangle and a circle, but could be written more concisely: - -```python -def calculate_area_of_rectangle(length, width): - area = length * width - return area - -def calculate_area_of_circle(radius): - import math - area = math.pi * (radius ** 2) - return area - -length_of_rectangle = 10 -width_of_rectangle = 5 -area_of_rectangle = calculate_area_of_rectangle(length_of_rectangle, width_of_rectangle) -print(f"Area of rectangle: {area_of_rectangle}") - -radius_of_circle = 7 -area_of_circle = calculate_area_of_circle(radius_of_circle) -print(f"Area of circle: {area_of_circle}") -``` - -1. Select the entire contents of the file. -{% data reusables.copilot.open-inline-chat-vscode %} -1. Type: `make this more concise` and press Enter. - - {% data variables.product.prodname_copilot_short %} suggests revised code. For example: - - ```python - import math - - def calculate_area_of_rectangle(length, width): - return length * width - - def calculate_area_of_circle(radius): - return math.pi * (radius ** 2) - - print(f"Area of rectangle: {calculate_area_of_rectangle(10, 5)}") - print(f"Area of circle: {calculate_area_of_circle(7)}") - ``` - -{% data reusables.copilot.assess-copilot-suggestion %} - -{% data reusables.copilot.check-copilot-suggestion %} - -## Splitting up complex units of code - -Large methods or functions that perform multiple operations are likely to offer fewer opportunities for reuse than smaller, simpler functions that are focused on performing a particular operation. They may also be more difficult to understand and debug. - -{% data variables.product.prodname_copilot_short %} can help you to split up complex blocks of code into smaller units that are more suitable for reuse. - -The following Python code is a very simple example, but it shows the principle of splitting up a single function into two functions that perform particular operations. - -```python -import pandas as pd -from pandas.io.formats.style import Styler - -def process_data(item, price): - # Cleanse data - item = item.strip() # Strip whitespace from item - price = price.strip() # Strip whitespace from price - price = float(price) # Convert price to a float - # More cleansing operations here - - # Create and print a DataFrame - data = {'Item': [item], 'Price': [price]} - df = pd.DataFrame(data) - print(df.to_string(index=False)) - -# Example usage -item = " Apple " -price = " 1.25" -process_data(item, price) -``` - -To split up the `process_data` function: - -1. Put the cursor in the function name. -{% data reusables.copilot.open-inline-chat-vscode %} -1. Type: `split into 2 separate functions: one for cleansing data, the other for printing` and press Enter. - - {% data variables.product.prodname_copilot_short %} suggests revised code. For example: - - ```python - def cleanse_data(item, price): - # Cleanse data - item = item.strip() # Strip whitespace from item - price = price.strip() # Strip whitespace from price - price = float(price) # Convert price to a float - return item, price - - def print_data(item, price): - # Create and print a DataFrame - data = {'Item': [item], 'Price': [price]} - df = pd.DataFrame(data) - print(df.to_string(index=False)) - - def process_data(item, price): - item, price = cleanse_data(item, price) - print_data(item, price) - ``` - - > [!NOTE] The example suggestion shown above replaces the existing function with three functions. The third function simply calls the other two functions, and allows for existing code that calls the `process_data` function. - -{% data reusables.copilot.assess-copilot-suggestion %} - -{% data reusables.copilot.check-copilot-suggestion %} - -## Rewrite conditional code for better readability - -There are often several ways to write code that does, or does not, get executed depending on various conditions. Some conditional structures are better suited than others to particular use cases, and choosing an alternative conditional structure can sometimes make the code easier to read. - -This Java method uses a series of `if` and `else if` statements to determine which operation to perform: - -```java -public String getSound(String animal) { - if (animal == null) { - System.out.println("Oops! A null animal?"); - } else if (animal.equalsIgnoreCase("Dog")) { - return "Bark"; - } else if ( animal.equalsIgnoreCase("Cat")) { - return "Meow"; - } else if ( animal.equalsIgnoreCase("Bird")) { - return "Tweet"; - } - return "Unknown"; -} -``` - -A `switch` statement might be a better way of applying the same logic. - -1. Put the cursor in the method name. -{% data reusables.copilot.open-inline-chat-vscode %} -1. Type: `rewrite the condition to use a switch and use Java 21 syntax with null case, but also add documentation and provide a better function name`. - - This demonstrates how you can use a single prompt to ask {% data variables.product.prodname_copilot_short %} to make multiple changes. - -1. Press Enter. - - {% data variables.product.prodname_copilot_short %} suggests revised code. For example: - - ```java - /** - * Retrieves the sound made by a given animal. - * - * @param animal The name of the animal. - * @return The sound made by the animal, or "Unknown" if the animal is not recognized. - */ - public String getAnimalSound(String animal) { - return switch (animal) { - case null -> { - System.out.println("Oops! A null animal?"); - yield "Unknown"; - } - case String a when a.equalsIgnoreCase("Dog") -> "Bark"; - case String a when a.equalsIgnoreCase("Cat") -> "Meow"; - case String a when a.equalsIgnoreCase("Bird") -> "Tweet"; - default -> "Unknown"; - }; - } - ``` - -{% data reusables.copilot.assess-copilot-suggestion %} - -{% data reusables.copilot.check-copilot-suggestion %} - -## Reformat code to use a different structure - -Suppose you have this function in JavaScript: - -```javascript -function listRepos(o, p) { - return fetch(`https://api.github.com/orgs/${o}/repos?per_page=${parseInt(p)}`) - .then((response) => response.json()) - .then( (data) => data); -} -``` - -If your coding standards require you to use the arrow notation for functions, and descriptive names for parameters, you can use {% data variables.product.prodname_copilot_short %} to help you make these changes. - -1. Put the cursor in the function name. -{% data reusables.copilot.open-inline-chat-vscode %} -1. Type: `use arrow notation and better parameter names` and press Enter. - - {% data variables.product.prodname_copilot_short %} suggests revised code. For example: - - ```javascript - const listRepos = (org, perPage) => { - return fetch(`https://api.github.com/orgs/${org}/repos?per_page=${parseInt(perPage)}`) - .then(response => response.json()) - .then(data => data); - }; - ``` - -## Improving the name of a symbol - -> [!NOTE] -> * {% data variables.product.prodname_vscode_shortname %} and {% data variables.product.prodname_vs %} only. -> * Support for this feature depends on having the appropriate language extension installed in your IDE for the language you are using. Not all language extensions support this feature. - -Well chosen names can help to make code easier to maintain. {% data variables.product.prodname_copilot_short %} in {% data variables.product.prodname_vscode_shortname %} and {% data variables.product.prodname_vs %} can suggest alternative names for symbols such as variables or functions. - -1. Put the cursor in the symbol name. -1. Press F2. -1. **{% data variables.product.prodname_vs %} only:** Press Ctrl+Space. - - {% data variables.product.prodname_copilot_short %} suggests alternative names. - - ![Screenshot of a dropdown list in {% data variables.product.prodname_vscode_shortname %} giving alternatives for a symbol name.](/assets/images/help/copilot/rename-symbol.png) - -1. In the dropdown list, select one of the suggested names. - - The name is changed throughout the project. diff --git a/content/copilot/tutorials/upgrade-projects.md b/content/copilot/tutorials/upgrade-projects.md deleted file mode 100644 index 87bd3bce9214..000000000000 --- a/content/copilot/tutorials/upgrade-projects.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: Upgrading projects with GitHub Copilot -shortTitle: Upgrade projects -intro: 'You can use {% data variables.product.prodname_copilot %} to upgrade your Maven and Gradle Java applications and .NET applications.' -versions: - feature: copilot -redirect_from: - - /copilot/using-github-copilot/guides-on-using-github-copilot/upgrading-java-projects-with-github-copilot - - /copilot/tutorials/upgrading-java-projects-with-github-copilot - - /copilot/tutorials/upgrading-projects-with-github-copilot -contentType: tutorials -category: - - Burn down tech debt - - Author and optimize with Copilot ---- - -## Introduction - -{% data variables.product.prodname_copilot %} can help streamline the process of modernizing and upgrading your Java and .NET applications. {% data variables.product.prodname_copilot_short %} will analyze the project, generate a plan, automatically fix issues it encounters when carrying out the plan, and produce a summary. - -## Upgrading Java projects - -You can upgrade a Git-based Maven or Gradle Java project using {% data variables.product.prodname_copilot %} in {% data variables.product.prodname_vscode %}. You will need: - -* Any paid [{% data variables.product.prodname_copilot_short %} plan](https://github.com/features/copilot/plans?ref_product=copilot&ref_type=purchase&ref_style=text&ref_plan=cfi). -* The latest version of [{% data variables.product.prodname_vscode %}](https://code.visualstudio.com/). -* For Maven-based projects, access to the public Maven Central repository. -* Installed versions of both the source and target JDKs. - -For an overview of the modernization workflow, see [AUTOTITLE](/copilot/tutorials/modernize-java-applications). - -## Upgrading .NET projects - -You can also upgrade a .NET project using {% data variables.product.prodname_copilot %} in {% data variables.product.prodname_vs %}. You will need: - -* Any paid [{% data variables.product.prodname_copilot_short %} plan](https://github.com/features/copilot/plans?ref_product=copilot&ref_type=purchase&ref_style=text&ref_plan=cfi). -* The latest release of {% data variables.product.prodname_vs %} Enterprise, Professional or Community 2022. - -For the next steps, see [GitHub Copilot app modernization - upgrade for .NET](https://marketplace.visualstudio.com/items?itemName=ms-appmod.dotnet-modernization) on Microsoft Visual Studio Marketplace. diff --git a/content/copilot/tutorials/use-an-ai-sme.md b/content/copilot/tutorials/use-an-ai-sme.md index cae60ad5066d..382b0be32137 100644 --- a/content/copilot/tutorials/use-an-ai-sme.md +++ b/content/copilot/tutorials/use-an-ai-sme.md @@ -157,5 +157,5 @@ Used this way, {% data variables.copilot.copilot_cli_short %} doesn't replace hu ## Next steps * Save your most useful prompt preambles as custom instructions, so you can reuse them across sessions and projects. See [AUTOTITLE](/copilot/how-tos/copilot-cli/customize-copilot/add-custom-instructions). -* Once you understand the area of the code you want to change, use {% data variables.copilot.copilot_cli_short %} to help you make the change. See [AUTOTITLE](/copilot/tutorials/refactor-code) and [AUTOTITLE](/copilot/tutorials/write-tests). +* Once you understand the area of the code you want to change, use {% data variables.copilot.copilot_cli_short %} to help you make the change. For testing examples, see [AUTOTITLE](/copilot/tutorials/write-tests). * Learn how to control which tools {% data variables.copilot.copilot_cli_short %} can run during a session. See [AUTOTITLE](/copilot/how-tos/copilot-cli/use-copilot-cli/allowing-tools). diff --git a/content/discussions/collaborating-with-your-community-using-discussions/collaborating-with-maintainers-using-discussions.md b/content/discussions/collaborating-with-your-community-using-discussions/collaborating-with-maintainers-using-discussions.md index aafab30556d9..98b0a17445d8 100644 --- a/content/discussions/collaborating-with-your-community-using-discussions/collaborating-with-maintainers-using-discussions.md +++ b/content/discussions/collaborating-with-your-community-using-discussions/collaborating-with-maintainers-using-discussions.md @@ -30,12 +30,6 @@ Community members can upvote discussions and top-level comments inside discussio For more information about participation in discussions, see [AUTOTITLE](/discussions/collaborating-with-your-community-using-discussions/participating-in-a-discussion). -{% ifversion copilot %} - -> [!TIP] You can also use {% data variables.copilot.copilot_chat_short %} to generate ideas, outlines, or drafts for discussions, based on your pull requests and issues. See [AUTOTITLE](/copilot/tutorials/copilot-cookbook/document-code/write-discussions-or-blog-posts). - -{% endif %} - ## Prerequisites To collaborate with maintainers in repository discussions, a repository administrator or project maintainer must enable {% data variables.product.prodname_discussions %} for the repository. For more information, see [AUTOTITLE](/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/enabling-or-disabling-github-discussions-for-a-repository). diff --git a/content/discussions/collaborating-with-your-community-using-discussions/participating-in-a-discussion.md b/content/discussions/collaborating-with-your-community-using-discussions/participating-in-a-discussion.md index 233a65633957..bf39890c17d4 100644 --- a/content/discussions/collaborating-with-your-community-using-discussions/participating-in-a-discussion.md +++ b/content/discussions/collaborating-with-your-community-using-discussions/participating-in-a-discussion.md @@ -25,12 +25,6 @@ In addition to starting or viewing discussions and polls, you can: {% ifversion fpt or ghec %}You can block users and report disruptive content to maintain a safe and pleasant environment for yourself. For more information, see [AUTOTITLE](/communities/maintaining-your-safety-on-github).{% endif %} -{% ifversion copilot %} - -> [!TIP] You can also use {% data variables.copilot.copilot_chat_short %} to generate ideas, outlines, or drafts for discussions based on your recent pull requests and issues. See [AUTOTITLE](/copilot/tutorials/copilot-cookbook/document-code/write-discussions-or-blog-posts). - -{% endif %} - ## Prerequisites {% data variables.product.prodname_discussions %} must be enabled for the repository or organization for you to participate in a discussion in the repository or organization. For more information, see [AUTOTITLE](/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/enabling-or-disabling-github-discussions-for-a-repository) and [AUTOTITLE](/organizations/managing-organization-settings/enabling-or-disabling-github-discussions-for-an-organization). diff --git a/content/get-started/using-github/communicating-on-github.md b/content/get-started/using-github/communicating-on-github.md index 68cbb2b883f6..2aa79a48b980 100644 --- a/content/get-started/using-github/communicating-on-github.md +++ b/content/get-started/using-github/communicating-on-github.md @@ -21,12 +21,6 @@ category: You can create and participate in issues, pull requests, and team discussions, depending on the type of conversation you'd like to have. -{% ifversion copilot %} - -> [!TIP] You can also use {% data variables.copilot.copilot_chat_short %} to generate ideas, outlines, or drafts for discussions, based on your pull requests and issues. See [AUTOTITLE](/copilot/tutorials/copilot-cookbook/document-code/write-discussions-or-blog-posts). - -{% endif %} - ### {% data variables.product.prodname_github_issues %} * Are useful for discussing specific details of a project such as bug reports, planned improvements and feedback diff --git a/content/get-started/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables.md b/content/get-started/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables.md index 7b4b2d4a7747..47165ed5a244 100644 --- a/content/get-started/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables.md +++ b/content/get-started/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables.md @@ -6,6 +6,8 @@ redirect_from: - /articles/organizing-information-with-tables - /github/writing-on-github/organizing-information-with-tables - /github/writing-on-github/working-with-advanced-formatting/organizing-information-with-tables + - /copilot/tutorials/copilot-cookbook/communicate-effectively/generating-tables + - /copilot/tutorials/copilot-chat-cookbook/communicate-effectively/generating-tables versions: fpt: '*' ghes: '*' diff --git a/content/issues/tracking-your-work-with-issues/learning-about-issues/about-issues.md b/content/issues/tracking-your-work-with-issues/learning-about-issues/about-issues.md index 84301183be22..53323bad87be 100644 --- a/content/issues/tracking-your-work-with-issues/learning-about-issues/about-issues.md +++ b/content/issues/tracking-your-work-with-issues/learning-about-issues/about-issues.md @@ -20,12 +20,6 @@ You can create issues in your repository to plan, discuss, and track work. Issue Issues can be created in a variety of ways, so you can choose the most convenient method for your workflow. For example, you can create an issue from a repository,{% ifversion sub-issues %} while adding sub-issues,{% endif %} convert a comment in an issue or pull request, create an issue from a specific line of code, or via a URL query. You can also create an issue from your platform of choice: through the web UI, {% data variables.product.prodname_desktop %}, {% data variables.product.prodname_cli %}, GraphQL and REST APIs, or {% data variables.product.prodname_mobile %}. See [AUTOTITLE](/issues/tracking-your-work-with-issues/using-issues/creating-an-issue). -{% ifversion copilot %} - -> [!TIP] You can also use {% data variables.copilot.copilot_chat_short %} to generate ideas, outlines, or drafts for discussions or blog posts, based on your issues. See [AUTOTITLE](/copilot/tutorials/copilot-cookbook/document-code/write-discussions-or-blog-posts). - -{% endif %} - {% ifversion sub-issues %} ## About sub-issues