Skip to content

Commit 8faec9b

Browse files
optimize code reviews tutorial (#58613)
Co-authored-by: Claire W <[email protected]>
1 parent 203ec79 commit 8faec9b

File tree

3 files changed

+231
-11
lines changed

3 files changed

+231
-11
lines changed

content/copilot/tutorials/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ children:
2121
- /explore-pull-requests
2222
- /write-tests
2323
- /refactor-code
24+
- /optimize-code-reviews
2425
- /reduce-technical-debt
2526
- /review-ai-generated-code
2627
- /learn-a-new-language
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
---
2+
title: Build an optimized review process with {% data variables.product.prodname_copilot_short %}
3+
allowTitleToDifferFromFilename: true
4+
shortTitle: Optimize code reviews
5+
intro: Automate reviews with {% data variables.product.prodname_copilot_short %} to optimize and improve your review process.
6+
product: '{% data variables.copilot.copilot_code-review_short %} is available for {% data variables.copilot.copilot_pro_short %}, {% data variables.copilot.copilot_pro_plus %}, {% data variables.copilot.copilot_business_short %} and {% data variables.copilot.copilot_enterprise_short %}. See [Copilot plans](https://github.com/features/copilot/plans?ref_product=copilot&ref_type=purchase&ref_style=text).'
7+
versions:
8+
feature: copilot
9+
topics:
10+
- Copilot
11+
contentType: tutorials
12+
category:
13+
- Accelerate PR velocity
14+
- Author and optimize with Copilot
15+
redirect_from:
16+
- /copilot/tutorials/optimize-reviews-with-copilot
17+
---
18+
19+
## Introduction
20+
21+
Code reviews are more efficient when you spend less time on minor implementation details, such as naming and style conventions, and instead focus your effort on higher level design, problem solving, and functionality that meets user needs.
22+
23+
In this article, we'll show how automatic reviews from {% data variables.product.prodname_copilot_short %} can help optimize your review process so you spend less time on minor changes and more time on nuanced problem solving and deeper understanding for implementation that's not simply adequate, but skillfully meets user needs.
24+
25+
## 1. Improve review quality from {% data variables.product.prodname_copilot_short %}
26+
27+
{% data variables.copilot.copilot_code-review_short %} can provide automated reviews for all pull requests in your repository and make reviewing more efficient by catching changes you don't want in your code. When paired with custom instructions, {% data variables.copilot.copilot_code-review_short %} is more effective because it can provide responses that are tailored to the way your team works, the tools you use, or the specifics of your project.
28+
29+
Best practices for writing custom instructions include:
30+
* Distinct headings
31+
* Bullet points
32+
* Short, direct instructions
33+
34+
Let's look at an example. If you're building an order processing system using Python, your custom instructions may include Python-specific formatting, performance, and secure coding practices, as well as guidance directly relevant to your project. The following example shows what a few of the lines of your custom instructions might look like.
35+
36+
```markdown
37+
## Repository context
38+
- This repository implements an order processing system (order intake, payment, fulfillment) where correctness, security, and auditability are critical.
39+
40+
## Style and conventions
41+
- Follow the PEP 8 and PEP 257 style guide for Python.
42+
- Use clear, domain-relevant names (orders, payments, inventory, customers, shipments).
43+
- Prefer small, focused functions and methods with clearly defined responsibilities.
44+
45+
## Secure coding
46+
- Verify proper input validation and sanitization.
47+
- Review authentication and authorization logic.
48+
49+
## Error handling guidelines
50+
- Handle timeouts and network errors gracefully.
51+
- Ensure failures are logged with enough detail for debugging.
52+
53+
## Order processing context
54+
- Ensure order creation, payment handling, and updates are idempotent to avoid duplicate orders or duplicate charges.
55+
- Validate and normalize all order, payment, and customer data before persisting or acting on it.
56+
- Do not log or persist sensitive data (passwords, raw payment details, full identifiers) without hashing, encryption, or redaction.
57+
- Call out obvious performance issues in core order workflows (e.g., N+1 queries, per-order synchronous network calls) and suggest simpler, more efficient alternatives.
58+
59+
## Review style
60+
- Be concise, specific and actionable.
61+
- Explain the "why" behind recommendations using bullet points.
62+
```
63+
64+
In the next section, we'll walk through how our example custom instructions can positively impact the review comments {% data variables.product.prodname_copilot_short %} provides for a pull request.
65+
66+
## 2. Automate reviews to address style conventions and performance
67+
68+
When automatic {% data variables.copilot.copilot_code-review_short %} is enabled, {% data variables.product.prodname_copilot_short %} will automatically review a pull request once it's out of draft mode.
69+
70+
Imagine you submit a pull request that includes the following function to update inventory in your order processing system.
71+
72+
```python
73+
def notify_inventory(product_id, quantity):
74+
requests.post("http://inventory-service/update", json={"product_id": product_id, "quantity": quantity})
75+
```
76+
77+
While this is functional, it lacks clarity and robustness. The intent of types are implicit, there are no docstrings, and it does not include error handling or logging, which makes it unclear whether the notification actually worked.
78+
79+
{% data variables.product.prodname_copilot_short %} would review the code and may make the following comment and code suggestion.
80+
81+
{% data reusables.copilot.example-prompts.response-is-an-example %}
82+
83+
```copilot
84+
Missing error handling for network calls
85+
86+
The notify_inventory function makes a synchronous network call without any error handling for timeouts, connection failures, or non-200 responses.
87+
88+
Why this matters:
89+
90+
- Network failures will cause unhandled exceptions and crash the order processing flow
91+
- Orders could be marked as CONFIRMED but inventory never gets updated
92+
- This violates the requirement to "handle timeouts and network errors gracefully"
93+
- Failures won't be logged with enough detail for debugging
94+
95+
Recommendation: Add proper error handling with timeout and logging:
96+
```
97+
98+
```python
99+
def notify_inventory(product_id: str, quantity: int) -> bool:
100+
"""Notify the inventory service of order placement.
101+
102+
Args:
103+
product_id: The product identifier.
104+
quantity: The quantity ordered.
105+
106+
Returns:
107+
True if the notification succeeded; False otherwise.
108+
"""
109+
try:
110+
response = requests.post(
111+
"http://inventory-service/update",
112+
json={"product_id": product_id, "quantity": quantity},
113+
timeout=5,
114+
)
115+
response.raise_for_status()
116+
logger.info(
117+
"Inventory notified for product %s, quantity %d (status %d)",
118+
product_id,
119+
quantity,
120+
response.status_code,
121+
)
122+
return True
123+
except requests.exceptions.Timeout:
124+
logger.error(
125+
"Timeout notifying inventory for product %s, quantity %d",
126+
product_id,
127+
quantity,
128+
exc_info=True,
129+
)
130+
except requests.exceptions.RequestException:
131+
logger.error(
132+
"Failed to notify inventory for product %s, quantity %d",
133+
product_id,
134+
quantity,
135+
exc_info=True,
136+
)
137+
return False
138+
```
139+
140+
The response from {% data variables.product.prodname_copilot_short %} follows guidance from your custom instructions in its recommendation. In this example, it follows the PEP 8 and 257 style guidance for Python and suggests an improvement to better handle timeouts and error logging, while concisely explaining the reasoning behind the suggestions.
141+
142+
> [!NOTE] Always carefully review {% data variables.product.prodname_copilot_short %}'s suggestions before accepting and committing.
143+
144+
Automatic review comments like these support you in building your own understanding when you're coding or can help you focus and narrow feedback given to others when reviewing.
145+
146+
147+
## 3. Flag security vulnerabilities and fix them
148+
149+
Next, imagine you've been tasked to improve how passwords are stored in your order processing system. You submit a pull request with code you thought sufficiently hashed user passwords to protect them.
150+
151+
```python
152+
def get_password_hash(password: str, salt: str) -> str:
153+
"""Hash a password with the given salt using SHA-256.
154+
155+
Returns the hexadecimal representation of the hashed password.
156+
"""
157+
return hashlib.sha256((password + salt).encode()).hexdigest()
158+
159+
160+
class User:
161+
"""Represents a user in the order processing system."""
162+
163+
def __init__(self, username: str, password: str, salt: str):
164+
"""Initialize a User with username, password, and salt.
165+
166+
The password is hashed and stored for authentication.
167+
"""
168+
self.username = username
169+
self.salt = salt
170+
self.password_hash = get_password_hash(password, self.salt)
171+
172+
def verify_password(self, password: str) -> bool:
173+
"""Verify a plain-text password against the stored hash."""
174+
return get_password_hash(password, self.salt) == self.password_hash
175+
```
176+
177+
However, in this example, using SHA-256 is not acceptable as it's not computationally expensive enough to protect user passwords.
178+
179+
While {% data variables.copilot.copilot_code-review_short %} can make security best practice suggestions, {% data variables.copilot.copilot_autofix_short %} for {% data variables.product.prodname_code_scanning %} takes it a step further. Leveraging the capabilities of {% data variables.product.prodname_code_scanning %} with {% data variables.product.prodname_codeql %} analysis to analyze the code in a {% data variables.product.github %} repository and find security vulnerabilities and coding errors, {% data variables.copilot.copilot_autofix_short %} can then suggest fixes for alerts, enabling you to prevent and reduce vulnerabilities more efficiently.
180+
181+
For example, {% data variables.copilot.copilot_autofix_short %} may make the following comment on the code.
182+
183+
```copilot
184+
Using SHA-256 for password hashing is insecure for authentication systems. SHA-256 is designed to be fast, making it vulnerable to brute-force attacks.
185+
186+
To fix the problem, use a password-specific hashing algorithm like bcrypt, scrypt, or argon2 (e.g., `argon2-cffi` from the PyPI package) which are designed to be slow and include built-in salting mechanisms.
187+
```
188+
189+
{% data variables.copilot.copilot_autofix_short %} will also make code suggestions for a potential fix to the vulnerability for you to review. In this case, it may make code suggestions, like those below, to import a package and update the code related to hashing the password.
190+
191+
```python
192+
from argon2 import PasswordHasher
193+
```
194+
195+
```python
196+
def get_initial_hash(password: str):
197+
ph = PasswordHasher()
198+
return ph.hash(password)
199+
200+
def check_password(password: str, known_hash):
201+
ph = PasswordHasher()
202+
return ph.verify(known_hash, password)
203+
```
204+
205+
> [!NOTE]
206+
> * Always verify and validate any changes {% data variables.product.prodname_copilot_short %} suggests before accepting them.
207+
> * In this example, {% data variables.copilot.copilot_code-review_short %} may also highlight the need to generate unique salts.
208+
209+
As you can see, identifying vulnerabilities automatically, along with suggestions for fixing them, helps you make security a priority. {% data variables.copilot.copilot_autofix_short %} enables you to focus on understanding secure coding and on fixes that work best for your code base and project.
210+
211+
## Optimized reviews with {% data variables.product.prodname_copilot_short %}
212+
213+
Automatic review comments help you optimize your reviews and secure your code more efficiently regardless of your level of experience.
214+
215+
* Custom instructions helped refine the responses from {% data variables.copilot.copilot_code-review_short %} so they were specific to our project and user needs and we also saw how we can tailor how much explanation {% data variables.product.prodname_copilot_short %} provides in feedback.
216+
* {% data variables.copilot.copilot_code-review_short %} helped us quickly improve our error logging and understand why it mattered.
217+
* {% data variables.copilot.copilot_autofix_short %} for {% data variables.product.prodname_code_scanning %} helped us prevent using an insufficient password hashing approach and protect user data.
218+
219+
## Next steps
220+
221+
To make your reviews more efficient and effective using {% data variables.product.prodname_copilot_short %}'s review capabilities, get started by following these steps.
222+
223+
1. Create custom instructions specific to your project and repository. Write your own, or take inspiration from our library of examples. See [AUTOTITLE](/copilot/tutorials/customization-library/custom-instructions).
224+
1. To enable automatic {% data variables.copilot.copilot_code-review_short %} for your repository, see [AUTOTITLE](/copilot/how-tos/use-copilot-agents/request-a-code-review/configure-automatic-review).
225+
1. To configure {% data variables.copilot.copilot_autofix_short %} for your repo you'll need to enable {% data variables.product.prodname_code_scanning %}. Once {% data variables.product.prodname_code_scanning %} with {% data variables.product.prodname_codeql %} analysis is enabled, {% data variables.copilot.copilot_autofix_short %} is enabled by default. For the easiest setup, see [AUTOTITLE](/code-security/code-scanning/enabling-code-scanning/configuring-default-setup-for-code-scanning).
226+
227+
## Further reading
228+
229+
To go deeper with reviewing AI generated code, see [AUTOTITLE](/copilot/tutorials/review-ai-generated-code).
Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,4 @@
11
{% data variables.product.prodname_code_scanning_caps %} is available for the following repository types:
22

3-
{%- ifversion fpt %}
43
* Public repositories on {% data variables.product.prodname_dotcom_the_website %}
5-
* Organization-owned repositories on {% data variables.product.prodname_team %} with [{% data variables.product.prodname_GH_code_security %}](/get-started/learning-about-github/about-github-advanced-security) enabled
6-
7-
{%- elsif ghec %}
8-
* Public repositories on {% data variables.product.prodname_dotcom_the_website %}
9-
* Organization-owned repositories on {% data variables.product.prodname_team %} or {% data variables.product.prodname_ghe_cloud %} with [{% data variables.product.prodname_GH_code_security %}](/get-started/learning-about-github/about-github-advanced-security) enabled
10-
11-
{%- elsif ghes %}
12-
* Organization-owned repositories with [{% data variables.product.prodname_GH_code_security %}](/get-started/learning-about-github/about-github-advanced-security) enabled
13-
14-
{% endif %}
4+
* Organization-owned repositories on {% data variables.product.prodname_team %}, {% data variables.product.prodname_ghe_cloud %}, or {% data variables.product.prodname_ghe_server %}, with [{% data variables.product.prodname_GH_code_security %}](/get-started/learning-about-github/about-github-advanced-security) enabled.

0 commit comments

Comments
 (0)