Allow articles with missing shortTitles to appear on home page (#54389)
This commit is contained in:
@@ -0,0 +1,149 @@
|
||||
---
|
||||
title: 'Documenting legacy code'
|
||||
shortTitle: Document legacy code
|
||||
intro: '{% data variables.product.prodname_copilot_chat_short %} can help with documenting legacy code.'
|
||||
redirect_from:
|
||||
- /copilot/example-prompts-for-github-copilot-chat/documenting-code/documenting-legacy-code
|
||||
versions:
|
||||
feature: copilot
|
||||
category:
|
||||
- 'Documenting code'
|
||||
complexity:
|
||||
- Simple
|
||||
octicon: book
|
||||
topics:
|
||||
- Copilot
|
||||
---
|
||||
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
|
||||
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.product.prodname_copilot_chat_short %} to document the code.
|
||||
|
||||
`Document this code`
|
||||
|
||||
> [!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 %}
|
||||
@@ -0,0 +1,171 @@
|
||||
---
|
||||
title: 'Explaining complex algorithms or logic'
|
||||
shortTitle: Explain complex logic
|
||||
intro: '{% data variables.product.prodname_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
|
||||
versions:
|
||||
feature: copilot
|
||||
category:
|
||||
- 'Documenting code'
|
||||
complexity:
|
||||
- Intermediate
|
||||
octicon: book
|
||||
topics:
|
||||
- Copilot
|
||||
---
|
||||
|
||||
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.product.prodname_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
|
||||
private static readonly HttpClient _client = new HttpClient();
|
||||
|
||||
public async Task<string> 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<string> 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<string, Label>(UpdateStatusLabel), message, statusLabel);
|
||||
} else {
|
||||
statusLabel.Text = message;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Example prompt
|
||||
|
||||
We can ask {% data variables.product.prodname_copilot_chat_short %} to make this code easier to understand using comments.
|
||||
|
||||
`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();
|
||||
|
||||
/// <summary>
|
||||
/// Fetches data from an API with retry mechanism and timeout functionality
|
||||
/// </summary>
|
||||
/// <param name="apiUrl">The URL to fetch data from</param>
|
||||
/// <param name="cancellationToken">Token to cancel the operation</param>
|
||||
/// <param name="maxRetries">Maximum number of retry attempts</param>
|
||||
/// <param name="cancellationDelay">Timeout duration in milliseconds</param>
|
||||
/// <param name="statusLabel">UI label to show status updates</param>
|
||||
public async Task<string> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes the actual API call to fetch data
|
||||
/// </summary>
|
||||
private async Task<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates UI label text safely across threads
|
||||
/// </summary>
|
||||
/// <param name="message">The message to display</param>
|
||||
/// <param name="statusLabel">The label control to update</param>
|
||||
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<string, Label>(UpdateStatusLabel), message, statusLabel);
|
||||
} else {
|
||||
// Direct update if already on UI thread
|
||||
statusLabel.Text = message;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Further reading
|
||||
|
||||
{% data reusables.copilot.example-prompts.further-reading-items %}
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
title: 'Explaining legacy code'
|
||||
shortTitle: Explain legacy code
|
||||
intro: '{% data variables.product.prodname_copilot_chat_short %} can help with explaining unfamiliar code.'
|
||||
redirect_from:
|
||||
- /copilot/example-prompts-for-github-copilot-chat/documenting-code/explaining-legacy-code
|
||||
versions:
|
||||
feature: copilot
|
||||
category:
|
||||
- 'Documenting code'
|
||||
complexity:
|
||||
- Simple
|
||||
octicon: book
|
||||
topics:
|
||||
- Copilot
|
||||
---
|
||||
|
||||
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.product.prodname_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.product.prodname_copilot_chat_short %} to explain the code to you.
|
||||
|
||||
```text
|
||||
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.
|
||||
|
||||
`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 %}
|
||||
@@ -0,0 +1,15 @@
|
||||
---
|
||||
title: Documenting code
|
||||
intro: 'Discover ways that you can use {% data variables.product.prodname_copilot_chat %} to document your code.'
|
||||
redirect_from:
|
||||
- /copilot/example-prompts-for-github-copilot-chat/documenting-code
|
||||
versions:
|
||||
feature: copilot
|
||||
topics:
|
||||
- Copilot
|
||||
children:
|
||||
- /documenting-legacy-code
|
||||
- /explaining-legacy-code
|
||||
- /explaining-complex-algorithms-or-logic
|
||||
- /syncing-documentation-with-code-changes
|
||||
---
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
title: 'Syncing documentation with code changes'
|
||||
shortTitle: Sync documentation
|
||||
intro: '{% data variables.product.prodname_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
|
||||
versions:
|
||||
feature: copilot
|
||||
category:
|
||||
- 'Documenting code'
|
||||
complexity:
|
||||
- Intermediate
|
||||
octicon: book
|
||||
topics:
|
||||
- Copilot
|
||||
---
|
||||
|
||||
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.product.prodname_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
|
||||
/**
|
||||
* 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<Products[]> {
|
||||
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.product.prodname_copilot_chat_short %} to update the documentation according to the current code.
|
||||
|
||||
`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 %}
|
||||
Reference in New Issue
Block a user