git-workflow
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGit Workflow & Best Practices
Git工作流与最佳实践
Purpose
目的
Comprehensive guide for git operations with emphasis on clean history, atomic commits, and professional workflows. Automatically analyzes staged changes and enforces single-responsibility principle.
本指南全面介绍Git操作,重点强调清晰的历史记录、原子提交和专业工作流。可自动分析暂存变更并强制执行单一职责原则。
When to Use
适用场景
Activate for any git operation:
- Committing changes (especially multiple files)
- Creating branches
- Merging or rebasing
- Managing git history
- Writing commit messages
- Organizing staging area
- Code review preparation
- Repository management
在以下任意Git操作场景中使用:
- 提交变更(尤其是涉及多文件的情况)
- 创建分支
- 合并或变基
- 管理Git历史记录
- 编写提交信息
- 整理暂存区
- 代码评审准备
- 仓库管理
Core Philosophy
核心理念
Single Responsibility Rule ⭐
单一职责原则 ⭐
CRITICAL: Before committing, analyze staged changes and divide into atomic commits.
Process:
- Run to see all staged files
git status - Identify different concerns/features
- Unstage everything:
git reset HEAD - Stage files by concern, one group at a time
- Commit each group with focused message
- Repeat until all changes are committed
Why: Makes history reviewable, revertable, and maintainable.
至关重要: 提交前需分析暂存变更,将其拆分为原子提交。
流程:
- 运行 查看所有暂存文件
git status - 识别不同的关注点/功能模块
- 取消所有暂存:
git reset HEAD - 按关注点分批暂存文件,每次一组
- 为每组提交编写聚焦的提交信息
- 重复上述步骤直至所有变更提交完成
原因: 让历史记录便于评审、回滚和维护。
Commit Organization
提交组织
Analyzing Staged Changes
分析暂存变更
bash
undefinedbash
undefinedCheck what's staged
查看暂存内容
git status
git status
See file-level summary
查看文件级摘要
git diff --cached --stat
git diff --cached --stat
See detailed changes
查看详细变更
git diff --cached
git diff --cached
Check specific file
查看特定文件
git diff --cached path/to/file
undefinedgit diff --cached path/to/file
undefinedGrouping Strategies
分组策略
By Feature:
- Auth system changes → one commit
- Payment module → separate commit
- User profile → another commit
By Layer:
- Database migrations → first commit
- Backend API → second commit
- Frontend UI → third commit
- Tests → fourth commit
By Type:
- New features (feat)
- Bug fixes (fix)
- Refactoring (refactor)
- Documentation (docs)
- Performance (perf)
- Tests (test)
By Dependency:
- Foundation/infrastructure first
- Features that depend on foundation second
按功能模块:
- 认证系统变更 → 单独一个提交
- 支付模块 → 单独一个提交
- 用户资料 → 单独一个提交
按架构分层:
- 数据库迁移 → 第一个提交
- 后端API → 第二个提交
- 前端UI → 第三个提交
- 测试代码 → 第四个提交
按变更类型:
- 新功能(feat)
- Bug修复(fix)
- 代码重构(refactor)
- 文档更新(docs)
- 性能优化(perf)
- 测试代码(test)
按依赖关系:
- 先提交基础/基础设施变更
- 再提交依赖于基础模块的功能变更
Division Workflow
拆分工作流
bash
undefinedbash
undefined1. Analyze current state
1. 分析当前状态
git status
git diff --cached --stat
git status
git diff --cached --stat
2. Unstage everything
2. 取消所有暂存
git reset HEAD
git reset HEAD
3. Stage first logical group
3. 暂存第一组逻辑相关的文件
git add file1.ts file2.ts directory/
git add file1.ts file2.ts directory/
4. Verify what's staged
4. 验证暂存内容
git diff --cached --stat
git diff --cached --stat
5. Commit with focused message
5. 提交并编写聚焦的信息
git commit -m "type: concise description"
git commit -m "type: 简洁描述"
6. Repeat steps 3-5 for remaining groups
6. 重复步骤3-5处理剩余分组
undefinedundefinedExample: Real Scenario
示例:真实场景
Situation: 29 files staged with mixed concerns
bash
undefined场景: 29个暂存文件包含混合关注点
bash
undefinedBefore - messy staging
拆分前 - 混乱的暂存区
$ git status
Changes to be committed:
Trading Styles feature (25 files)
modified: src/app/styles/page.tsx
new file: src/core/domain/models/TradingStyle.ts
new file: src/infrastructure/database/migrations/create_trading_styles.ts
...
History enhancements (4 files)
modified: src/app/history/page.tsx
modified: src/app/api/history/recommendations/route.ts
...
**Solution:**
```bash$ git status
Changes to be committed:
交易风格功能(25个文件)
modified: src/app/styles/page.tsx
new file: src/core/domain/models/TradingStyle.ts
new file: src/infrastructure/database/migrations/create_trading_styles.ts
...
历史记录增强功能(4个文件)
modified: src/app/history/page.tsx
modified: src/app/api/history/recommendations/route.ts
...
**解决方案:**
```bash1. Reset staging
1. 重置暂存区
git reset HEAD
git reset HEAD
2. Commit #1 - Trading Styles feature
2. 提交#1 - 交易风格功能
git add
package.json pnpm-lock.yaml
src/app/styles/
src/core/domain/models/TradingStyle.ts
src/core/ports/ITradingStyleRepository.ts
src/infrastructure/database/TradingStyleRepository.ts
src/infrastructure/database/migrations/create_trading_styles.ts
package.json pnpm-lock.yaml
src/app/styles/
src/core/domain/models/TradingStyle.ts
src/core/ports/ITradingStyleRepository.ts
src/infrastructure/database/TradingStyleRepository.ts
src/infrastructure/database/migrations/create_trading_styles.ts
git commit -m "feat: Add trading style persona system for AI-powered analysis"
git add
package.json pnpm-lock.yaml
src/app/styles/
src/core/domain/models/TradingStyle.ts
src/core/ports/ITradingStyleRepository.ts
src/infrastructure/database/TradingStyleRepository.ts
src/infrastructure/database/migrations/create_trading_styles.ts
package.json pnpm-lock.yaml
src/app/styles/
src/core/domain/models/TradingStyle.ts
src/core/ports/ITradingStyleRepository.ts
src/infrastructure/database/TradingStyleRepository.ts
src/infrastructure/database/migrations/create_trading_styles.ts
git commit -m "feat: 为AI驱动分析添加交易风格角色系统"
3. Commit #2 - History enhancements
3. 提交#2 - 历史记录增强
git add
src/app/history/page.tsx
src/app/api/history/recommendations/route.ts
src/infrastructure/database/TimeseriesRepository.ts
src/components/layout/AppLayout.tsx
src/app/history/page.tsx
src/app/api/history/recommendations/route.ts
src/infrastructure/database/TimeseriesRepository.ts
src/components/layout/AppLayout.tsx
git commit -m "feat: Add comprehensive search and filtering to history page"
**Result:** Clean, focused commits that are independently reviewable and revertable.
---git add
src/app/history/page.tsx
src/app/api/history/recommendations/route.ts
src/infrastructure/database/TimeseriesRepository.ts
src/components/layout/AppLayout.tsx
src/app/history/page.tsx
src/app/api/history/recommendations/route.ts
src/infrastructure/database/TimeseriesRepository.ts
src/components/layout/AppLayout.tsx
git commit -m "feat: 为历史记录页面添加全面搜索与过滤功能"
**结果:** 清晰、聚焦的提交,可独立评审和回滚。
---Commit Messages
提交信息
Conventional Commits Format
约定式提交格式
<type>(<scope>): <subject>
<body>
<footer><type>(<scope>): <subject>
<body>
<footer>Types
类型说明
- - New feature
feat - - Bug fix
fix - - Code restructuring (no behavior change)
refactor - - Performance improvement
perf - - Documentation only
docs - - Formatting, whitespace, semicolons
style - - Adding/updating tests
test - - Maintenance, dependencies
chore - - Build system changes
build - - CI/CD configuration
ci - - Revert previous commit
revert
- - 新功能
feat - - Bug修复
fix - - 代码重构(无行为变更)
refactor - - 性能优化
perf - - 仅文档更新
docs - - 格式调整、空格、分号等
style - - 添加/更新测试
test - - 维护工作、依赖更新
chore - - 构建系统变更
build - - CI/CD配置变更
ci - - 回滚之前的提交
revert
Subject Line Rules
主题行规则
- Use imperative mood: "Add feature" not "Added feature"
- Start with lowercase (no capital first letter)
- No period at end
- 50 characters maximum
- Be specific and descriptive
- 使用祈使语气:"Add feature" 而非 "Added feature"
- 首字母小写
- 结尾无句号
- 最多50个字符
- 具体且具有描述性
Body Guidelines
正文指南
- Explain WHAT and WHY, not HOW
- Wrap at 72 characters
- Use bullet points for multiple changes
- Reference issue numbers:
Fixes #123 - Include breaking changes
- 说明做了什么(WHAT)和为什么做(WHY),无需说明怎么做(HOW)
- 每行不超过72个字符
- 多变更时使用项目符号
- 引用问题编号:
Fixes #123 - 包含破坏性变更说明
Examples
示例
Good:
bash
git commit -m "$(cat <<'EOF'
feat: add trading style filtering to history page
Implemented comprehensive search and filtering:
- Multi-criteria filtering (action, type, risk, style)
- Partial symbol search with case-insensitive matching
- LEFT JOIN with trading_styles table
- Extended API with new query parameters
Fixes #456
EOF
)"Bad:
bash
git commit -m "Fixed stuff"
git commit -m "WIP"
git commit -m "Updated files"规范示例:
bash
git commit -m "$(cat <<'EOF'
feat: 为历史记录页面添加交易风格过滤功能
实现了全面的搜索与过滤:
- 多条件过滤(操作类型、风险等级、风格)
- 不区分大小写的部分符号搜索
- 与trading_styles表的LEFT JOIN查询
- 扩展API新增查询参数
Fixes #456
EOF
)"不规范示例:
bash
git commit -m "Fixed stuff"
git commit -m "WIP"
git commit -m "Updated files"Branching Strategy
分支策略
Branch Naming
分支命名
Format:
type/description-in-kebab-caseTypes:
- - New features
feature/ - - Bug fixes
fix/ - - Code improvements
refactor/ - - Documentation
docs/ - - Test additions
test/ - - Maintenance
chore/
Examples:
bash
feature/trading-style-personas
fix/history-filter-bug
refactor/database-queries
docs/api-documentation格式:
type/description-in-kebab-case类型:
- - 新功能
feature/ - - Bug修复
fix/ - - 代码优化
refactor/ - - 文档更新
docs/ - - 测试代码添加
test/ - - 维护工作
chore/
示例:
bash
feature/trading-style-personas
fix/history-filter-bug
refactor/database-queries
docs/api-documentationBranch Workflow
分支工作流
bash
undefinedbash
undefinedCreate and switch to new branch
创建并切换到新分支
git checkout -b feature/new-feature
git checkout -b feature/new-feature
Work on changes
进行开发变更
git add ...
git commit -m "..."
git add ...
git commit -m "..."
Keep branch updated with main
保持分支与main分支同步
git fetch origin
git rebase origin/main
git fetch origin
git rebase origin/main
Push to remote
推送到远程仓库
git push origin feature/new-feature
git push origin feature/new-feature
Create pull request (via GitHub/GitLab UI)
通过GitHub/GitLab界面创建Pull Request
undefinedundefinedBranch Management
分支管理
bash
undefinedbash
undefinedList all branches
列出所有分支
git branch -a
git branch -a
Switch branches
切换分支
git checkout branch-name
git checkout branch-name
Delete local branch
删除本地分支
git branch -d branch-name
git branch -d branch-name
Delete remote branch
删除远程分支
git push origin --delete branch-name
git push origin --delete branch-name
Rename current branch
重命名当前分支
git branch -m new-name
---git branch -m new-name
---Staging Operations
暂存操作
Selective Staging
选择性暂存
bash
undefinedbash
undefinedStage specific files
暂存特定文件
git add file1.ts file2.ts
git add file1.ts file2.ts
Stage entire directory
暂存整个目录
git add src/features/
git add src/features/
Stage all changes
暂存所有变更
git add .
git add .
Stage by file extension
按文件扩展名暂存
git add *.ts
git add *.ts
Interactive staging (patch mode)
交互式暂存(补丁模式)
git add -p file.ts
undefinedgit add -p file.ts
undefinedPatch Mode Operations
补丁模式操作
When using :
git add -p- - stage this hunk
y - - don't stage this hunk
n - - split into smaller hunks
s - - manually edit hunk
e - - quit
q - - help
?
使用 时的选项:
git add -p- - 暂存此代码块
y - - 不暂存此代码块
n - - 拆分为更小的代码块
s - - 手动编辑代码块
e - - 退出
q - - 查看帮助
?
Unstaging
取消暂存
bash
undefinedbash
undefinedUnstage all files
取消所有文件的暂存
git reset HEAD
git reset HEAD
Unstage specific file
取消特定文件的暂存
git restore --staged file.ts
git restore --staged file.ts
Unstage directory
取消目录的暂存
git restore --staged src/features/
---git restore --staged src/features/
---History Management
历史记录管理
Viewing History
查看历史记录
bash
undefinedbash
undefinedCompact history
简洁历史记录
git log --oneline -10
git log --oneline -10
Detailed history
详细历史记录
git log -5
git log -5
With file changes
包含文件变更的历史记录
git log --stat -3
git log --stat -3
Specific file history
特定文件的历史记录
git log -- path/to/file
git log -- path/to/file
Graph view
图形化视图
git log --oneline --graph --all
git log --oneline --graph --all
Search commits
搜索提交
git log --grep="search term"
git log --grep="搜索关键词"
By author
按作者查看
git log --author="name"
git log --author="姓名"
Date range
按日期范围查看
git log --since="2 weeks ago"
undefinedgit log --since="2 weeks ago"
undefinedAmending Commits
修改最近一次提交
bash
undefinedbash
undefinedAdd forgotten files to last commit
将遗漏的文件添加到最近一次提交
git add forgotten-file.ts
git commit --amend --no-edit
git add forgotten-file.ts
git commit --amend --no-edit
Change last commit message
修改最近一次提交的信息
git commit --amend -m "new message"
**⚠️ Warning:** Only amend commits that haven't been pushed!git commit --amend -m "新的提交信息"
**⚠️ 警告:** 仅可修改尚未推送到远程仓库的提交!Interactive Rebase
交互式变基
bash
undefinedbash
undefinedRebase last 3 commits
对最近3次提交进行变基
git rebase -i HEAD~3
git rebase -i HEAD~3
Rebase from specific commit
从特定提交开始变基
git rebase -i commit-hash
**Options:**
- `pick` - keep commit as-is
- `reword` - change commit message
- `edit` - modify commit
- `squash` - combine with previous
- `fixup` - like squash, discard message
- `drop` - remove commitgit rebase -i commit-hash
**选项:**
- `pick` - 保留提交原样
- `reword` - 修改提交信息
- `edit` - 修改提交内容
- `squash` - 与前一个提交合并
- `fixup` - 与前一个提交合并,丢弃当前提交信息
- `drop` - 删除提交Squashing Commits
合并提交
Before pushing:
bash
undefined推送前合并提交:
bash
undefinedSquash last 3 commits
合并最近3次提交
git rebase -i HEAD~3
git rebase -i HEAD~3
Mark commits as "squash" or "fixup"
将需要合并的提交标记为 "squash" 或 "fixup"
undefinedundefinedCherry-picking
挑选提交
bash
undefinedbash
undefinedApply specific commit to current branch
将特定提交应用到当前分支
git cherry-pick commit-hash
git cherry-pick commit-hash
Cherry-pick multiple commits
挑选多个提交
git cherry-pick hash1 hash2 hash3
---git cherry-pick hash1 hash2 hash3
---Merging & Rebasing
合并与变基
Merge vs Rebase
合并 vs 变基
Merge:
- Creates merge commit
- Preserves complete history
- Use for: integrating feature branches to main
bash
git checkout main
git merge feature/new-featureRebase:
- Rewrites history, linear timeline
- Cleaner history
- Use for: updating feature branch with main changes
bash
git checkout feature/new-feature
git rebase main合并:
- 创建合并提交
- 保留完整历史记录
- 适用场景:将功能分支合并到main分支
bash
git checkout main
git merge feature/new-feature变基:
- 重写历史记录,生成线性时间线
- 历史记录更简洁
- 适用场景:更新功能分支与main分支的同步
bash
git checkout feature/new-feature
git rebase mainMerge Strategies
合并策略
Fast-forward (default):
bash
git merge feature/branchNo fast-forward (always create merge commit):
bash
git merge --no-ff feature/branchSquash (combine all commits):
bash
git merge --squash feature/branch
git commit -m "feat: merged feature"快进合并(默认):
bash
git merge feature/branch禁止快进(始终创建合并提交):
bash
git merge --no-ff feature/branch合并压缩(将所有提交合并为一个):
bash
git merge --squash feature/branch
git commit -m "feat: 合并功能分支"Resolving Conflicts
解决冲突
bash
undefinedbash
undefinedCheck conflict status
查看冲突状态
git status
git status
View conflicts
查看冲突内容
git diff
git diff
After resolving conflicts in editor
在编辑器中解决冲突后
git add resolved-file.ts
git add resolved-file.ts
Continue rebase
继续变基
git rebase --continue
git rebase --continue
Or abort
或终止变基
git rebase --abort
---git rebase --abort
---Remote Operations
远程操作
Working with Remotes
远程仓库操作
bash
undefinedbash
undefinedView remotes
查看远程仓库
git remote -v
git remote -v
Add remote
添加远程仓库
git remote add origin https://github.com/user/repo.git
git remote add origin https://github.com/user/repo.git
Update remote URL
更新远程仓库URL
git remote set-url origin new-url
git remote set-url origin new-url
Fetch from remote
从远程仓库拉取更新
git fetch origin
git fetch origin
Pull with rebase
以变基方式拉取
git pull --rebase origin main
git pull --rebase origin main
Push to remote
推送到远程仓库
git push origin branch-name
git push origin branch-name
Force push (use carefully!)
强制推送(谨慎使用!)
git push --force-with-lease origin branch-name
undefinedgit push --force-with-lease origin branch-name
undefinedPull Request Workflow
Pull Request工作流
bash
undefinedbash
undefined1. Update local main
1. 更新本地main分支
git checkout main
git pull origin main
git checkout main
git pull origin main
2. Create feature branch
2. 创建功能分支
git checkout -b feature/new-feature
git checkout -b feature/new-feature
3. Make changes and commit atomically
3. 进行开发并按单一职责原则提交变更
(following single-responsibility rule)
4. 保持分支与远程同步
4. Keep branch updated
—
git fetch origin
git rebase origin/main
git fetch origin
git rebase origin/main
5. Push to remote
5. 推送到远程仓库
git push origin feature/new-feature
git push origin feature/new-feature
6. Create PR via GitHub/GitLab UI
6. 通过GitHub/GitLab界面创建PR
7. Address review feedback
7. 处理评审反馈
git add .
git commit -m "fix: address review comments"
git push origin feature/new-feature
git add .
git commit -m "fix: 处理评审意见"
git push origin feature/new-feature
8. After PR merged, clean up
8. PR合并后清理分支
git checkout main
git pull origin main
git branch -d feature/new-feature
---git checkout main
git pull origin main
git branch -d feature/new-feature
---Advanced Techniques
高级技巧
Stashing
暂存变更(Stash)
bash
undefinedbash
undefinedStash current changes
暂存当前变更
git stash
git stash
Stash with message
添加信息暂存变更
git stash save "work in progress"
git stash save "开发中"
List stashes
列出所有暂存
git stash list
git stash list
Apply last stash
应用最近一次暂存
git stash apply
git stash apply
Apply and remove stash
应用并删除暂存
git stash pop
git stash pop
Apply specific stash
应用特定暂存
git stash apply stash@{2}
git stash apply stash@{2}
Drop stash
删除特定暂存
git stash drop stash@{0}
git stash drop stash@{0}
Clear all stashes
清空所有暂存
git stash clear
undefinedgit stash clear
undefinedTagging
标签管理
bash
undefinedbash
undefinedCreate lightweight tag
创建轻量标签
git tag v1.0.0
git tag v1.0.0
Create annotated tag
创建附注标签
git tag -a v1.0.0 -m "Release version 1.0.0"
git tag -a v1.0.0 -m "发布版本1.0.0"
List tags
列出所有标签
git tag
git tag
Push tag to remote
推送标签到远程仓库
git push origin v1.0.0
git push origin v1.0.0
Push all tags
推送所有标签
git push origin --tags
git push origin --tags
Delete tag
删除标签
git tag -d v1.0.0
git push origin --delete v1.0.0
undefinedgit tag -d v1.0.0
git push origin --delete v1.0.0
undefinedBisect (Finding Bugs)
二分查找(定位Bug)
bash
undefinedbash
undefinedStart bisect
启动二分查找
git bisect start
git bisect start
Mark current commit as bad
将当前标记为有Bug
git bisect bad
git bisect bad
Mark known good commit
标记已知正常的提交
git bisect good commit-hash
git bisect good commit-hash
Git will checkout middle commit
Git会自动检出中间提交
Test it, then mark as good or bad
测试后标记为正常或有Bug
git bisect good # or git bisect bad
git bisect good # 或 git bisect bad
Repeat until bug is found
重复操作直至找到Bug
Reset after finding
完成后重置
git bisect reset
undefinedgit bisect reset
undefinedReflog (Recovery)
引用日志(恢复操作)
bash
undefinedbash
undefinedView reflog
查看引用日志
git reflog
git reflog
Recover lost commit
恢复丢失的提交
git reset --hard commit-hash
git reset --hard commit-hash
Recover deleted branch
恢复已删除的分支
git checkout -b recovered-branch commit-hash
---git checkout -b recovered-branch commit-hash
---Git Ignore
Git忽略规则
.gitignore Patterns
.gitignore 模式
bash
undefinedbash
undefinedIgnore file
忽略单个文件
secret.env
secret.env
Ignore directory
忽略目录
node_modules/
node_modules/
Ignore by extension
按扩展名忽略
*.log
*.log
Ignore except specific file
忽略除特定文件外的所有文件
!important.log
!important.log
Ignore in all subdirectories
忽略所有子目录中的指定文件
**/debug.log
undefined**/debug.log
undefinedCommon Ignores
常见忽略内容
bash
undefinedbash
undefinedDependencies
依赖目录
node_modules/
vendor/
node_modules/
vendor/
Build outputs
构建输出
dist/
build/
*.exe
dist/
build/
*.exe
Environment
环境配置文件
.env
.env.local
.env
.env.local
IDE
IDE配置
.vscode/
.idea/
*.swp
.vscode/
.idea/
*.swp
OS
系统文件
.DS_Store
Thumbs.db
.DS_Store
Thumbs.db
Logs
日志文件
*.log
logs/
---*.log
logs/
---Best Practices Checklist
最佳实践检查清单
Before Committing
提交前
- Run to analyze staged files
git status - Group changes by single responsibility
- Unstage unrelated files
- Stage only related files together
- Review before committing
git diff --cached - Write clear, descriptive commit message
- Follow conventional commit format
- Ensure code builds successfully
- Run tests if applicable
- Verify commit is independently reviewable
- 运行 分析暂存文件
git status - 按单一职责原则分组变更
- 取消无关文件的暂存
- 仅暂存相关文件
- 提交前查看
git diff --cached - 编写清晰、描述性的提交信息
- 遵循约定式提交格式
- 确保代码可正常构建
- 如有测试需运行测试
- 验证提交可独立评审
Branch Management
分支管理
- Use descriptive branch names
- Keep branches short-lived
- Rebase regularly with main
- Delete merged branches
- Don't commit directly to main
- 使用描述性分支名称
- 保持分支生命周期简短
- 定期与main分支变基同步
- 删除已合并的分支
- 不直接向main分支提交
Commit Quality
提交质量
- Atomic commits (one concern per commit)
- Meaningful commit messages
- No WIP or "fix stuff" messages
- No commented-out code in commits
- No generated files (unless necessary)
- No secrets or credentials
- 原子提交(每个提交对应一个关注点)
- 有意义的提交信息
- 无WIP或“修复问题”这类模糊信息
- 提交中无注释掉的代码
- 提交中无生成文件(除非必要)
- 提交中无密钥或凭证
Code Review
代码评审
- Small, focused pull requests
- Descriptive PR title and description
- Reference related issues
- Self-review before requesting review
- Address all review comments
- Keep commits clean during review
- 小而聚焦的Pull Request
- 描述性的PR标题和内容
- 引用相关问题
- 申请评审前先自我评审
- 处理所有评审意见
- 评审过程中保持提交清晰
Anti-Patterns to Avoid
需避免的反模式
❌ Giant Mixed Commits
❌ 大型混合提交
bash
git add .
git commit -m "various changes"Problem: Impossible to review, revert, or understand
Fix: Divide into atomic commits by concern
bash
git add .
git commit -m "各种变更"问题: 无法评审、回滚或理解变更内容
解决: 按关注点拆分为原子提交
❌ Committing Directly to Main
❌ 直接向main分支提交
bash
git checkout main
git commit -m "quick fix"
git pushProblem: Bypasses code review, risky
Fix: Always use feature branches
bash
git checkout main
git commit -m "快速修复"
git push问题: 绕过代码评审,风险高
解决: 始终使用功能分支
❌ Force Push to Shared Branches
❌ 强制推送到共享分支
bash
git push --force origin mainProblem: Destroys others' work, breaks history
Fix: Use and only on your branches
--force-with-leasebash
git push --force origin main问题: 破坏他人工作,损坏历史记录
解决: 使用 ,且仅在自己的分支上使用
--force-with-lease❌ Large Binary Files
❌ 大型二进制文件
bash
git add large-video.mp4
git commit -m "add video"Problem: Bloats repository size forever
Fix: Use Git LFS or external storage
bash
git add large-video.mp4
git commit -m "添加视频"问题: 永久膨胀仓库体积
解决: 使用Git LFS或外部存储
❌ Committing Secrets
❌ 提交密钥
bash
git add .env
git commit -m "add config"Problem: Security vulnerability, hard to remove
Fix: Use .gitignore, environment variables, secrets management
bash
git add .env
git commit -m "添加配置"问题: 安全漏洞,难以彻底删除
解决: 使用.gitignore、环境变量、密钥管理工具
❌ Meaningless Messages
❌ 无意义的提交信息
bash
git commit -m "fix"
git commit -m "update"
git commit -m "wip"Problem: History is useless for debugging
Fix: Write descriptive, specific commit messages
bash
git commit -m "修复"
git commit -m "更新"
git commit -m "wip"问题: 历史记录对调试无用
解决: 编写具体、描述性的提交信息
Quick Reference
快速参考
Essential Commands
核心命令
bash
undefinedbash
undefinedStatus and diff
状态与差异查看
git status
git diff
git diff --cached
git diff --stat
git status
git diff
git diff --cached
git diff --stat
Staging
暂存操作
git add file.ts
git add .
git reset HEAD
git restore --staged file.ts
git add file.ts
git add .
git reset HEAD
git restore --staged file.ts
Committing
提交操作
git commit -m "message"
git commit --amend
git commit -m "message"
git commit --amend
Branching
分支操作
git branch
git checkout -b branch-name
git branch -d branch-name
git branch
git checkout -b branch-name
git branch -d branch-name
History
历史记录查看
git log --oneline -10
git log --stat
git show commit-hash
git log --oneline -10
git log --stat
git show commit-hash
Remote
远程操作
git fetch origin
git pull --rebase
git push origin branch-name
git fetch origin
git pull --rebase
git push origin branch-name
Stashing
暂存变更操作
git stash
git stash pop
undefinedgit stash
git stash pop
undefinedRecovery Commands
恢复命令
bash
undefinedbash
undefinedUndo last commit (keep changes)
撤销最后一次提交(保留变更)
git reset --soft HEAD~1
git reset --soft HEAD~1
Undo last commit (discard changes)
撤销最后一次提交(丢弃变更)
git reset --hard HEAD~1
git reset --hard HEAD~1
Undo changes to file
撤销文件变更
git restore file.ts
git restore file.ts
Recover deleted branch
恢复已删除的分支
git reflog
git checkout -b branch-name commit-hash
---git reflog
git checkout -b branch-name commit-hash
---Resources
参考资源
- Conventional Commits: https://www.conventionalcommits.org/
- Git Book: https://git-scm.com/book/en/v2
- Oh Shit, Git!: https://ohshitgit.com/
Status: Production-ready ✅
Line Count: ~480 (under 500-line rule) ✅
Coverage: Complete git workflow + atomic commit enforcement ✅
- 约定式提交: https://www.conventionalcommits.org/
- Git官方手册: https://git-scm.com/book/en/v2
- Oh Shit, Git!: https://ohshitgit.com/
状态: 可用于生产环境 ✅
行数: ~480(符合500行以内要求) ✅
覆盖范围: 完整Git工作流 + 原子提交强制执行 ✅