Skip to main content

Git集成

Git版本控制是现代软件开发的基础。Claude Code与Git深度集成,不仅能执行常见的Git操作,还能理解你的代码变更意图,自动生成规范的提交信息,智能处理代码审查,甚至协助创建和管理Pull Request。

这篇文章介绍Claude Code的Git集成能力,帮你建立高效的版本控制工作流。

Git状态查看

实时状态监控

Claude Code会自动跟踪Git仓库状态变化:

查看当前Git状态

Claude Code会提供清晰的状态报告:

📊 Git Repository Status

Branch: main (ahead of origin/main by 2 commits)

📝 Staged Changes (3 files):
✓ src/components/Button.jsx (Modified)
✓ src/utils/helpers.js (Modified)
✓ tests/Button.test.js (Modified)

📄 Unstaged Changes (2 files):
~ src/App.js (Modified)
~ src/config.js (Modified)

❓ Untracked Files (4 files):
? src/components/NewFeature.jsx
? src/styles/newtheme.css
? .env.local
? docs/notes.md

Recent commits:
a3b2c1d (2 hours ago) Add dark mode support
f9e8d7c (5 hours ago) Fix authentication bug
e6a5b4c (1 day ago) Update dependencies

Would you like me to:
1. Review the staged changes
2. Commit the staged changes
3. Stage all changes
4. Create a new branch

智能变更分析

Claude Code不只列出文件,还能分析变更内容:

分析一下当前所有的改动
🔍 Change Analysis

Summary: 9 files changed across 3 categories

1. Feature Implementation (2 files):
✓ NewFeature.jsx - Complete new component (245 lines)
✓ newtheme.css - Dark theme styles (89 lines)

2. Bug Fixes (2 files):
✓ Button.jsx - Fixed hover state bug (3 lines changed)
✓ helpers.js - Fixed date formatting (5 lines changed)

3. Refactoring (3 files):
✓ App.js - Improved component structure (23 lines changed)
✓ config.js - Centralized configuration (15 lines changed)
✓ Button.test.js - Added missing tests (34 lines added)

Risk Level: 🟢 Low
- No breaking changes detected
- All changes are backward compatible
- Test coverage: 95%

Recommendations:
✓ Safe to commit together
💡 Consider splitting into 2 commits:
1. Bug fixes (can be deployed quickly)
2. New features (can be tested separately)

对比传统方式

传统方式:

git status
# 输出难以理解,需要自己判断文件状态
# 不知道具体改了什么
# 无法判断变更的影响范围

Claude Code方式:

这些改动会影响哪些功能?

Claude Code会:

  1. 分析代码变更的影响
  2. 识别可能的问题
  3. 建议测试策略
  4. 评估合并风险

智能提交(Smart Commit)

自动生成提交信息

这是Claude Code最强大的功能之一:

帮我提交当前的更改

Claude Code会:

  1. 并行运行Git命令收集信息
  2. 分析所有变更
  3. 生成规范的提交信息
I'll create a commit with your changes.

📊 Analyzing changes...

✓ Found 5 modified files
✓ Analyzed 127 lines changed
✓ Identified 3 feature additions

✏️ Drafting commit message...

Subject: Add user authentication feature

Body:
- Implement login/logout functionality with JWT tokens
- Add protected route middleware for authenticated pages
- Create user profile management component
- Update API integration with authentication endpoints
- Add comprehensive unit tests for auth flow

Technical Details:
- Frontend: Added AuthContext and useAuth hook
- Backend: Integrated JWT token refresh mechanism
- Security: Implemented token storage in httpOnly cookies
- Testing: Added 12 new test cases (98% coverage)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude (noreply@anthropic.com)

✓ Commit created successfully: a3b2c1d

自定义提交信息风格

你可以指定提交信息的格式:

使用Conventional Commits格式提交
feat(auth): implement user authentication flow

- add login and logout functionality
- implement JWT token management
- create protected route middleware
- add user profile component

BREAKING CHANGE: requires API v2.0+

Co-Authored-By: Claude (noreply@anthropic.com)

✓ Commit created: f8e7d6c

分阶段提交

对于复杂的更改,可以分批提交:

先把bug修复提交了,新功能稍后再提交

Claude Code会智能分类:

📊 Separating changes...

Bug Fixes (staging):
✓ src/utils/date.js - Fixed timezone issue
✓ src/components/Button.jsx - Fixed hover bug

Committing bug fixes...

fix: resolve timezone and button hover bugs

- Fix date parsing timezone offset issue
- Fix button hover state not updating correctly

✓ Committed: a1b2c3d

Remaining changes (not committed):
~ src/features/Auth.jsx - New authentication feature
~ src/features/Profile.jsx - New profile page

Ready to commit features when you're ready

交互式提交

Claude Code支持更细粒度的控制:

帮我提交更改,但.env.local不要提交
✓ Staging files...
✓ src/App.js
✓ src/components/*.jsx
✓ src/utils/*.js

⚠️ Excluded from commit:
🔒 .env.local (contains sensitive data)

✓ Commit created: b2c3d4e

💡 Suggestion:
Add .env.local to .gitignore if you haven't already

提交前检查

Claude Code会自动进行安全检查:

提交当前更改

如果有问题:

⚠️ Pre-commit Checks

Issues found:

1. Security Alert:
🔴 .env.local staged - contains API keys!
→ Action: Removed from staging

2. Code Quality:
🟡 console.log found in src/App.js (line 45)
→ Suggestion: Replace with logger

3. Testing:
🟡 New component lacks tests: UserWidget.jsx
→ Suggestion: Add test file

Proceed with commit?
[1] Yes, commit anyway
[2] Fix issues first (recommended)
[3] Show me the details

代码审查

自动代码审查

每次提交前,Claude Code都会进行代码审查:

帮我审查一下这次的更改
🔍 Code Review Report

Changed Files: 4
Total Lines: +156 -23

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. src/components/UserProfile.jsx
✓ Good: Clean component structure
✓ Good: Proper error handling
⚠️ Warning: Missing prop validation for 'userId'
💡 Suggestion: Add PropTypes or TypeScript

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

2. src/api/userApi.js
✓ Good: Consistent naming
✓ Good: Comprehensive error messages
🔴 Critical: API key exposed in code!
→ Line 15: const API_KEY = 'sk-1234567890'
💡 Action: Move to environment variable

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

3. src/utils/validation.js
✓ Good: Pure functions
✓ Good: Good test coverage
⚠️ Warning: Regex may be vulnerable to ReDoS
→ Line 45: Complex email validation regex
💡 Suggestion: Use validator library

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

4. tests/user.test.js
✓ Good: Comprehensive test cases
✓ Good: Clear test descriptions
⚠️ Warning: Missing edge case tests
💡 Suggestion: Add tests for null/undefined inputs

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Overall Score: 7/10

Critical Issues: 1 (must fix)
Warnings: 3 (should fix)
Suggestions: 4 (nice to have)

Recommendations:
1. 🔴 URGENT: Remove API key before committing
2. Add prop validation to UserProfile component
3. Simplify email validation regex
4. Add edge case tests

Would you like me to:
1. Fix the critical issues automatically
2. Fix all issues
3. Guide you through fixing them manually

PR(Pull Request)审查

创建PR时,Claude Code能提供专业审查:

帮我审查PR #123
📋 Pull Request Review: #123 - Add payment integration

Overview:
+245 lines, -89 lines across 12 files
Author: @developer
Base: main ← Feature: payment-gateway

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

✅ Strengths:
• Clean architecture - well separated concerns
• Good error handling throughout
• Comprehensive test coverage (94%)
• Clear documentation in code comments

⚠️ Issues to Address:

🔴 High Priority:
1. Security: Payment token stored in localStorage
Location: src/services/payment.js:67
Risk: XSS vulnerability
Fix: Use httpOnly cookies or backend session

2. Error Handling: Missing retry logic for API failures
Location: src/api/payment.js:34
Impact: Payment may fail on network blip
Fix: Implement exponential backoff retry

🟡 Medium Priority:
3. Performance: Re-renders on every state change
Location: src/components/Checkout.jsx
Fix: useMemo/useCallback optimization

4. Testing: Missing test for refund flow
Location: tests/payment.test.js
Fix: Add refund test case

🟢 Low Priority:
5. Code Style: Inconsistent naming (pay_payment vs payment)
6. Documentation: Missing API endpoint docs

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Security Scan:
🔴 1 critical vulnerability found
🟡 2 potential issues identified

Performance Impact:
• Bundle size: +45KB (acceptable)
• Runtime performance: No significant impact

Breaking Changes:
• None - backward compatible

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Recommendation: ❌ Request Changes

Required fixes before merge:
1. Fix security issue with token storage
2. Add retry logic for API calls

Optional improvements:
3. Performance optimization
4. Add missing tests

📝 Review Comment Template:
[Ready to paste into PR]

Would you like me to:
1. Generate detailed review comments
2. Fix the issues automatically
3. Create follow-up issues

对比传统审查流程

传统方式:

  1. 手动打开每个文件
  2. 逐行阅读代码
  3. 容易遗漏问题
  4. 审查意见不统一
  5. 耗时且易出错

Claude Code方式:

全面审查这次改动,特别关注安全性和性能

Claude Code会:

  1. 自动扫描所有变更
  2. 应用最佳实践检查
  3. 识别常见反模式
  4. 提供具体的修复建议
  5. 生成标准审查报告

分支管理

智能分支创建

我要开发一个新功能:用户头像上传
🌿 Creating feature branch...

✓ Created branch: feature/user-avatar-upload
Based on: main (at commit a3b2c1d)

Branch setup:
✓ Switched to new branch
✓ Created feature branch configuration
✓ Set up tracking with origin

📋 Feature Development Checklist:
☐ Implement avatar upload component
☐ Add image validation
☐ Integrate with storage API
☐ Add loading states
☐ Implement error handling
☐ Write unit tests
☐ Update documentation

Ready to start development! 🚀

Tips for this feature:
• Consider image size limits (max 5MB recommended)
• Support common formats: JPEG, PNG, WebP
• Implement client-side preview
• Add progress indicator for uploads

分支对比

对比当前分支和main分支的差异
🔍 Branch Comparison: feature/user-avatar-upload vs main

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Statistics:
Files changed: 7
Insertions: +342
Deletions: -45
Net change: +297 lines

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

New Files (3):
✓ src/components/AvatarUpload.jsx (187 lines) - NEW
✓ src/utils/imageValidator.js (45 lines) - NEW
✓ src/hooks/useAvatarUpload.js (67 lines) - NEW

Modified Files (4):
~ src/pages/Profile.jsx - Integrated avatar upload
~ src/api/userApi.js - Added upload endpoint
~ src/styles/profile.css - Avatar styling
~ tests/user.test.js - Added tests

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Code Quality:
✓ All new files follow project conventions
✓ Test coverage: 92%
✓ No breaking changes to existing APIs

Merge Readiness: 🟢 Ready

Potential conflicts: None detected

Recommended next steps:
1. Run full test suite: npm test
2. Check bundle size impact
3. Create pull request

Would you like me to:
1. Run the tests
2. Create a pull request
3. Continue development

分支切换

切换到feature/login页面
🔄 Switching branches...

⚠️ Warning: You have uncommitted changes:

Modified:
src/App.js
src/styles/main.css

Options:
[1] Stash changes and switch
[2] Commit changes and switch
[3] Discard changes and switch
[4] Cancel

Recommended: Option 1 (stash)

Selected: 1

✓ Changes stashed: WIP on main
✓ Switched to branch 'feature/login'
✓ Branch is up to date with origin/feature/login

Your stash is saved. Apply it later with:
git stash pop

分支清理

清理已合并的分支
🧹 Cleaning up branches...

Analyzing branches...

Local branches (8):
✓ main (active)
✓ feature/user-avatar
✓ feature/login (merged)
✓ feature/payment (merged)
✓ bugfix/auth-error (merged)
✓ experiment/new-ui (stale)
✓ hotfix/critical-bug (merged)
✓ refactor/api-calls (merged)

Remote branches (10):
✓ origin/main
✓ origin/feature/user-avatar
✓ origin/feature/login (merged)
... (7 more)

Safe to delete (already merged):
• feature/login
• feature/payment
• bugfix/auth-error
• hotfix/critical-bug
• refactor/api-calls

Potentially stale:
⚠️ experiment/new-ui (last commit: 3 months ago)
→ No merge commit found
→ May contain useful work
→ Recommendation: Review before deleting

Delete merged branches? [Y/n]
Y

✓ Deleted local branches: 5
✓ Pruned remote branches: 7

💡 Kept: experiment/new-ui (review recommended)

Remaining branches: 2
• main
• feature/user-avatar (active development)

冲突解决

智能冲突检测

在合并前预测冲突:

检查feature分支合并到main是否会有冲突
🔍 Conflict Analysis: feature/user-avatar → main

Checking for potential conflicts...

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Merge Analysis:

Status: 🟡 Minor conflicts expected

Files with conflicts (2):

1. src/pages/Profile.jsx
Conflict Type: Same line modifications
Your changes: Added avatar upload UI
Their changes: Refactored component structure
Resolution complexity: Medium

Diff:
<<<<<<< feature/user-avatar
<AvatarUpload onUpload={handleAvatarChange} />
=======
<ProfileHeader user={user} />
>>>>>>> main

2. src/api/userApi.js
Conflict Type: Adjacent line changes
Your changes: Added uploadAvatar function
Their changes: Modified getUser function
Resolution complexity: Low
→ Can be auto-merged

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Resolution Strategy:

For src/pages/Profile.jsx:
Option 1: Keep both changes (recommended)
- Merge avatar upload with new structure
- Place AvatarUpload in appropriate location

Option 2: Accept theirs
- Use refactored structure
- Manually add avatar upload later

Option 3: Accept yours
- Keep avatar upload
- Delay refactoring

Recommendation: Option 1 - Merge both changes

Would you like me to:
1. Perform merge and auto-resolve what's possible
2. Show detailed merge plan
3. Wait for you to sync main branch first

自动解决冲突

合并feature分支到main,自动解决冲突
🔀 Merging feature/user-avatar into main...

✓ Fetching latest changes...
✓ Attempting merge...

⚠️ Merge conflicts detected in 2 files

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

1. src/pages/Profile.jsx

CONFLICT:
<<<<<<< feature/user-avatar
return (
<div className="profile">
<AvatarUpload onUpload={handleAvatarUpload} />
<UserDetails user={user} />
</div>
)
=======
return (
<div className="profile">
<ProfileHeader user={user} />
<UserDetails user={user} />
<ProfileSettings user={user} />
</div>
)
>>>>>>> main

🤖 Auto-Resolution:
Merging both versions:

return (
<div className="profile">
<ProfileHeader user={user} />
<AvatarUpload onUpload={handleAvatarUpload} />
<UserDetails user={user} />
<ProfileSettings user={user} />
</div>
)

✓ Resolved: Combined both changes logically
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

2. src/api/userApi.js

CONFLICT:
<<<<<<< feature/user-avatar
export async function uploadAvatar(userId, file) {
// Implementation...
}
=======
export async function getUser(userId) {
// Updated implementation...
}
>>>>>>> main

🤖 Auto-Resolution:
No actual conflict - different functions
✓ Resolved: Kept both functions

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

✓ All conflicts resolved automatically
✓ Changes staged
✓ Ready for merge commit

Merge commit message:
Merge branch 'feature/user-avatar' into main

- Integrated avatar upload functionality
- Merged with profile page refactoring
- Auto-resolved 2 conflicts (no manual intervention needed)

Commit? [Y/n]
Y

✓ Merge successful: c4d5e6f

Would you like to:
1. Push to remote
2. Delete feature branch
3. Run tests to verify merge

手动冲突解决指导

对于复杂的冲突,Claude Code会提供指导:

帮我解决这个Git冲突
🔧 Conflict Resolution Guide

File: src/components/UserList.jsx
Status: Conflicting changes on same lines

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Understanding the Conflict:

Current branch (feature/search):
Added search functionality with real-time filtering
+23 lines, -3 lines

Incoming branch (main):
Refactored to use TypeScript
+45 lines, -15 lines

Conflict details:
Both branches modified the same component structure
Need to merge search logic with TypeScript types

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Step-by-Step Resolution:

Step 1: Accept TypeScript structure (main)
✓ Type definitions are important
✓ Keep the new interfaces

Step 2: Add search functionality
✓ Port search logic to TypeScript
✓ Add proper types for search params

Step 3: Update imports
✓ Ensure all imports are correct

Step 4: Test the merged version

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Proposed Resolution:

```typescript
interface UserListProps {
users: User[];
onUserSelect: (user: User) => void;
searchable?: boolean; // NEW from feature branch
}

export function UserList({ users, onUserSelect, searchable = false }: UserListProps) {
const [searchQuery, setSearchQuery] = useState('');

// Search logic from feature branch (converted to TypeScript)
const filteredUsers = useMemo(() => {
if (!searchable || !searchQuery) return users;

return users.filter(user =>
user.name.toLowerCase().includes(searchQuery.toLowerCase())
);
}, [users, searchQuery, searchable]);

return (
<div className="user-list">
{searchable && (
<SearchInput
value={searchQuery}
onChange={setSearchQuery}
/>
)}
{filteredUsers.map(user => (
<UserCard
key={user.id}
user={user}
onClick={() => onUserSelect(user)}
/>
))}
</div>
);
}

This resolution: ✓ Keeps TypeScript types (from main) ✓ Adds search functionality (from feature) ✓ Maintains backward compatibility ✓ Follows project conventions

Apply this resolution? [Y/n] Y

✓ Conflict resolved ✓ File updated ✓ Changes staged

Next: Resolve remaining conflicts or complete merge


## PR创建和管理

### 智能PR创建

为feature/user-avatar创建一个PR

📝 Creating Pull Request...

Analyzing branch: feature/user-avatar → main

✓ Fetching branch information... ✓ Comparing changes... ✓ Generating PR description...

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Pull Request Draft:

Title: ✨ Add user avatar upload functionality

Description:

Summary

Implemented complete user avatar upload functionality with image validation, preview, and storage integration.

Changes

  • ✅ New avatar upload component with drag-and-drop support
  • ✅ Client-side image validation (size, format, dimensions)
  • ✅ Integration with cloud storage API
  • ✅ Real-time upload progress indicator
  • ✅ Error handling and user feedback
  • ✅ Avatar preview and crop functionality
  • ✅ Comprehensive unit tests (92% coverage)

Technical Details

  • Component: AvatarUpload.jsx (187 lines)
  • Hook: useAvatarUpload.js (67 lines)
  • Validator: imageValidator.js (45 lines)
  • API Integration: Cloud storage service
  • State Management: React hooks

Files Changed

  • 7 files changed, 342 insertions(+), 45 deletions(-)
  • New files: 3
  • Modified files: 4

Testing

  • ✅ Unit tests: 47 test cases, all passing
  • ✅ Integration tests: API upload flow
  • ✅ Manual testing: Chrome, Firefox, Safari
  • ✅ Edge cases: Large files, invalid formats, network errors

Screenshots

[Avatar upload component - drag and drop UI] [Upload progress indicator] [Avatar preview and crop modal]

Checklist

  • Code follows project style guidelines
  • Self-review completed
  • Unit tests added/updated
  • Documentation updated
  • No new warnings
  • Bundle size impact acceptable (+45KB)
  • Accessibility tested
  • Ready for review

Closes #123 - User avatar feature request

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Reviewers requested:

  • @senior-dev (code review)
  • @frontend-lead (architecture review)

Labels:

  • feature
  • enhancement
  • needs-review

Milestone: v2.0.0

Create this PR? [Y/n] Y

✓ Pull request created successfully! 🔗 PR #142: https://github.com/repo/pull/142

Would you like me to:

  1. Add more reviewers
  2. Set up auto-merge conditions
  3. Create follow-up issues
  4. Notify team members

### PR更新和管理

更新PR #142,添加最新的改动

🔄 Updating Pull Request #142...

Current status: ✅ Open 📊 Changes: 7 files, +342/-45 💬 3 comments, 2 approvals

New changes detected: ✓ src/components/AvatarUpload.jsx (Modified) ✓ tests/avatar.test.js (Added test cases)

Generating update message...

Update comment:

🔄 PR Update

Added requested changes from code review:

Changes in this update:

  1. Fixed accessibility issue

    • Added keyboard navigation support
    • Improved screen reader announcements
    • Fixed ARIA labels
  2. Enhanced error handling

    • Better error messages for users
    • Graceful fallback for older browsers
    • Network timeout handling
  3. Additional test coverage

    • Added 8 new test cases
    • Edge case coverage: 98%
    • Performance tests included

Review feedback addressed:

  • ✅ @senior-dev: Added keyboard support
  • ✅ @frontend-lead: Fixed performance issue
  • ✅ @accessibility: Improved ARIA labels

Updated metrics:

  • Test coverage: 92% → 98%
  • Performance: Lighthouse score 95+
  • Accessibility: WCAG AA compliant

Ready for re-review! 🎯

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

✓ PR updated successfully ✓ Comment posted ✓ Reviewers notified

Updated PR: 🔗 https://github.com/repo/pull/142

Would you like to:

  1. Request specific re-review
  2. Mark as ready for merge
  3. Address remaining comments

### PR合并策略

PR #142已经通过审查,帮我合并

✅ PR #142 Review Status

Approvals: 2/2 required ✅ @senior-dev - Approved ✅ @frontend-lead - Approved

CI/CD Status: All checks passing ✅ Tests: 47/47 passing ✅ Lint: No issues ✅ Build: Success ✅ Security: No vulnerabilities

Merge Strategy Selection:

Available options:

  1. Merge commit (create merge commit)
  2. Squash and merge (combine into one commit)
  3. Rebase and merge (rebase on main)

Recommended: Squash and merge

Reasons for squash merge: ✓ Cleaner history (one commit instead of 12) ✓ Comprehensive commit message ✓ Preserves all changes ✓ Easier to revert if needed ✓ Best practice for feature branches

Squash commit message:

feat: add user avatar upload functionality

Implement complete avatar upload system with image validation, preview, and cloud storage integration.

Features:

  • Drag-and-drop upload interface
  • Client-side image validation (size, format, dimensions)
  • Real-time upload progress with error handling
  • Avatar preview and crop functionality
  • Keyboard navigation and screen reader support
  • 98% test coverage, WCAG AA compliant

Technical details:

  • New components: AvatarUpload, ImagePreview, CropModal
  • Storage integration: Cloud service API
  • State management: React hooks with context
  • Performance: Optimized for 5MB+ images

Files changed:

  • 7 files modified
  • 342 insertions, 45 deletions
  • 3 new components, 4 modified files

Closes #123

🤖 Generated with Claude Code

Co-Authored-By: Claude (noreply@anthropic.com)

Proceed with squash merge? [Y/n] Y

✓ Fetching latest main... ✓ Squashing commits... ✓ Creating merge commit... ✓ Updating branch... ✓ Pushing to remote...

✅ PR merged successfully! ✓ Feature branch deployed to production

Post-merge actions: ✓ Deleted feature branch ✓ Created v2.0.0 release tag ✓ Notified team in Slack ✓ Updated project roadmap

Would you like to:

  1. View merged changes
  2. Start next feature
  3. Create retrospective notes

## 与Git工作流集成

### Git Flow工作流

使用Git Flow开始一个新的功能分支

🌿 Git Flow: Starting New Feature

Current configuration: Production branch: main Development branch: develop Feature branch prefix: feature/ Release branch prefix: release/ Hotfix branch prefix: hotfix/

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Creating feature branch...

✓ Fetched latest from origin � Branched from: develop (at d4e5f6a) � Created: feature/user-dashboard

Branch setup: 📊 Tracking: origin/feature/user-dashboard 📝 Base version: v1.2.0-develop 🎯 Target release: v1.3.0

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Feature Development Template:

Feature: User Dashboard

Objectives:

[ ] Create main dashboard layout [ ] Implement widget system [ ] Add data visualization [ ] Set up real-time updates

Technical Stack:

  • React with TypeScript
  • Chart.js for visualization
  • WebSocket for real-time data
  • Tailwind CSS for styling

Development Checklist:

☐ Set up component structure ☐ Implement dashboard layout ☐ Create widget components ☐ Integrate data APIs ☐ Add unit tests ☐ Add integration tests ☐ Update documentation ☐ Performance testing

Definition of Done:

✓ All code reviewed ✓ Unit test coverage > 80% ✓ Integration tests passing ✓ Documentation complete ✓ Performance benchmarks met ✓ No security vulnerabilities ✓ Accessibility compliant

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Ready to start! 🚀

Quick commands for this feature: git flow feature finish user-dashboard # Complete feature git flow feature publish user-dashboard # Share with team

Estimated effort: 3-5 days Suggested reviewers: @frontend-lead, @ux-designer


### GitHub Flow工作流

使用GitHub Flow提交一个紧急修复

🔥 Hotfix Flow: Critical Bug Fix

Issue: Production auth token expiration bug Severity: 🔴 Critical Impact: Users being logged out unexpectedly

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Creating hotfix branch...

✓ Based on: main (production) ✓ Created: hotfix/auth-token-fix

Hotfix protocol: ⚠️ Minimal changes only ⚠️ Must include tests ⚠️ Requires immediate review ⚠️ Fast-track to production

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Analyzing the bug...

Root cause identified: File: src/utils/auth.js Line: 45 Issue: Token expiration not checked properly

Proposed fix:

// Before:
function isTokenValid(token) {
return token && token.expiresAt > Date.now();
}

// After:
function isTokenValid(token) {
if (!token) return false;
// Add buffer time (5 minutes)
const expirationBuffer = 5 * 60 * 1000;
return token.expiresAt > (Date.now() + expirationBuffer);
}

Impact: ✓ Low risk change ✓ No breaking changes ✓ Backward compatible ✓ Easy to rollback

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Implementing hotfix...

✓ Fixed token validation logic ✓ Added unit test for expiration edge case ✓ Verified fix in staging environment ✓ Checked for similar issues (found 0)

Creating PR...

fix: resolve auth token premature expiration

Critical fix for authentication bug causing unexpected logouts.

Changes:

  • Added 5-minute buffer to token expiration check
  • Prevents users from being logged out during active sessions
  • Added unit test for edge case

Testing:

  • ✓ Unit tests passing
  • ✓ Manual testing in staging
  • ✓ Verified no regression

Risk: Low Impact: High (fixes critical UX issue) Deploy: Immediate

🤖 Generated with Claude Code

Co-Authored-By: Claude (noreply@anthropic.com)

✓ PR created: #157 ✓ Requested urgent review from @tech-lead ✓ CI/CD checks passed

Waiting for approval... (1 minute later) ✓ Approved by @tech-lead ✓ Auto-merged to main ✓ Deployed to production

✅ Hotfix complete! Total time: 8 minutes

Post-deployment: ✓ Monitoring production logs ✓ Zero errors since deployment ✓ User sessions stable

Would you like to:

  1. Schedule follow-up refactor
  2. Create incident report
  3. Monitor metrics

### Trunk-Based Development

提交到主分支,使用trunk-based开发

🌳 Trunk-Based Development Commit

Analyzing changes for main branch...

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Pre-commit Checks:

✓ Code Quality:

  • No linting errors
  • TypeScript compilation successful
  • Code follows style guide

✓ Testing:

  • All unit tests passing (87/87)
  • Integration tests passing (23/23)
  • Test coverage: 88%

✓ Build:

  • Production build successful
  • Bundle size: -12KB (optimization)
  • No new vulnerabilities

✓ Documentation:

  • JSDoc comments added
  • README updated
  • CHANGELOG.md updated

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Commit strategy: ✅ Small, frequent commits ✅ Each commit is production-ready ✅ Feature flags for incomplete features ✅ Automated tests always passing

This commit: Feature: Advanced search filters Size: Small (one logical change) Risk: Low (isolated feature) Status: Production-ready

✓ Tests: 5 new test cases ✓ Docs: API documentation updated ✓ Feature flag: FEATURE_ADVANCED_SEARCH=true

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Creating commit...

feat(search): add advanced filtering with category and date range

Implements advanced search functionality:

  • Category multi-select filter
  • Date range picker with presets
  • Saved search queries
  • URL search state persistence

Technical:

  • New component: SearchFilters
  • State: URL query params
  • Feature flag: FEATURE_ADVANCED_SEARCH
  • Tests: 5 new cases
  • Coverage: 95%

Status: Production-ready ✅ Feature flag: Disabled by default

🤖 Generated with Claude Code

Co-Authored-By: Claude (noreply@anthropic.com)

✓ Committed to main: f8g9h0i

Automated actions: ✓ CI/CD pipeline started ✓ Running full test suite... ✓ Deploying to staging... ✓ Running integration tests...

(3 minutes later) ✅ All checks passed ✅ Deployed to production (feature flag disabled)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

To enable this feature in production:

  1. Test in staging with flag enabled
  2. Gradual rollout (10% → 50% → 100%)
  3. Monitor metrics and errors
  4. Full rollout if stable

Enable command: export FEATURE_ADVANCED_SEARCH=true

Next steps: • Monitor production metrics • Enable feature flag for testing • Gather user feedback


## 实用技巧和最佳实践

### 技巧1: 提交前自动检查

设置自动的提交前检查:

设置提交前自动运行测试和lint

🔧 Setting up pre-commit hooks...

Installing Husky... ✓ Configured .husky directory

Creating pre-commit hook...

#!/bin/sh . "$(dirname "$0")/_/husky.sh"

echo "🔍 Running pre-commit checks..."

Run linting

echo "📋 Checking code style..." npm run lint if [ $? -ne 0 ]; then echo "❌ Linting failed. Please fix linting errors." exit 1 fi

Run tests

echo "🧪 Running tests..." npm test -- --passWithNoTests if [ $? -ne 0 ]; then echo "❌ Tests failed. Please fix failing tests." exit 1 fi

Check types

echo "📝 Type checking..." npm run type-check if [ $? -ne 0 ]; then echo "❌ Type errors found. Please fix type errors." exit 1 fi

echo "✅ All checks passed! Proceeding with commit..."

✓ Pre-commit hook installed

Test configuration: 📋 Linting: ESLint with Prettier 🧪 Testing: Jest with coverage 📝 Types: TypeScript strict mode

Now every commit will automatically: ✓ Check code style ✓ Run all tests ✓ Verify types ✓ Prevent broken code from being committed


### 技巧2: 智能提交信息

使用模板生成一致的提交信息:

创建提交信息模板

📝 Creating commit message template...

Created .gitmessage:

type: [subject]

│ │ │

│ │ └─⫸ Summary in imperative mood, no period at end

│ │

│ └─⫸ Commit scope: components|api|docs|tests|build|tools

└─⫸ Commit type: feat|fix|docs|style|refactor|test|chore

--- COMMIT MESSAGE START (lines below will be kept) ---

Explain why this change is being made

(optional) Describe what changed

(optional) List any related issue numbers

--- FOOTER START ---

Breaking changes: List any breaking changes here

Deprecated: List any deprecated features

Closes: #issue-number

--- COMMIT MESSAGE END ---

Configured Git to use template: git config commit.template .gitmessage

✓ Template created and configured

Usage: git commit

Git will open editor with template

Fill in the details and save

Example commit:

feat(auth): add OAuth2 integration

Implemented OAuth2 authentication with Google and GitHub providers.

  • Added OAuth flow handler
  • Created callback endpoint
  • Updated user model to store OAuth data
  • Added comprehensive tests

Breaking changes: None Closes #123 🤖 Generated with Claude Code

Co-Authored-By: Claude (noreply@anthropic.com)


### 技巧3: 自动化分支命名

建立一致的分支命名规范:

创建功能分支时使用标准命名

🌿 Branch Naming Convention

Establishing branch naming rules...

✓ Created branch validation hook ✓ Documented naming patterns

Branch Types:

  1. feature/ - New features Pattern: feature/[feature-name] Examples: ✓ feature/user-authentication ✓ feature/payment-gateway ✓ feature/dark-mode

  2. bugfix/ - Bug fixes Pattern: bugfix/[bug-description] Examples: ✓ bugfix/login-timeout ✓ bugfix/memory-leak ✓ bugfix/validation-error

  3. hotfix/ - Urgent production fixes Pattern: hotfix/[issue]-[description] Examples: ✓ hotfix/123-crash-on-load ✓ hotfix/456-security-patch

  4. release/ - Release preparation Pattern: release/[version] Examples: ✓ release/v1.2.0 ✓ release/v2.0.0-beta

  5. refactor/ - Code refactoring Pattern: refactor/[component-name] Examples: ✓ refactor/auth-system ✓ refactor/database-layer

Naming Rules: ✓ Use lowercase letters ✓ Use hyphens to separate words ✓ Use issue numbers when applicable ✓ Keep names descriptive but concise ✗ No underscores (use hyphens) ✗ No spaces ✗ No special characters

Example workflow:

我要开发一个新功能:用户消息通知

→ Creates: feature/user-message-notifications

分支信息: Type: feature Name: user-message-notifications Base branch: develop Tracking: origin/feature/user-message-notifications

Checklist for this feature: ☐ Implement notification system ☐ Add real-time updates ☐ Create notification preferences ☐ Write tests ☐ Update docs

Start development? [Y/n]


### 技巧4: 提交历史清理

定期清理提交历史:

清理这个功能分支的提交历史

🧹 Cleaning up commit history...

Current branch: feature/user-dashboard Total commits: 23

Analyzing commits...

Commit types found: ✓ Feature commits: 8 ⚠️ Work-in-progress commits: 5 ⚠️ Fix typo commits: 3 ⚠️ "WIP" commits: 4 ⚠️ "Update" commits: 3

Recommendation: Squash to 3 meaningful commits

Proposed structure:

  1. feat: implement dashboard layout and structure Combines: Initial commits, layout work, basic components

  2. feat: add widget system and data integration Combines: Widget implementation, API integration, data handling

  3. feat: add styling and final polish Combines: CSS updates, responsive design, accessibility fixes

Proceed with interactive rebase? [Y/n] Y

✓ Started interactive rebase ✓ Squashing 23 commits → 3 commits ✓ Rewriting history...

New commit history:

f8g9h0i (HEAD) feat: add styling and final polish e7d8c9b feat: add widget system and data integration a6b5c4d feat: implement dashboard layout and structure

✓ Cleanup complete ✓ 3 clean, semantic commits ⚠️ Force push required to update remote

Force push to update remote? [Y/n] Y

✓ Force push successful ✓ Remote branch updated

Benefits: ✓ Clearer history ✓ Easier to review ✓ Better for code archaeology ✓ Follows best practices


### 技巧5: Git别名配置

设置常用Git命令的别名:

设置常用的Git别名来提高效率

⚡ Setting up Git aliases...

Created useful aliases:

Status and log

git st → git status git lg → git log --graph --oneline --all --decorate git hist → git log --pretty=format:'%h %ad | %s%d [%an]' --graph --date=short

Branch operations

git co → git checkout git cob → git checkout -b git br → git branch git brd → git branch -d

Commit operations

git cm → git commit -m git ca → git commit --amend git cane → git commit --amend --no-edit

Diff and merge

git df → git diff git dfs → git diff --staged git mt → git mergetool

Remote operations

git pushu → git push -u origin HEAD git pullr → git pull --rebase

Advanced

git last → git log -1 HEAD git undo → git reset --soft HEAD^ git stash-unstaged → git stash --keep-index git unstage → git reset HEAD

✓ Aliases configured

Examples:

Instead of: git status git checkout -b feature/new-feature git commit -m "Add feature" git push -u origin feature/new-feature

Now use: git st git cob feature/new-feature git cm "Add feature" git pushu

Time saved per command: ~3 seconds Daily usage: ~50 commands Time saved per day: ~2.5 minutes Annual savings: ~10 hours! 🎉


## 实际应用场景

### 场景1: 多人协作开发

**情境:** 团队中多人同时开发相关功能

帮我处理与团队成员的代码冲突

👥 Collaborative Development Sync

Team Activity Analysis:

Active branches: ✓ feature/user-profile (you) - Last commit: 10 min ago ✓ feature/auth-system (@alice) - Last commit: 1 hour ago ✓ bugfix/api-errors (@bob) - Last commit: 30 min ago

Intersection detected: ⚠️ Both your branch and @alice's branch modify:

  • src/components/UserCard.jsx
  • src/api/userApi.js

Sync strategy recommended:

Step 1: Fetch latest changes

git fetch origin

Step 2: Check for conflicts

git merge origin/feature/auth-system --no-commit --no-ff

⚠️ Conflict detected in src/components/UserCard.jsx

Analyzing conflict...

Your changes:

  • Added user avatar display
  • Modified card layout

@alice's changes:

  • Added user status indicator
  • Modified card layout

Resolution: Combine both changes ✓ Keep avatar display (your feature) ✓ Keep status indicator (@alice's feature) ✓ Merge layout changes carefully

Merging...

✓ Auto-resolved layout ✓ Integrated both features ✓ No functionality lost

Step 3: Communicate with team

Drafting message to @alice:

Hey @alice! 👋

I noticed our branches both modify UserCard.jsx.
I've integrated both changes:
- Your status indicator feature ✅
- My avatar display feature ✅
- Merged layout cleanly ✅

No conflicts - everything works together.
Ready to coordinate PR review?

Thanks!

Step 4: Sync with remote

git add src/components/UserCard.jsx
git commit -m "Merge: combine avatar and status features"

✓ Commit created
✓ Both features preserved
✓ Clean merge history

Result: ✅ Your feature: Working ✅ @alice's feature: Working ✅ Both integrated: No conflicts ✅ Team communication: Established

Next: Coordinate PR review time


### 场景2: 紧急Hotfix

**情境:** 生产环境发现紧急Bug,需要立即修复

生产环境出问题了,立即修复

🚨 PRODUCTION INCIDENT RESPONSE

Incident Details: Severity: CRITICAL 🔴 Impact: Users unable to complete payments Affected: 100% of payment transactions Started: 5 minutes ago Errors: 500 errors on /api/checkout

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

IMMEDIATE ACTION PLAN:

Phase 1: Investigation & Isolation (2 minutes)

✓ Fetching recent commits... ✓ Checking error logs... ✓ Identifying root cause...

Root Cause Found: File: src/api/payment.js Commit: a3b2c1d (15 minutes ago) Issue: Undefined variable 'paymentProvider'

guilty change:

// Line 45
const result = await paymentProvider.processPayment(data);
// ^^^^^^^^^^^^^^ undefined!

Phase 2: Hotfix Branch Creation (1 minute)

✓ Created hotfix: hotfix/payment-crash
✓ Based on: production (main)
✓ Switched to hotfix branch

Phase 3: Fix Implementation (2 minutes)

Fix applied:

// Line 45 - before
const result = await paymentProvider.processPayment(data);

// Line 45 - after
const result = await paymentService.processPayment(data);

✓ Fixed variable name ✓ Added regression test ✓ Verified fix locally

Phase 4: Testing & Validation (2 minutes)

✓ Unit tests: PASSED (47/47)
✓ Integration tests: PASSED (12/12)
✓ Manual checkout test: PASSED
✓ Error rate: 0%

Phase 5: Emergency Deployment (1 minute)

Creating hotfix PR...

fix: resolve payment processing crash

Critical fix for undefined variable causing payment failures.

  • Fixed variable name: paymentProvider → paymentService
  • Added test to prevent regression
  • Verified fix in staging environment

Risk: LOW (single variable fix) Impact: HIGH (restores payment functionality) Deploy: IMMEDIATE

🤖 Generated with Claude Code

Co-Authored-By: Claude (noreply@anthropic.com)

✓ PR created ✓ Auto-approved (emergency override) ✓ Merged to main ✓ Deployed to production

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

INCIDENT RESOLVED ✅

Total time: 8 minutes Investigation: 2 min Fix implementation: 2 min Testing: 2 min Deployment: 2 min

Impact minimized: ✓ Payments restored ✓ User experience: Normal ✓ Data loss: None

Post-Incident Actions: 📝 Incident report created 🐛 Root cause analysis started 🔒 Added test to prevent recurrence 📢 Team notified of resolution

Would you like to:

  1. Review the incident report
  2. Schedule post-mortem meeting
  3. Improve CI/CD to catch this earlier

### 场景3: 代码审查助手

**情境:** 审查团队成员的PR,确保代码质量

帮我审查团队成员的Pull Request

👨‍💼 Team Code Review Session

Loading Pull Request: #156 - Add file upload feature

Author: @junior-dev Files: 12 files changed, +543 -89 Time since creation: 2 hours

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

INITIAL ASSESSMENT

Overall Impression: Good effort, needs improvements Code Quality: 6/10 Test Coverage: 4/10 Documentation: 7/10 Security: 5/10

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

DETAILED REVIEW

Category 1: Functionality ✅

✅ GOOD: • File upload component works as expected • Progress bar is accurate • Error handling is present

⚠️ CONCERNS: • No file type validation on client side • Missing file size limit (could upload 1GB+) • No cancellation option for uploads

Suggestions:

// Add validation
const validateFile = (file) => {
const maxSize = 5 * 1024 * 1024; // 5MB
const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];

if (file.size > maxSize) {
throw new Error('File too large. Max 5MB.');
}

if (!allowedTypes.includes(file.type)) {
throw new Error('Invalid file type.');
}
};

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Category 2: Code Quality 🟡

✅ GOOD: • Clean component structure • Good use of React hooks • Consistent naming

⚠️ ISSUES:

  1. Performance - Large file uploads freeze UI Location: src/components/FileUpload.jsx:45 Issue: Synchronous file reading blocks main thread

    Fix:

// Instead of:
const content = await readFile(file);

// Use:
const content = await readFileChunked(file, onProgress);
  1. Memory Leak - Event listeners not cleaned up Location: src/components/FileUpload.jsx:78 Issue: Missing cleanup in useEffect

    Fix:

useEffect(() => {
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, []);

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Category 3: Testing 🔴

🔴 CRITICAL: Insufficient test coverage

Current: 23% Target: 80%

Missing tests: ❌ No test for large file upload ❌ No test for invalid file type ❌ No test for upload failure ❌ No test for progress tracking ❌ No test for concurrent uploads

Suggested test cases:

describe('FileUpload', () => {
it('should reject files larger than 5MB', async () => {
const largeFile = new File(['x'.repeat(6 * 1024 * 1024)], 'large.jpg');
await expect(uploadFile(largeFile)).rejects.toThrow('too large');
});

it('should reject invalid file types', async () => {
const invalidFile = new File(['content'], 'test.exe');
await expect(uploadFile(invalidFile)).rejects.toThrow('Invalid type');
});

it('should handle network errors gracefully', async () => {
// Mock failed upload
await expect(uploadFile(file)).rejects.toThrow('Upload failed');
});
});

Recommendation: Add at least 10 more test cases

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Category 4: Security 🔴

🔴 CRITICAL ISSUES:

  1. XSS Vulnerability Location: src/components/FileUpload.jsx:92 Issue: File name rendered without sanitization

    Current:

<div>{file.name}</div>

Fix:

import DOMPurify from 'dompurify';
<div>{DOMPurify.sanitize(file.name)}</div>
  1. No CSRF protection Location: src/api/upload.js Issue: Upload endpoint missing CSRF token

    Fix: Add CSRF token to headers

  2. File path traversal Location: src/api/upload.js:34 Issue: Filename not validated

    Fix:

const safeFilename = path.basename(filename);

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Category 5: Documentation ✅

✅ GOOD: • Component is well documented • Props are explained • Usage examples provided

💡 SUGGESTIONS: • Add error codes documentation • Document API rate limits • Add troubleshooting section

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

REVIEW SUMMARY

Required Changes (Must Fix): 🔴 Fix XSS vulnerability 🔴 Add CSRF protection 🔴 Add file validation

Recommended Changes (Should Fix): 🟡 Fix memory leak 🟡 Add error handling tests 🟡 Improve performance for large files

Nice to Have: 💡 Add upload cancellation 💡 Improve documentation 💡 Add progress bar animation

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

DECISION: ❌ Request Changes

Estimated effort to fix: 2-3 hours

Generating review comments...

✓ Posted 12 review comments ✓ Categorized by severity ✓ Included code examples ✓ Provided resources for learning

Message to @junior-dev:


Hey! 👋

Great start on the file upload feature! The core functionality works well.

I've left some review comments that need attention before we can merge:

**Must fix (security issues):**
1. XSS vulnerability in file name rendering
2. Missing CSRF protection
3. No file size/type validation

**Should fix (code quality):**
4. Memory leak with event listeners
5. Performance issue with large files
6. More test coverage needed

I've included code examples in the comments to help you fix these.

Don't worry - these are common issues and great learning opportunities!
If you have questions, feel free to ask.

Target for fixes: End of day tomorrow

You've got this! 💪

Would you like me to:

  1. Set up a follow-up meeting
  2. Create a checklist for the developer
  3. Mark for re-review when updated

## 最佳实践总结

### ✅ DO - 推荐做法

1. **频繁提交,小步快跑**
- 每完成一个小功能就提交
- 保持每次提交的逻辑完整性
- 避免积累大量未提交的更改

2. **编写清晰的提交信息**
- 使用现在时态:"Add feature"不是"Added feature"
- 首行简短(50字符内)
- 空行后详细说明为什么和怎么做

3. **保护敏感信息**
- 始终使用.gitignore忽略敏感文件
- 提交前检查是否包含密码、API密钥
- 使用环境变量管理配置

4. **保持分支简洁**
- 功能分支保持短生命周期
- 及时合并已完成的功能
- 定期清理已合并的分支

5. **编写有意义的测试**
- 为新功能添加测试
- 测试边界情况和错误处理
- 保持测试的可读性

### ❌ DON'T - 避免做法

1. **不要提交调试代码**

❌ console.log('debug'); ❌ debugger; ❌ 注释掉的大段代码


2. **不要在提交信息中包含敏感信息**

❌ "Fixed password: admin123" ❌ "Added API key: sk-1234567890"


3. **不要在主分支直接开发**
- 使用功能分支
- 通过PR合并
- 保持主分支稳定

4. **不要忽视冲突**
- 不要盲目使用" theirs"或"ours"
- 理解冲突的原因
- 与团队沟通解决

5. **不要提交生成的文件**

❌ node_modules/ ❌ build/ ❌ dist/ ❌ .next/ ❌ *.log


## 常见问题

### Q: Claude Code会自动提交我的代码吗?

**A:** 不会。Claude Code只在你明确要求时才会创建提交:

❌ 错误理解: "帮我修复这个bug" → 会自动提交

✅ 正确理解: "帮我修复这个bug" → 只修改文件 "提交这个修复" → 才会创建提交


你需要明确说:
- "提交这些更改"
- "创建一个提交"
- "帮我commit"

### Q: 如何撤销Claude Code创建的提交?

**A:** 有多种方法:

```bash
# 方法1: 撤销最近的提交(保留更改)
git reset --soft HEAD~1

# 方法2: 撤销最近的提交(丢弃更改)
git reset --hard HEAD~1

# 方法3: 撤销特定提交
git revert <commit-hash>

# 方法4: 回到某个提交
git reset --hard <commit-hash>

Claude Code可以帮你:

撤销上一次提交,但保留我的更改

Q: 如何处理Claude Code生成的提交信息?

A: 你可以:

  1. 接受默认 - 通常已经很好
  2. 要求修改 - 指定格式或风格
  3. 手动编辑 - 使用git commit --amend
使用emoji风格重新生成提交信息

Q: 可以在提交前检查更改吗?

A: 当然可以!

显示即将提交的所有更改

Claude Code会:

  1. 列出所有暂存的文件
  2. 显示具体更改内容
  3. 询问是否确认提交

Q: 如何防止意外提交敏感信息?

A: 多层保护:

  1. 配置.gitignore
帮我更新.gitignore,排除敏感文件
  1. 使用Git Hooks
设置提交前检查是否包含敏感信息
  1. Claude Code自动检查 Claude Code会自动检测并警告:
  • API密钥
  • 密码
  • 证书文件

总结

Git集成是Claude Code最强大的功能之一,它不只是执行Git命令,还能理解你的开发意图:

核心优势:

  1. 智能提交信息

    • 自动分析代码变更
    • 生成规范的commit message
    • 符合团队规范
  2. 安全可靠

    • 多重检查机制
    • 自动检测敏感信息
    • 防止错误提交
  3. 高效协作

    • 智能PR创建
    • 自动代码审查
    • 冲突预测和解决
  4. 工作流集成

    • 支持Git Flow
    • 支持GitHub Flow
    • 支持Trunk-Based Development

使用原则:

  1. 明确意图 - 清楚表达要做什么
  2. 小步提交 - 频繁提交小改动
  3. 编写测试 - 确保代码质量
  4. 保护敏感 - 注意安全信息
  5. 团队协作 - 善用分支和PR

掌握这些Git集成技巧,能建立起高效、安全、规范的版本控制工作流,让团队协作更加顺畅。

下一步