Code Review với Copilot
1. Tại sao Review Code với AI?
Lợi ích của AI Code Review
| Aspect | Human Review | AI Review |
|---|---|---|
| Speed | Slow (hours/days) | Instant |
| Consistency | Variable | Consistent |
| Availability | Limited | 24/7 |
| Coverage | May miss | Comprehensive |
| Learning | From experience | From patterns |
AI Review bổ sung cho Human Review
- ✅ Catch obvious issues trước
- ✅ Consistent style checking
- ✅ Security vulnerability scan
- ✅ Human reviewer focus vào logic phức tạp
2. Review Methods với Copilot
2.1 Using /explain
Hiểu code trước khi review:
1// Select code, then:2/explain this function in detail, including potential issues2.2 Using Inline Chat
Select code và ask trực tiếp:
1Ctrl+I2> Review this code for:3> - Security vulnerabilities4> - Performance issues5> - Best practices violations2.3 Using @workspace
Review trong context của project:
1@workspace review src/auth/login.ts considering the overall architecture3. Security Review
Common Vulnerabilities
Security Checklist
Prompt Template cho Security Review
1Review this code for security vulnerabilities:2 3Check for:41. SQL Injection52. XSS (Cross-Site Scripting)63. CSRF vulnerabilities74. Hardcoded secrets/credentials85. Insecure random number generation96. Path traversal107. Unvalidated redirects118. Missing input validation12 13For each issue found:14- Describe the vulnerability15- Show the vulnerable code16- Provide the fixExample: SQL Injection Check
Original Code:
1def get_user(username):2 query = f"SELECT * FROM users WHERE username = '{username}'"3 return db.execute(query)Prompt:
1Review this for SQL injectionCopilot Response:
1🚨 SQL INJECTION VULNERABILITY FOUND2 3The code concatenates user input directly into SQL query.4 5Attack Example:6username = "'; DROP TABLE users; --"7 8Fix:9```python10def get_user(username):11 query = "SELECT * FROM users WHERE username = ?"12 return db.execute(query, (username,))Or use ORM:
1def get_user(username):2 return User.query.filter_by(username=username).first()1---2 3## 4. Performance Review4 5### Performance ChecklistReview this code for performance issues:
Check for:
- N+1 query problems
- Unnecessary loops
- Missing indexes
- Memory leaks
- Blocking operations
- Inefficient algorithms (O(n²) when O(n) possible)
- Redundant computations
- Large data in memory
1### Example: N+1 Query Problem2 3**Original Code:**4```python5def get_orders_with_items():6 orders = Order.query.all() # 1 query7 result = []8 for order in orders:9 items = order.items # N queries!10 result.append({11 'order': order,12 'items': items13 })14 return resultCopilot Review:
1🔴 N+1 QUERY PROBLEM2 3Current: 1 + N queries (N = number of orders)4 5Fix: Use eager loading6```python7def get_orders_with_items():8 orders = Order.query.options(9 joinedload(Order.items)10 ).all() # 1 query with JOIN11 12 return [{'order': o, 'items': o.items} for o in orders]1---2 3## 5. Code Quality Review4 5### Clean Code ChecklistReview this code for clean code principles:
Check for:
- Single Responsibility violations
- Long functions (>20 lines)
- Deep nesting (>3 levels)
- Magic numbers
- Unclear naming
- Code duplication
- Missing error handling
- Incomplete documentation
1### Example Review2 3**Original Code:**4```javascript5function p(d) {6 let t = 0;7 for (let i = 0; i < d.length; i++) {8 if (d[i].s === 1) {9 if (d[i].a > 100) {10 t += d[i].a * 0.9;11 } else {12 t += d[i].a;13 }14 }15 }16 return t;17}Copilot Review:
1Code Quality Issues:2 31. 📛 Unclear Naming4 - `p` → `calculateTotalActiveAmount`5 - `d` → `dataItems`6 - `s` → `status`7 - `a` → `amount`8 - `t` → `total`9 102. 🔢 Magic Numbers11 - `1` → `STATUS_ACTIVE`12 - `100` → `DISCOUNT_THRESHOLD`13 - `0.9` → `DISCOUNT_RATE`14 153. 📚 Missing Documentation16 17Fixed Version:18```javascript19const STATUS_ACTIVE = 1;20const DISCOUNT_THRESHOLD = 100;21const DISCOUNT_RATE = 0.9;22 23/**24 * Calculates total amount for active items with bulk discount25 * @param {Array} items - List of items with status and amount26 * @returns {number} Total amount after discounts27 */28function calculateTotalActiveAmount(items) {29 return items30 .filter(item => item.status === STATUS_ACTIVE)31 .reduce((total, item) => {32 const amount = item.amount > DISCOUNT_THRESHOLD33 ? item.amount * DISCOUNT_RATE34 : item.amount;35 return total + amount;36 }, 0);37}1---2 3## 6. Review Specific Patterns4 5### 6.1 Error Handling ReviewReview error handling in this code:
- Are all errors caught?
- Are errors logged properly?
- Are user-facing messages safe (no sensitive data)?
- Is there proper cleanup on error?
1### 6.2 API Design ReviewReview this API for:
- RESTful conventions
- Proper status codes
- Input validation
- Response format consistency
- Error response format
1### 6.3 Database Code ReviewReview this database code for:
- Transaction handling
- Connection management
- Query efficiency
- Data integrity
- Race conditions
1### 6.4 Frontend Code ReviewReview this React component for:
- Unnecessary re-renders
- Memory leaks (missing cleanup)
- Accessibility (a11y)
- State management
- Props validation
1---2 3## 7. Review Workflow4 5### Step-by-step Review Process6 7```markdown8## Code Review Checklist9 10### 1. Functionality11- [ ] Does it work as expected?12- [ ] Edge cases handled?13- [ ] Error states handled?14 15### 2. Security16- [ ] Input validation?17- [ ] No sensitive data exposed?18- [ ] Proper authentication/authorization?19 20### 3. Performance21- [ ] Efficient algorithms?22- [ ] No unnecessary operations?23- [ ] Proper caching?24 25### 4. Maintainability26- [ ] Clear naming?27- [ ] Proper documentation?28- [ ] No code duplication?29 30### 5. Testing31- [ ] Tests exist?32- [ ] Tests pass?33- [ ] Edge cases tested?Quick Review Command
Tạo command tổng hợp:
1@workspace Review the staged changes:2 31. Security check42. Performance check53. Code quality check64. Test coverage check7 8Format: 9- 🔴 Critical: Must fix10- 🟡 Warning: Should fix11- 🟢 Suggestion: Nice to have8. Automated Review Integration
Pre-commit Review
Tạo script để review trước khi commit:
1# pre_commit_review.py2import subprocess3import sys45def get_staged_files():6 result = subprocess.run(7 ['git', 'diff', '--staged', '--name-only'],8 capture_output=True, text=True9 )10 return result.stdout.strip().split('\n')1112def review_file(filepath):13 # Use Copilot CLI or API for automated review14 print(f"Reviewing: {filepath}")15 # Integration code here1617if __name__ == "__main__":18 files = get_staged_files()19 issues = []20 21 for f in files:22 if f.endswith(('.py', '.js', '.ts')):23 issues.extend(review_file(f))24 25 if any(i['severity'] == 'critical' for i in issues):26 print("❌ Critical issues found. Fix before committing.")27 sys.exit(1)28 29 print("✅ Review passed")GitHub Actions Integration
1# .github/workflows/code-review.yml2name: AI Code Review3 4on:5 pull_request:6 branches: [main]7 8jobs:9 review:10 runs-on: ubuntu-latest11 steps:12 - uses: actions/checkout@v413 14 - name: AI Code Review15 uses: github/copilot-code-review-action@v116 with:17 github-token: ${{ secrets.GITHUB_TOKEN }}9. Review Response Patterns
Constructive Feedback Format
Khi nhận review từ Copilot, reformat để share với team:
1## Code Review: feature/user-auth2 3### Summary4Overall: 🟡 Needs minor fixes5 6### Issues Found7 8#### 🔴 Critical (1)91. **SQL Injection in login.py:45**10 - Issue: User input concatenated in query11 - Fix: Use parameterized queries12 13#### 🟡 Warning (2)141. **Missing error handling in auth_service.py:78**152. **Hardcoded timeout value in config.py:12**16 17#### 🟢 Suggestions (3)181. Consider adding docstrings to public methods192. Could simplify the conditional at line 89203. Unit test coverage could be improved21 22### Recommended Actions231. Fix SQL injection immediately242. Add error handling before merge253. Address suggestions in follow-up PR10. Hands-on Exercise
Challenge: Security Review
Review đoạn code sau và tìm tất cả security issues:
1const express = require('express');2const app = express();34app.post('/login', (req, res) => {5 const { username, password } = req.body;6 7 // Check credentials8 const query = `SELECT * FROM users 9 WHERE username='${username}' 10 AND password='${password}'`;11 12 db.query(query, (err, results) => {13 if (results.length > 0) {14 const token = username + Date.now();15 res.cookie('auth', token);16 res.redirect('/dashboard?user=' + username);17 } else {18 res.send('Invalid credentials for ' + username);19 }20 });21});2223app.get('/profile/:id', (req, res) => {24 const userId = req.params.id;25 const userData = fs.readFileSync('./users/' + userId + '.json');26 res.json(JSON.parse(userData));27});Task:
- Sử dụng Copilot để identify tất cả vulnerabilities
- List các issues theo severity
- Provide fixed version cho từng issue
Expected Issues:
- SQL Injection
- Plain text password storage
- Weak session token
- XSS in error message
- Open redirect
- Path traversal
- Missing input validation
Tiếp theo
Bài tiếp theo: Refactoring với Copilot - cải thiện code structure, clean up tech debt, và modernize codebase!
