Git 完整手册(中高级开发者版)
版本:2025-01 · 面向中高级开发者 · 全面整合版
目标:不仅会"用命令",更要理解 Git 的数据模型与命令语义,能在复杂协作中自如切换策略,快速解决实际问题。
目录(Table of Contents)
第一部分:核心概念与数据模型
第二部分:命令体系详解
第三部分:四大灵魂命令深度解析
- 3.1 git fetch:只更新远程引用
- 3.2 git merge:合并时间线
- 3.3 git checkout/switch/restore:切换与恢复
- 3.4 git rebase:重放提交
- 3.5 四者关系对比
第四部分:实战场景手册
第五部分:协作策略与最佳实践
第六部分:问题排查与救命技巧
第七部分:高级主题
附录
第一部分:核心概念与数据模型
1.1 Git 本质认知
Git 是一个内容寻址的有向无环图(DAG)存储系统。
核心概念
- 内容寻址:每个对象都有唯一的 SHA1 哈希值
- 有向无环图:提交历史形成不可循环的节点网络
- 对象类型:
blob
:文件内容tree
:目录快照commit
:提交记录(包含父指针、作者、时间戳等)tag
:标签对象
数据结构可视化
CommitA --> CommitB --> CommitC
(HEAD)指向当前工作分支
每个 commit 包含:
- 指向父提交的指针
- 指向项目快照(tree)的指针
- 作者信息、提交信息、时间戳
- 唯一的 SHA1 哈希值
1.2 四层架构详解
层级 | 位置 | 说明 | 操作命令 |
---|---|---|---|
工作区 | 文件系统 | 你编辑代码的地方 | 直接编辑文件 |
暂存区 | .git/index | 已 add 的文件列表 | git add |
本地仓库 | .git/objects | 已 commit 的版本历史 | git commit |
远程仓库 | GitHub/GitLab | 同步协作副本 | git push |
数据流动路径
编辑文件 → git add → git commit → git push
↓ ↓ ↓ ↓
工作区 → 暂存区 → 本地库 → 远程库
查看各层差异
git status # 工作区 vs 暂存区
git diff # 工作区 vs 暂存区
git diff --cached # 暂存区 vs 本地库
git diff HEAD # 工作区 vs 最新提交
1.3 引用系统与指针
引用类型
- HEAD:指向当前分支的最新提交
- 分支引用:
refs/heads/main
、refs/heads/feature
- 远程引用:
refs/remotes/origin/main
- 标签引用:
refs/tags/v1.0.0
指针移动示例
# 创建新提交时
git commit # HEAD 和当前分支指针都移动到新提交
# 切换分支时
git switch feature # HEAD 指向 feature 分支
# 合并分支时
git merge feature # 可能创建新的合并提交
1.4 可视化心智模型
Git 操作心智流
编辑 → 暂存 → 提交 → 推送
↓ ↓ ↓ ↓
工作区 → 暂存区 → 本地库 → 远程库
↑ ↑ ↑ ↑
分支合并 ↔ 远程同步 ↔ 回退修正
核心原则
Git 的本质是移动"指针",每个命令都是在操作 HEAD、branch、index、object 四者之间的关系。
第二部分:命令体系详解
2.1 初始化与配置
仓库初始化
# 创建新仓库
git init [--initial-branch=main]
# 克隆现有仓库
git clone <url> [directory]
git clone --depth=1 <url> # 浅克隆
git clone --filter=blob:none <url> # 部分克隆
配置管理
# 全局配置
git config --global user.name "Your Name"
git config --global user.email "your@email.com"
git config --global init.defaultBranch main
# 本地配置
git config user.name "Project Name"
git config user.email "project@email.com"
# 查看配置
git config --list
git config user.name
推荐配置
# 拉取策略
git config --global pull.rebase true
git config --global rebase.autoStash true
git config --global fetch.prune true
# 合并策略
git config --global merge.ff only
git config --global rerere.enabled true
# 行结尾处理
git config --global core.autocrlf input # macOS/Linux
git config --global core.autocrlf true # Windows
# 推送策略
git config --global push.default simple
2.2 状态检视
查看状态
git status # 详细状态
git status -sb # 简短状态
git status --porcelain # 机器可读格式
查看差异
git diff # 工作区 vs 暂存区
git diff --cached # 暂存区 vs 最新提交
git diff HEAD # 工作区 vs 最新提交
git diff --name-only # 只显示文件名
git diff --stat # 统计信息
查看历史
git log # 详细历史
git log --oneline # 单行显示
git log --graph --oneline --decorate --all # 图形化历史
git log --since="2 weeks ago" # 时间过滤
git log --author="John" # 作者过滤
git log --grep="fix" # 提交信息过滤
查看提交详情
git show <commit> # 查看提交详情
git show <commit>:<file> # 查看文件在特定提交的内容
git describe --tags # 最近标签描述
搜索内容
git grep "pattern" # 在工作区搜索
git grep -n "pattern" # 显示行号
git log -S "pattern" # 在提交历史中搜索
2.3 文件操作
添加文件
git add <file> # 添加特定文件
git add . # 添加所有文件
git add -A # 添加所有文件(包括删除)
git add -p # 交互式添加(分块)
git add -u # 只添加已跟踪的文件
移除文件
git rm <file> # 删除文件并暂存
git rm --cached <file> # 从暂存区移除,保留工作区文件
git mv <old> <new> # 重命名文件(保持历史)
恢复文件
git restore <file> # 从暂存区恢复工作区
git restore --staged <file> # 从暂存区移除
git restore --source=HEAD <file> # 从指定提交恢复
2.4 提交管理
创建提交
git commit -m "message" # 提交并添加信息
git commit -am "message" # 添加所有已跟踪文件并提交
git commit --amend # 修改最后一次提交
git commit --amend -m "new message" # 修改提交信息
重置提交
git reset --soft HEAD~1 # 回退提交,保留暂存区和工作区
git reset --mixed HEAD~1 # 回退提交和暂存区,保留工作区(默认)
git reset --hard HEAD~1 # 回退所有更改(危险)
git reset <commit> # 重置到指定提交
撤销更改
git revert <commit> # 创建反向提交(安全)
git revert --no-commit <commit> # 撤销但不提交
git revert -m 1 <merge-commit> # 撤销合并提交
查看操作历史
git reflog # 查看所有 HEAD 移动记录
git reflog show <branch> # 查看特定分支的 reflog
2.5 分支操作
查看分支
git branch # 本地分支
git branch -r # 远程分支
git branch -a # 所有分支
git branch -vv # 显示上游分支
创建分支
git branch <name> # 创建分支
git checkout -b <name> # 创建并切换分支
git switch -c <name> # 新命令:创建并切换
切换分支
git checkout <branch> # 切换分支
git switch <branch> # 新命令:切换分支
git switch - # 切换到上一个分支
删除分支
git branch -d <branch> # 删除已合并的分支
git branch -D <branch> # 强制删除分支
git push origin --delete <branch> # 删除远程分支
合并分支
git merge <branch> # 合并分支
git merge --no-ff <branch> # 强制创建合并提交
git merge --ff-only <branch> # 只允许快进合并
git merge --squash <branch> # 压缩合并
变基操作
git rebase <branch> # 变基到指定分支
git rebase -i <commit> # 交互式变基
git rebase --onto <newbase> <upstream> <branch> # 变基到新基础
git rebase --continue # 继续变基
git rebase --abort # 中止变基
2.6 远程协作
管理远程仓库
git remote -v # 查看远程仓库
git remote add <name> <url> # 添加远程仓库
git remote remove <name> # 删除远程仓库
git remote set-url <name> <new-url> # 修改远程 URL
获取更新
git fetch # 获取默认远程仓库
git fetch <remote> # 获取指定远程仓库
git fetch --all # 获取所有远程仓库
git fetch --prune # 清理已删除的远程分支
拉取更新
git pull # 拉取并合并
git pull --rebase # 拉取并变基
git pull --ff-only # 只允许快进
推送更新
git push # 推送到默认远程仓库
git push <remote> <branch> # 推送到指定分支
git push -u <remote> <branch> # 设置上游分支
git push --force-with-lease # 安全强制推送
git push --tags # 推送标签
2.7 高级功能
暂存工作
git stash # 暂存当前工作
git stash push -m "message" # 带消息暂存
git stash list # 查看暂存列表
git stash show stash@{0} # 查看暂存内容
git stash apply stash@{0} # 应用暂存
git stash pop stash@{0} # 应用并删除暂存
git stash drop stash@{0} # 删除暂存
拣选提交
git cherry-pick <commit> # 拣选单个提交
git cherry-pick A..B # 拣选提交范围
git cherry-pick --continue # 继续拣选
git cherry-pick --abort # 中止拣选
二分查找
git bisect start # 开始二分查找
git bisect bad # 标记当前为坏提交
git bisect good <commit> # 标记已知好提交
git bisect reset # 结束二分查找
查看文件历史
git blame <file> # 查看每行最后修改人
git blame -L 10,50 <file> # 查看指定行范围
多工作区
git worktree add <path> <branch> # 添加工作区
git worktree list # 列出工作区
git worktree remove <path> # 删除工作区
2.8 维护清理
垃圾回收
git gc # 垃圾回收
git gc --aggressive # 激进垃圾回收
git fsck # 检查对象完整性
git prune # 删除不可达对象
重新打包
git repack -ad # 重新打包对象
git count-objects -v # 查看对象统计
清理文件
git clean -f # 删除未跟踪文件
git clean -fd # 删除未跟踪文件和目录
git clean -n # 预览清理操作
稀疏检出
git sparse-checkout init --cone
git sparse-checkout set <dir1> <dir2>
git sparse-checkout disable
2.9 发布打包
标签管理
git tag # 列出标签
git tag -a v1.0.0 -m "message" # 创建注释标签
git tag v1.0.0 # 创建轻量标签
git push --tags # 推送所有标签
git tag -d v1.0.0 # 删除本地标签
打包导出
git archive -o release.zip HEAD # 导出归档
git archive --format=tar.gz HEAD > release.tar.gz
补丁管理
git format-patch <range> # 生成补丁文件
git am *.patch # 应用补丁
git apply <patch> # 应用补丁(不创建提交)
子模块
git submodule add <url> <path> # 添加子模块
git submodule update --init --recursive # 更新子模块
git submodule deinit <path> # 停用子模块
第三部分:四大灵魂命令深度解析
3.1 git fetch:只更新远程引用
核心语义
git fetch
只下载远程对象并更新 refs/remotes/origin/*
,不改变当前分支或工作区。
可视化示例
执行前:
main: A--B
origin/main: A--B
执行 git fetch 后:
main: A--B (不变)
origin/main: A--B--C (更新了)
常用参数
git fetch # 默认远程仓库所有分支
git fetch --all # 所有远程仓库
git fetch origin main # 只拉取 origin/main
git fetch --prune # 清理已删除的远程分支
git fetch --tags # 同步标签
git fetch --depth=1 # 浅抓取
使用场景
- 查看远程更新而不影响本地工作
- 在合并前先了解远程变化
- 定期同步远程引用
3.2 git merge:合并时间线
核心语义
把另一个分支的 tip 合并进当前分支,可能产生合并提交。
合并类型
快进合并(Fast-forward)
合并前:
main: A--B
feature: A--B--C--D
执行 git merge feature 后:
main: A--B--C--D
三方合并(Three-way merge)
合并前:
main: A--B--C
feature: A--B--D--E
执行 git merge feature 后:
main: A--B--C--F
\ /
D--E
常用参数
git merge <branch> # 基本合并
git merge --no-ff <branch> # 强制创建合并提交
git merge --ff-only <branch> # 只允许快进合并
git merge --squash <branch> # 压缩合并
git merge -X ours <branch> # 冲突时偏向当前分支
git merge -X theirs <branch> # 冲突时偏向目标分支
git merge --abort # 取消合并
冲突解决流程
- 编辑冲突文件
git add <file>
标记已解决git commit
完成合并
3.3 git checkout/switch/restore:切换与恢复
命令演进
git checkout
:老命令,功能混杂git switch
:新命令,专门用于分支切换git restore
:新命令,专门用于文件恢复
分支切换
# 推荐使用新命令
git switch <branch> # 切换分支
git switch -c <branch> # 创建并切换分支
git switch - # 切换到上一个分支
# 老命令(仍可用)
git checkout <branch>
git checkout -b <branch>
文件恢复
# 推荐使用新命令
git restore <file> # 从暂存区恢复工作区
git restore --staged <file> # 从暂存区移除
git restore --source=HEAD <file> # 从指定提交恢复
# 老命令(仍可用)
git checkout -- <file>
git checkout HEAD -- <file>
3.4 git rebase:重放提交
核心语义
把当前分支的提交**"搬到"**目标分支 tip 之后,形成新的 commit id(历史被重写)。
可视化示例
变基前:
main: A--B--C
feature: A--B--D--E
执行 git rebase main 后:
main: A--B--C
feature: A--B--C--D'--E' (D、E 被重放)
常用参数
git rebase <branch> # 基本变基
git rebase -i <commit> # 交互式变基
git rebase --onto <newbase> <upstream> <branch> # 变基到新基础
git rebase --continue # 继续变基
git rebase --abort # 中止变基
git rebase --skip # 跳过当前提交
交互式变基操作
pick
:使用提交reword
:修改提交信息edit
:编辑提交squash
:压缩到前一个提交fixup
:压缩到前一个提交(丢弃信息)drop
:删除提交
重要原则
不要对已推送到公共仓库的分支做 rebase(除非全员知情并配合)。
3.5 四者关系对比
命令 | 是否改动工作区 | 是否新提交 | 是否改历史 | 典型用途 |
---|---|---|---|---|
fetch | 否 | 否 | 否 | 更新远程引用 |
merge | 是 | 可能 | 否 | 汇合两条时间线 |
pull | 是 | 取决于配置 | 取决于 rebase | "抓取+整合"的快捷方式 |
rebase | 是 | 否(但会生成新 commit id) | 是 | 平直化历史 |
选择策略
- 团队可审计历史优先 → merge(保留真实分歧与合流点)
- 线性历史、整洁审阅优先 → rebase(个人分支用,PR 前整理)
第四部分:实战场景手册
4.1 日常开发流程
标准开发流程
# 1. 获取最新代码
git fetch origin
git rebase origin/main
# 2. 创建功能分支
git switch -c feature/new-feature
# 3. 开发并提交
git add .
git commit -m "feat: add new feature"
# 4. 推送分支
git push -u origin feature/new-feature
# 5. 创建 Pull Request
# (在 GitHub/GitLab 界面操作)
# 6. 合并后清理
git switch main
git pull origin main
git branch -d feature/new-feature
git push origin --delete feature/new-feature
快速修复流程
# 1. 保存当前工作
git stash push -m "wip: current work"
# 2. 切换到主分支
git switch main
git pull origin main
# 3. 创建修复分支
git switch -c hotfix/urgent-fix
# 4. 修复并提交
# ... 修复代码 ...
git add .
git commit -m "fix: urgent bug fix"
# 5. 推送并合并
git push -u origin hotfix/urgent-fix
# 创建 PR 并合并
# 6. 恢复工作
git switch -
git stash pop
4.2 分支管理策略
GitFlow 工作流
# 主分支
main # 生产环境
develop # 开发环境
# 功能分支
feature/user-auth # 新功能
feature/payment-system
# 发布分支
release/v1.2.0 # 准备发布
# 热修复分支
hotfix/critical-bug # 紧急修复
主干开发工作流
# 只有主分支
main
# 短期功能分支
feature/login-page # 1-2 天完成
feature/api-integration # 3-5 天完成
# 所有功能都直接合并到 main
4.3 冲突解决步骤
合并冲突解决
# 1. 尝试合并
git merge feature/login
# 2. 查看冲突文件
git status
# 3. 编辑冲突文件
# 手动解决冲突标记:
# <<<<<<< HEAD
# 当前分支内容
# =======
# 目标分支内容
# >>>>>>> feature/login
# 4. 标记已解决
git add <resolved-file>
# 5. 完成合并
git commit
变基冲突解决
# 1. 开始变基
git rebase main
# 2. 解决冲突
# 编辑冲突文件...
# 3. 标记已解决
git add <resolved-file>
# 4. 继续变基
git rebase --continue
# 5. 如果还有冲突,重复 2-4
# 6. 如果完成,变基结束
冲突解决工具
# 使用合并工具
git mergetool
# 配置合并工具
git config --global merge.tool vimdiff
git config --global mergetool.vimdiff.cmd 'vimdiff $LOCAL $MERGED $REMOTE'
4.4 历史修改与回退
修改最后一次提交
# 修改提交信息
git commit --amend -m "new message"
# 添加文件到上次提交
git add forgotten-file.txt
git commit --amend --no-edit
修改多个提交(交互式变基)
# 修改最近 3 个提交
git rebase -i HEAD~3
# 在编辑器中:
# pick abc1234 old commit message
# reword def5678 another commit
# squash ghi9012 third commit
# 保存并退出,按提示操作
安全回退(已推送)
# 创建反向提交
git revert <bad-commit>
# 回退多个提交
git revert <old-commit>..<new-commit>
# 回退合并提交
git revert -m 1 <merge-commit>
危险回退(未推送)
# 软回退(保留更改)
git reset --soft HEAD~1
# 混合回退(默认)
git reset --mixed HEAD~1
# 硬回退(丢弃更改)
git reset --hard HEAD~1
4.5 多人协作同步
同步远程更新
# 方法1:先获取再合并
git fetch origin
git merge origin/main
# 方法2:先获取再变基
git fetch origin
git rebase origin/main
# 方法3:直接拉取
git pull origin main
git pull --rebase origin main
处理他人推送
# 1. 获取远程更新
git fetch origin
# 2. 查看差异
git log HEAD..origin/main --oneline
# 3. 合并或变基
git merge origin/main
# 或
git rebase origin/main
# 4. 解决冲突(如果有)
# ... 解决冲突 ...
# 5. 推送更新
git push origin main
强制推送安全策略
# 危险:可能覆盖他人工作
git push --force origin main
# 安全:检查远程是否有新提交
git push --force-with-lease origin main
# 更安全:指定要覆盖的提交
git push --force-with-lease=origin/main:abc1234 origin main
4.6 紧急问题修复
紧急修复流程
# 1. 保存当前工作
git stash push -m "emergency stash"
# 2. 切换到生产分支
git switch main
git pull origin main
# 3. 创建热修复分支
git switch -c hotfix/critical-security-fix
# 4. 快速修复
# ... 紧急修复代码 ...
git add .
git commit -m "hotfix: critical security vulnerability"
# 5. 立即推送
git push -u origin hotfix/critical-security-fix
# 6. 创建紧急 PR 并合并
# 7. 部署到生产环境
# 8. 恢复原工作
git switch -
git stash pop
回滚紧急修复
# 如果修复有问题,立即回滚
git revert <hotfix-commit>
git push origin main
# 或者重置到修复前
git reset --hard <commit-before-hotfix>
git push --force-with-lease origin main
4.7 代码审查流程
准备审查
# 1. 确保分支是最新的
git fetch origin
git rebase origin/main
# 2. 整理提交历史
git rebase -i HEAD~3
# 3. 推送更新
git push --force-with-lease origin feature/review-ready
# 4. 创建 Pull Request
审查反馈处理
# 1. 获取反馈
git fetch origin
git switch feature/review-ready
# 2. 根据反馈修改
# ... 修改代码 ...
# 3. 提交修改
git add .
git commit -m "address review feedback"
# 4. 推送更新
git push origin feature/review-ready
# 5. 如果历史被重写
git push --force-with-lease origin feature/review-ready
审查后合并
# 1. 合并到主分支
git switch main
git merge feature/review-ready
# 2. 或者使用 squash 合并
git merge --squash feature/review-ready
git commit -m "feat: implement new feature"
# 3. 推送主分支
git push origin main
# 4. 清理分支
git branch -d feature/review-ready
git push origin --delete feature/review-ready
4.8 大仓库优化
浅克隆
# 只克隆最近提交
git clone --depth=1 <url>
# 增加深度
git fetch --unshallow
# 浅克隆特定分支
git clone --depth=1 --branch=main <url>
部分克隆
# 不克隆文件内容
git clone --filter=blob:none <url>
# 不克隆大文件
git clone --filter=blob:limit=1m <url>
# 只克隆特定目录
git clone --filter=tree:0 <url>
git sparse-checkout init --cone
git sparse-checkout set src/ docs/
稀疏检出
# 启用稀疏检出
git sparse-checkout init --cone
# 设置要检出的目录
git sparse-checkout set src/ tests/
# 添加更多目录
git sparse-checkout add docs/
# 禁用稀疏检出
git sparse-checkout disable
仓库清理
# 清理大文件
git filter-branch --tree-filter 'rm -f large-file.txt' HEAD
# 使用 filter-repo(推荐)
git filter-repo --path large-file.txt --invert-paths
# 清理引用
git for-each-ref --format="delete %(refname)" refs/original | git update-ref --stdin
git reflog expire --expire=now --all
git gc --prune=now --aggressive
第五部分:协作策略与最佳实践
5.1 工作流策略
主干开发(Trunk-based Development)
特点:
- 主分支始终可部署
- 功能分支生命周期短(1-2 天)
- 频繁集成,小步快跑
命令流程:
# 开发新功能
git switch main
git pull origin main
git switch -c feature/quick-fix
# ... 开发 ...
git add .
git commit -m "feat: quick fix"
git push -u origin feature/quick-fix
# 创建 PR,快速合并
GitFlow 工作流
特点:
- 严格的分支模型
- 长期功能分支
- 发布分支管理
分支结构:
main (生产)
├── develop (开发)
├── feature/user-auth (功能)
├── release/v1.2.0 (发布)
└── hotfix/critical-bug (热修复)
GitHub Flow
特点:
- 简单的主分支模型
- 功能分支 + PR
- 持续部署
命令流程:
# 创建功能分支
git switch -c feature/new-feature
# ... 开发 ...
git push -u origin feature/new-feature
# 创建 PR,代码审查后合并
5.2 提交规范
Conventional Commits 规范
# 格式:<type>[optional scope]: <description>
# 类型
feat: 新功能
fix: 修复 bug
docs: 文档更新
style: 代码格式(不影响功能)
refactor: 重构
test: 测试相关
chore: 构建过程或辅助工具的变动
# 示例
git commit -m "feat(auth): add OAuth2 login"
git commit -m "fix(api): resolve timeout issue"
git commit -m "docs: update installation guide"
提交信息最佳实践
# 好的提交信息
git commit -m "feat: add user authentication system"
git commit -m "fix: resolve memory leak in image processing"
git commit -m "docs: update API documentation for v2.0"
# 避免的提交信息
git commit -m "fix"
git commit -m "update"
git commit -m "changes"
多行提交信息
git commit -m "feat: add user authentication
- Implement OAuth2 integration
- Add JWT token management
- Update user model schema
- Add authentication middleware
Closes #123"
5.3 配置推荐
全局配置
# 用户信息
git config --global user.name "Your Name"
git config --global user.email "your@email.com"
# 默认分支
git config --global init.defaultBranch main
# 拉取策略
git config --global pull.rebase true
git config --global rebase.autoStash true
# 推送策略
git config --global push.default simple
git config --global push.autoSetupRemote true
# 合并策略
git config --global merge.ff only
git config --global rerere.enabled true
# 行结尾处理
git config --global core.autocrlf input
git config --global core.ignorecase false
# 凭证管理
git config --global credential.helper osxkeychain # macOS
git config --global credential.helper manager-core # Windows
git config --global credential.helper store # Linux
# 别名配置
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.unstage 'reset HEAD --'
git config --global alias.last 'log -1 HEAD'
git config --global alias.visual '!gitk'
项目特定配置
# 在项目根目录
git config user.name "Project Name"
git config user.email "project@company.com"
git config core.autocrlf false
git config merge.ours.driver true
第六部分:问题排查与救命技巧
6.1 常见错误解读
"Your branch is ahead of 'origin/main' by X commits"
含义:本地分支比远程分支多了 X 个提交 解决:
git push origin main
"Your branch is behind 'origin/main' by X commits"
含义:远程分支比本地分支多了 X 个提交 解决:
git pull origin main
# 或
git fetch origin
git rebase origin/main
"You are in 'detached HEAD' state"
含义:HEAD 指向了某个提交而不是分支 解决:
# 创建新分支
git switch -c new-branch
# 或切换到现有分支
git switch main
"fatal: refusing to merge unrelated histories"
含义:两个仓库没有共同历史 解决:
git merge --allow-unrelated-histories origin/main
"error: failed to push some refs"
含义:远程有本地没有的提交 解决:
git pull origin main
git push origin main
# 或强制推送(危险)
git push --force-with-lease origin main
"merge: local changes would be overwritten"
含义:本地有未提交的更改 解决:
# 暂存更改
git stash
git pull origin main
git stash pop
# 或提交更改
git add .
git commit -m "wip: save changes"
git pull origin main
6.2 数据恢复技巧
使用 reflog 恢复
# 查看所有操作历史
git reflog
# 恢复到特定操作
git reset --hard HEAD@{2}
# 恢复被删除的分支
git branch recover-branch <commit-hash>
恢复误删的文件
# 从暂存区恢复
git checkout HEAD -- <file>
# 从特定提交恢复
git checkout <commit-hash> -- <file>
# 从其他分支恢复
git checkout <branch-name> -- <file>
恢复误删的分支
# 1. 查看 reflog
git reflog
# 2. 找到分支的最后提交
git reflog | grep <branch-name>
# 3. 恢复分支
git branch <branch-name> <commit-hash>
恢复误删的提交
# 1. 查看 reflog
git reflog
# 2. 找到提交的哈希
git reflog | grep <commit-message>
# 3. 恢复提交
git cherry-pick <commit-hash>
6.3 性能问题诊断
检查仓库大小
# 查看仓库大小
du -sh .git
# 查看对象统计
git count-objects -vH
# 查看最大的文件
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | sed -n 's/^blob //p' | sort --numeric-sort --key=2 | tail -10
清理大文件
# 查找大文件
git rev-list --objects --all | git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | awk '/^blob/ {if ($3 > 1000000) print $3 " " $4}' | sort -nr
# 使用 filter-repo 清理
git filter-repo --strip-blobs-bigger-than 10M
优化仓库
# 垃圾回收
git gc --aggressive --prune=now
# 重新打包
git repack -Ad
# 清理引用
git for-each-ref --format="delete %(refname)" refs/original | git update-ref --stdin
git reflog expire --expire=now --all
git gc --prune=now
6.4 冲突解决流程图
遇到冲突
↓
git status 查看冲突文件
↓
编辑冲突文件
↓
解决冲突标记
<<<<<<< HEAD
当前分支内容
=======
目标分支内容
>>>>>>> branch-name
↓
删除冲突标记
↓
git add <resolved-file>
↓
git commit (merge) 或 git rebase --continue (rebase)
↓
冲突解决完成
6.5 常见误区与陷阱
误区 1:"pull 总是安全的"
问题:git pull
可能做 merge 或 rebase,会改变历史 正确做法:
git fetch origin
git log HEAD..origin/main # 查看远程更新
git merge origin/main # 或 git rebase origin/main
误区 2:"reset --hard 就是回滚"
问题:reset --hard
会丢失工作区更改 正确做法:
# 已推送的提交用 revert
git revert <commit>
# 未推送的提交用 reset
git reset --soft HEAD~1 # 保留更改
git reset --mixed HEAD~1 # 保留工作区
git reset --hard HEAD~1 # 丢弃所有更改
误区 3:"强推直接 --force"
问题:可能覆盖他人的工作 正确做法:
git push --force-with-lease origin main
误区 4:"rebase 总是比 merge 好"
问题:rebase 会重写历史,不适合公共分支 正确做法:
- 个人分支:用 rebase 保持线性历史
- 公共分支:用 merge 保留真实历史
救命技巧
# 1. reflog 是救命稻草
git reflog
# 2. 开启 rerere 自动解决重复冲突
git config --global rerere.enabled true
# 3. 使用 --force-with-lease 安全强推
git push --force-with-lease origin main
# 4. 定期备份重要分支
git push origin <important-branch>
# 5. 使用 worktree 并行开发
git worktree add ../hotfix main
第七部分:高级主题
7.1 Plumbing 命令索引
Plumbing 命令是 Git 的底层命令,直接操作对象和引用。
对象操作
# 创建对象
echo "content" | git hash-object -w --stdin
git hash-object -w <file>
# 查看对象
git cat-file -t <object> # 查看对象类型
git cat-file -p <object> # 查看对象内容
git cat-file -s <object> # 查看对象大小
# 列出树对象
git ls-tree <tree>
git ls-tree -r <tree> # 递归列出
引用操作
# 解析引用
git rev-parse HEAD
git rev-parse main
git rev-parse origin/main
# 更新引用
git update-ref refs/heads/new-branch <commit>
# 列出引用
git for-each-ref
git show-ref
索引操作
# 更新索引
git update-index --add <file>
git update-index --remove <file>
git update-index --skip-worktree <file>
# 读取索引
git ls-files
git ls-files --stage
7.2 底层对象操作
从零创建提交
# 1. 创建文件内容
echo "Hello World" | git hash-object -w --stdin
# 输出:<blob-hash>
# 2. 创建树对象
git update-index --add --cacheinfo 100644 <blob-hash> hello.txt
git write-tree
# 输出:<tree-hash>
# 3. 创建提交对象
git commit-tree <tree-hash> -m "Initial commit"
# 输出:<commit-hash>
# 4. 更新分支引用
git update-ref refs/heads/main <commit-hash>
查看对象关系
# 查看提交的树
git cat-file -p <commit> | grep tree
# 查看树的内容
git cat-file -p <tree-hash>
# 查看文件内容
git cat-file -p <blob-hash>
7.3 Git Hooks 应用
客户端 Hooks
# pre-commit: 提交前检查
#!/bin/sh
# 运行测试
npm test
# 检查代码格式
npm run lint
# commit-msg: 检查提交信息
#!/bin/sh
# 检查提交信息格式
if ! grep -qE "^(feat|fix|docs|style|refactor|test|chore):" "$1"; then
echo "Invalid commit message format"
exit 1
fi
# pre-push: 推送前检查
#!/bin/sh
# 运行完整测试套件
npm run test:all
服务端 Hooks
# pre-receive: 接收推送前
#!/bin/bash
# 检查分支保护
if [[ "$1" == "refs/heads/main" ]]; then
echo "Direct push to main is not allowed"
exit 1
fi
# update: 更新引用前
#!/bin/bash
# 检查提交权限
if [[ "$1" == "refs/heads/main" ]]; then
# 检查用户权限
if ! is_maintainer "$USER"; then
echo "Only maintainers can push to main"
exit 1
fi
fi
安装 Hooks
# 复制 hook 脚本
cp pre-commit .git/hooks/
chmod +x .git/hooks/pre-commit
# 或使用工具管理
npm install --save-dev husky
npx husky install
npx husky add .husky/pre-commit "npm test"
7.4 部分克隆与稀疏检出
部分克隆类型
# 不克隆文件内容
git clone --filter=blob:none <url>
# 限制文件大小
git clone --filter=blob:limit=1m <url>
# 不克隆树对象
git clone --filter=tree:0 <url>
# 组合过滤
git clone --filter=blob:none --filter=tree:0 <url>
稀疏检出配置
# 启用稀疏检出
git sparse-checkout init --cone
# 设置要检出的目录
git sparse-checkout set src/ tests/
# 添加更多目录
git sparse-checkout add docs/
# 列出当前配置
git sparse-checkout list
# 禁用稀疏检出
git sparse-checkout disable
大仓库优化策略
# 1. 浅克隆
git clone --depth=1 <url>
# 2. 部分克隆
git clone --filter=blob:none <url>
# 3. 稀疏检出
git sparse-checkout init --cone
git sparse-checkout set src/
# 4. 定期清理
git gc --aggressive --prune=now
附录
A. 命令速查表
日常使用
命令 | 功能 | 常用参数 |
---|---|---|
git status | 查看状态 | -sb , --porcelain |
git add | 添加文件 | -p , -A , -u |
git commit | 提交更改 | -m , -am , --amend |
git push | 推送更改 | -u , --force-with-lease |
git pull | 拉取更改 | --rebase , --ff-only |
分支操作
命令 | 功能 | 常用参数 |
---|---|---|
git branch | 分支管理 | -a , -vv , -d , -D |
git switch | 切换分支 | -c , - |
git merge | 合并分支 | --no-ff , --ff-only , --squash |
git rebase | 变基 | -i , --onto , --continue |
历史操作
命令 | 功能 | 常用参数 |
---|---|---|
git log | 查看历史 | --oneline , --graph , --decorate |
git show | 查看提交 | <commit> , --stat |
git reset | 重置提交 | --soft , --mixed , --hard |
git revert | 撤销提交 | -m , --no-commit |
远程操作
命令 | 功能 | 常用参数 |
---|---|---|
git fetch | 获取更新 | --all , --prune |
git remote | 远程管理 | -v , add , remove |
git clone | 克隆仓库 | --depth , --filter |
B. 全部命令清单
仓库管理
init
- 初始化仓库clone
- 克隆仓库config
- 配置管理help
- 帮助信息
文件操作
add
- 添加文件rm
- 删除文件mv
- 移动文件restore
- 恢复文件checkout
- 切换/恢复(老命令)
提交管理
commit
- 创建提交reset
- 重置提交revert
- 撤销提交amend
- 修改提交reflog
- 操作历史
分支管理
branch
- 分支操作switch
- 切换分支merge
- 合并分支rebase
- 变基操作cherry-pick
- 拣选提交
远程协作
remote
- 远程管理fetch
- 获取更新pull
- 拉取更新push
- 推送更新
高级功能
stash
- 暂存工作worktree
- 多工作区bisect
- 二分查找blame
- 文件历史grep
- 内容搜索
维护清理
gc
- 垃圾回收fsck
- 完整性检查prune
- 清理对象repack
- 重新打包clean
- 清理文件
发布管理
tag
- 标签管理archive
- 打包导出format-patch
- 生成补丁am
- 应用补丁submodule
- 子模块
C. 配置项完整列表
核心配置
# 用户信息
user.name = "Your Name"
user.email = "your@email.com"
# 默认分支
init.defaultBranch = main
# 行结尾处理
core.autocrlf = input
core.ignorecase = false
core.filemode = true
# 凭证管理
credential.helper = osxkeychain
拉取配置
# 拉取策略
pull.rebase = true
rebase.autoStash = true
# 获取配置
fetch.prune = true
fetch.pruneTags = true
推送配置
# 推送策略
push.default = simple
push.autoSetupRemote = true
push.followTags = true
合并配置
# 合并策略
merge.ff = only
merge.tool = vimdiff
rerere.enabled = true
别名配置
# 常用别名
alias.st = status
alias.co = checkout
alias.br = branch
alias.ci = commit
alias.unstage = reset HEAD --
alias.last = log -1 HEAD
alias.visual = !gitk
D. 参考资源
官方文档
在线工具
学习资源
- Learn Git Branching - 交互式学习
- GitHub Learning Lab - 实践课程
- Atlassian Git Tutorials - 详细教程
工具推荐
- GUI 工具:SourceTree、GitKraken、Tower
- IDE 集成:VS Code、IntelliJ IDEA、Vim
- 命令行工具:tig、lazygit、delta
版权与使用:本手册可在团队内自由传播与二开。若需 PDF/HTML 版本可由本 Markdown 导出。
建议:把本文件放到你的知识库(Obsidian/Notion)并收藏关键段落。
更新:定期更新以保持与最新 Git 版本的兼容性。