Git Troubleshooting Skill
Git 故障排查技巧
This skill provides comprehensive guidance on diagnosing and resolving git issues, recovering from mistakes, fixing corrupted repositories, and handling common error scenarios.
本技巧提供关于诊断和解决Git问题、从操作失误中恢复、修复损坏的仓库以及处理常见错误场景的全面指南。
Activate this skill when:
- Encountering git error messages
- Recovering lost commits or branches
- Fixing corrupted repositories
- Resolving detached HEAD state
- Handling botched merges or rebases
- Diagnosing repository issues
- Recovering from force push
- Fixing authentication problems
在以下场景中激活本技巧:
- 遇到Git错误提示
- 恢复丢失的提交或分支
- 修复损坏的代码仓库
- 解决分离HEAD状态
- 处理失败的合并或变基操作
- 诊断仓库问题
- 从强制推送操作中恢复
- 修复身份验证问题
Recovering Lost Commits
恢复丢失的提交
View reflog (local history of HEAD)
View reflog (local history of HEAD)
View reflog for specific branch
View reflog for specific branch
git reflog show branch-name
git reflog show branch-name
Output example:
Output example:
abc123 HEAD@{0}: commit: feat: add authentication
abc123 HEAD@{0}: commit: feat: add authentication
def456 HEAD@{1}: commit: fix: resolve bug
def456 HEAD@{1}: commit: fix: resolve bug
ghi789 HEAD@{2}: reset: moving to HEAD~1
ghi789 HEAD@{2}: reset: moving to HEAD~1
Recover lost commit
Recover lost commit
Or create branch from lost commit
Or create branch from lost commit
git branch recovered-branch abc123
git branch recovered-branch abc123
Or reset to lost commit
Or reset to lost commit
Finding Dangling Commits
查找悬挂提交
Find all unreachable objects
Find all unreachable objects
dangling commit abc123
dangling commit abc123
dangling blob def456
dangling blob def456
View dangling commit
View dangling commit
Recover dangling commit
Recover dangling commit
git branch recovered abc123
git branch recovered abc123
Recovering Deleted Branch
恢复已删除的分支
Find branch commit in reflog
Find branch commit in reflog
Look for branch deletion:
Look for branch deletion:
abc123 HEAD@{5}: checkout: moving from feature-branch to main
abc123 HEAD@{5}: checkout: moving from feature-branch to main
Recreate branch
Recreate branch
git branch feature-branch abc123
git branch feature-branch abc123
Or if branch was merged before deletion
Or if branch was merged before deletion
git log --all --oneline | grep "feature"
git branch feature-branch def456
git log --all --oneline | grep "feature"
git branch feature-branch def456
Recovering After Reset
重置操作后的恢复
After accidental reset --hard
After accidental reset --hard
Find commit before reset:
Find commit before reset:
abc123 HEAD@{0}: reset: moving to HEAD~5
abc123 HEAD@{0}: reset: moving to HEAD~5
def456 HEAD@{1}: commit: last good commit
def456 HEAD@{1}: commit: last good commit
Restore to previous state
Restore to previous state
Or create recovery branch
Or create recovery branch
git branch recovery def456
git branch recovery def456
Resolving Detached HEAD
解决分离HEAD问题
Understanding Detached HEAD
理解分离HEAD
Detached HEAD state occurs when:
Detached HEAD state occurs when:
git checkout abc123
git checkout v1.0.0
git checkout origin/main
git checkout abc123
git checkout v1.0.0
git checkout origin/main
HEAD is not attached to any branch
HEAD is not attached to any branch
Recovering from Detached HEAD
从分离HEAD状态恢复
Check current state
Check current state
HEAD detached at abc123
HEAD detached at abc123
Option 1: Create new branch
Option 1: Create new branch
git checkout -b new-branch-name
git checkout -b new-branch-name
Option 2: Return to previous branch
Option 2: Return to previous branch
Option 3: Reattach HEAD to branch
Option 3: Reattach HEAD to branch
git checkout -b temp-branch
git checkout main
git merge temp-branch
git checkout -b temp-branch
git checkout main
git merge temp-branch
If you made commits in detached HEAD:
If you made commits in detached HEAD:
Find the commits
Find the commits
git branch recovery-branch abc123
git branch recovery-branch abc123
Preventing Detached HEAD
预防分离HEAD问题
Instead of checking out tag directly
Instead of checking out tag directly
git checkout -b release-v1.0 v1.0.0
git checkout -b release-v1.0 v1.0.0
Instead of checking out remote branch
Instead of checking out remote branch
git checkout -b local-feature origin/feature-branch
git checkout -b local-feature origin/feature-branch
Check if HEAD is detached
Check if HEAD is detached
git symbolic-ref -q HEAD && echo "attached" || echo "detached"
git symbolic-ref -q HEAD && echo "attached" || echo "detached"
Fixing Merge Conflicts
修复合并冲突
Understanding Conflict Markers
理解冲突标记
<<<<<<< HEAD (Current Change)
int result = add(a, b);
||||||| merged common ancestors (Base)
int result = sum(a, b);
=======
int sum = calculate(a, b);
>>>>>>> feature-branch (Incoming Change)
<<<<<<< HEAD (Current Change)
int result = add(a, b);
||||||| merged common ancestors (Base)
int result = sum(a, b);
=======
int sum = calculate(a, b);
>>>>>>> feature-branch (Incoming Change)
Basic Conflict Resolution
基础冲突解决
When merge conflict occurs
When merge conflict occurs
both modified: file.go
both modified: file.go
View conflict
View conflict
Option 1: Keep ours (current branch)
Option 1: Keep ours (current branch)
git checkout --ours file.go
git add file.go
git checkout --ours file.go
git add file.go
Option 2: Keep theirs (incoming branch)
Option 2: Keep theirs (incoming branch)
git checkout --theirs file.go
git add file.go
git checkout --theirs file.go
git add file.go
Option 3: Manual resolution
Option 3: Manual resolution
Edit file.go to resolve conflicts
Edit file.go to resolve conflicts
Complete merge
Complete merge
Abort cherry-pick
Abort cherry-pick
Abort am (apply mailbox)
Abort am (apply mailbox)
Complex Conflict Resolution
复杂冲突解决
Use merge tool
Use merge tool
View three-way diff
View three-way diff
git diff --ours
git diff --theirs
git diff --base
git diff --ours
git diff --theirs
git diff --base
Show conflicts with context
Show conflicts with context
List conflicted files
List conflicted files
git diff --name-only --diff-filter=U
git diff --name-only --diff-filter=U
After resolving all conflicts
After resolving all conflicts
Fixing Botched Rebase
修复失败的变基操作
Recovering from Failed Rebase
从失败的变基中恢复
Abort current rebase
Abort current rebase
Find state before rebase
Find state before rebase
abc123 HEAD@{1}: rebase: checkout main
abc123 HEAD@{1}: rebase: checkout main
Return to pre-rebase state
Return to pre-rebase state
git reset --hard HEAD@{1}
git reset --hard HEAD@{1}
Alternative: use ORIG_HEAD
Alternative: use ORIG_HEAD
git reset --hard ORIG_HEAD
git reset --hard ORIG_HEAD
During rebase conflict
During rebase conflict
both modified: file.go
both modified: file.go
Resolve conflicts
Resolve conflicts
git add file.go
git rebase --continue
git add file.go
git rebase --continue
Skip problematic commit
Skip problematic commit
Edit commit during rebase
Edit commit during rebase
git commit --amend
git rebase --continue
git commit --amend
git rebase --continue
Rebase onto Wrong Branch
变基到错误分支
Find original branch point
Find original branch point
Reset to before rebase
Reset to before rebase
git reset --hard HEAD@{5}
git reset --hard HEAD@{5}
Rebase onto correct branch
Rebase onto correct branch
git rebase correct-branch
git rebase correct-branch
Repository Corruption
仓库损坏问题
Check repository integrity
Check repository integrity
Check connectivity
Check connectivity
git fsck --connectivity-only
git fsck --connectivity-only
Verify pack files
Verify pack files
git verify-pack -v .git/objects/pack/*.idx
git verify-pack -v .git/objects/pack/*.idx
Fixing Corrupted Objects
修复损坏的对象
Remove corrupted object
Remove corrupted object
rm .git/objects/ab/cd1234...
rm .git/objects/ab/cd1234...
Try to recover from remote
Try to recover from remote
Rebuild object database
Rebuild object database
Aggressive cleanup
Aggressive cleanup
git gc --aggressive --prune=now
git gc --aggressive --prune=now
Fixing Index Corruption
修复索引损坏
Remove corrupted index
Remove corrupted index
Rebuild index
Rebuild index
Or reset to HEAD
Or reset to HEAD
Recovering from Bad Pack File
从损坏的Pack文件中恢复
Unpack corrupted pack
Unpack corrupted pack
git unpack-objects < .git/objects/pack/pack-*.pack
git unpack-objects < .git/objects/pack/pack-*.pack
Remove corrupted pack
Remove corrupted pack
rm .git/objects/pack/pack-*
rm .git/objects/pack/pack-*
Repack repository
Repack repository
Verify integrity
Verify integrity
Corrupted Branch References
损坏的分支引用
View all references
View all references
Manual reference fix
Manual reference fix
echo "abc123def456" > .git/refs/heads/branch-name
echo "abc123def456" > .git/refs/heads/branch-name
Or use update-ref
Or use update-ref
git update-ref refs/heads/branch-name abc123
git update-ref refs/heads/branch-name abc123
Delete corrupted reference
Delete corrupted reference
git update-ref -d refs/heads/bad-branch
git update-ref -d refs/heads/bad-branch
Fixing HEAD Reference
修复HEAD引用
HEAD is corrupted or missing
HEAD is corrupted or missing
echo "ref: refs/heads/main" > .git/HEAD
echo "ref: refs/heads/main" > .git/HEAD
Or point to specific commit
Or point to specific commit
echo "abc123def456" > .git/HEAD
echo "abc123def456" > .git/HEAD
Pruning Stale References
清理过时引用
Remove stale remote references
Remove stale remote references
Remove all stale references
Remove all stale references
Remove all remote branches that no longer exist
Remove all remote branches that no longer exist
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -D
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -D
Undo Last Commit (Keep Changes)
撤销最近一次提交(保留变更)
Soft reset (changes staged)
Soft reset (changes staged)
Mixed reset (changes unstaged)
Mixed reset (changes unstaged)
Undo Last Commit (Discard Changes)
撤销最近一次提交(丢弃变更)
Can still recover via reflog
Can still recover via reflog
git reflog
git reset --hard HEAD@{1}
git reflog
git reset --hard HEAD@{1}
Undo Multiple Commits
撤销多次提交
Reset to specific commit
Reset to specific commit
Revert multiple commits (creates new commits)
Revert multiple commits (creates new commits)
Interactive rebase to remove commits
Interactive rebase to remove commits
Mark commits with 'drop' or delete lines
Mark commits with 'drop' or delete lines
Undo Changes to File
撤销文件的变更
Discard uncommitted changes
Discard uncommitted changes
Or in Git 2.23+
Or in Git 2.23+
Discard staged changes
Discard staged changes
git reset HEAD file.go
git restore file.go
git reset HEAD file.go
git restore file.go
Or in Git 2.23+
Or in Git 2.23+
git restore --staged file.go
git restore file.go
git restore --staged file.go
git restore file.go
Restore file from specific commit
Restore file from specific commit
git checkout abc123 -- file.go
git checkout abc123 -- file.go
Undo Public Commits
撤销已公开的提交
Never use reset on public commits
Never use reset on public commits
Use revert instead
Use revert instead
git revert HEAD
git revert abc123
git revert abc123..def456
git revert HEAD
git revert abc123
git revert abc123..def456
Revert merge commit
Revert merge commit
git revert -m 1 merge-commit-hash
git revert -m 1 merge-commit-hash
Handling Force Push Issues
处理强制推送问题
Recovering After Force Push
强制推送后的恢复
If you were force pushed over
If you were force pushed over
abc123 HEAD@{1}: pull: Fast-forward
abc123 HEAD@{1}: pull: Fast-forward
Recover your commits
Recover your commits
git reset --hard HEAD@{1}
git reset --hard HEAD@{1}
Create backup branch
Create backup branch
Merge with force-pushed branch
Merge with force-pushed branch
git pull origin main
git merge backup-branch
git pull origin main
git merge backup-branch
Preventing Force Push Damage
预防强制推送造成的损失
Always fetch before force push
Always fetch before force push
View what would be lost
View what would be lost
git log origin/main..HEAD
git log origin/main..HEAD
Force push with lease (safer)
Force push with lease (safer)
git push --force-with-lease origin main
git push --force-with-lease origin main
Configure push protection
Configure push protection
git config --global push.default simple
git config --global push.default simple
Find large files in history
Find large files in history
git rev-list --objects --all |
git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' |
awk '/^blob/ {print substr($0,6)}' |
sort --numeric-sort --key=2 |
tail -10
git rev-list --objects --all |
git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' |
awk '/^blob/ {print substr($0,6)}' |
sort --numeric-sort --key=2 |
tail -10
Verify current large files
Verify current large files
git ls-files | xargs ls -lh | sort -k 5 -h -r | head -20
git ls-files | xargs ls -lh | sort -k 5 -h -r | head -20
Removing Large Files
移除大文件
Using git-filter-repo (recommended)
Using git-filter-repo (recommended)
git filter-repo --path large-file.bin --invert-paths
git filter-repo --path large-file.bin --invert-paths
bfg --strip-blobs-bigger-than 100M
bfg --strip-blobs-bigger-than 100M
After removal
After removal
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push --force origin main
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git push --force origin main
Preventing Large Files
预防大文件提交
Configure pre-commit hook
Configure pre-commit hook
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
if git diff --cached --name-only | xargs du -h | awk '$1 ~ /M$|G$/' | grep .; then
echo "Error: Large file detected"
exit 1
fi
EOF
chmod +x .git/hooks/pre-commit
cat > .git/hooks/pre-commit << 'EOF'
#!/bin/bash
if git diff --cached --name-only | xargs du -h | awk '$1 ~ /M$|G$/' | grep .; then
echo "Error: Large file detected"
exit 1
fi
EOF
chmod +x .git/hooks/pre-commit
Authentication Issues
身份验证问题
Test SSH connection
Test SSH connection
Check SSH key
Check SSH key
Generate new SSH key
Generate new SSH key
ssh-keygen -t ed25519 -C "email@example.com"
ssh-keygen -t ed25519 -C "email@example.com"
Add key to ssh-agent
Add key to ssh-agent
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
Configure SSH
Configure SSH
cat > ~/.ssh/config << EOF
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
EOF
cat > ~/.ssh/config << EOF
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
EOF
HTTPS Authentication
HTTPS身份验证
Cache credentials
Cache credentials
git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=3600'
git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=3600'
Or use store (less secure)
Or use store (less secure)
git config --global credential.helper store
git config --global credential.helper store
Update remote URL
Update remote URL
Use personal access token
Use personal access token
Check remote URL
Check remote URL
Change to SSH
Change to SSH
git remote set-url origin git@github.com:user/repo.git
git remote set-url origin git@github.com:user/repo.git
Change to HTTPS
Change to HTTPS
Verify permissions
Verify permissions
ls -la .git/
chmod -R u+rw .git/
ls -la .git/
chmod -R u+rw .git/
Submodule Not Initialized
子模块未初始化
Initialize submodules
Initialize submodules
git submodule init
git submodule update
git submodule init
git submodule update
Or in one command
Or in one command
git submodule update --init --recursive
git submodule update --init --recursive
Detached HEAD in Submodule
子模块出现分离HEAD
Enter submodule
Enter submodule
Create branch
Create branch
Or attach to existing branch
Or attach to existing branch
git checkout main
git pull origin main
git checkout main
git pull origin main
Update parent repo
Update parent repo
cd ..
git add submodule-dir
git commit -m "chore: update submodule"
cd ..
git add submodule-dir
git commit -m "chore: update submodule"
Check submodule status
Check submodule status
Reset submodule
Reset submodule
git submodule update --init --force
git submodule update --init --force
Remove and re-add submodule
Remove and re-add submodule
git submodule deinit -f path/to/submodule
git rm -f path/to/submodule
git submodule add <url> path/to/submodule
git submodule deinit -f path/to/submodule
git rm -f path/to/submodule
git submodule add <url> path/to/submodule
Optimize repository
Optimize repository
Repack efficiently
Repack efficiently
git repack -a -d --depth=250 --window=250
git repack -a -d --depth=250 --window=250
Prune old objects
Prune old objects
Clean up unnecessary files
Clean up unnecessary files
Shallow clone
Shallow clone
git clone --depth 1 <url>
git clone --depth 1 <url>
Fetch only one branch
Fetch only one branch
git clone --single-branch --branch main <url>
git clone --single-branch --branch main <url>
Partial clone
Partial clone
git clone --filter=blob:none <url>
git clone --filter=blob:none <url>
Sparse checkout
Sparse checkout
git sparse-checkout init --cone
git sparse-checkout set folder1 folder2
git sparse-checkout init --cone
git sparse-checkout set folder1 folder2
Increase memory limits
Increase memory limits
git config --global pack.windowMemory "100m"
git config --global pack.packSizeLimit "100m"
git config --global pack.threads "1"
git config --global pack.windowMemory "100m"
git config --global pack.packSizeLimit "100m"
git config --global pack.threads "1"
Disable delta compression temporarily
Disable delta compression temporarily
git config --global pack.compression 0
git config --global pack.compression 0
Common Error Messages
常见错误提示
"fatal: refusing to merge unrelated histories"
"fatal: refusing to merge unrelated histories"
Allow merging unrelated histories
Allow merging unrelated histories
git pull origin main --allow-unrelated-histories
git pull origin main --allow-unrelated-histories
"fatal: not a git repository"
"fatal: not a git repository"
Reinitialize repository
Reinitialize repository
Or check if .git directory exists
Or check if .git directory exists
Restore from backup if corrupted
Restore from backup if corrupted
"error: Your local changes would be overwritten"
"error: Your local changes would be overwritten"
Stash changes
Stash changes
git stash
git pull
git stash pop
git stash
git pull
git stash pop
Or discard changes
Or discard changes
git reset --hard HEAD
git pull
git reset --hard HEAD
git pull
"error: failed to push some refs"
"error: failed to push some refs"
Fetch and merge first
Fetch and merge first
git pull --rebase origin main
git pull --rebase origin main
Force push (dangerous)
Force push (dangerous)
git push --force origin main
git push --force origin main
Safer force push
Safer force push
git push --force-with-lease origin main
git push --force-with-lease origin main
"fatal: unable to access: SSL certificate problem"
"fatal: unable to access: SSL certificate problem"
Disable SSL verification (not recommended)
Disable SSL verification (not recommended)
git config --global http.sslVerify false
git config --global http.sslVerify false
Or update SSL certificates
Or update SSL certificates
git config --global http.sslCAInfo /path/to/cacert.pem
git config --global http.sslCAInfo /path/to/cacert.pem
Repository Health Check
仓库健康检查
Full integrity check
Full integrity check
Check connectivity
Check connectivity
git fsck --connectivity-only
git fsck --connectivity-only
Verify objects
Verify objects
git verify-pack -v .git/objects/pack/*.idx
git verify-pack -v .git/objects/pack/*.idx
git reflog expire --dry-run --all
git reflog expire --dry-run --all
Analyze repository
Analyze repository
Enable verbose logging
Enable verbose logging
GIT_TRACE=1 git status
GIT_TRACE=1 git pull
GIT_TRACE=1 git status
GIT_TRACE=1 git pull
Debug specific operations
Debug specific operations
GIT_TRACE_PACKET=1 git fetch
GIT_TRACE_PERFORMANCE=1 git diff
GIT_CURL_VERBOSE=1 git push
GIT_TRACE_PACKET=1 git fetch
GIT_TRACE_PERFORMANCE=1 git diff
GIT_CURL_VERBOSE=1 git push
Configuration debugging
Configuration debugging
git config --list --show-origin
git config --list --show-scope
git config --list --show-origin
git config --list --show-scope
Prevention Strategies
预防策略
- Regular Backups: Create backup branches before risky operations
- Use Reflog: Reflog is your safety net, keep it clean
- Enable Rerere: Reuse recorded conflict resolutions
- Protect Branches: Use branch protection rules
- Pre-commit Hooks: Validate commits before they're made
- Regular Maintenance: Run periodically
- Test Before Force Push: Always verify with
- Communication: Inform team about disruptive operations
- Learn Git Internals: Understanding how git works prevents issues
- Keep Git Updated: Use latest stable version
- 定期备份: 在执行风险操作前创建备份分支
- 使用Reflog: Reflog是你的安全网,注意保持其整洁
- 启用Rerere: 复用已记录的冲突解决结果
- 分支保护: 使用分支保护规则
- Pre-commit钩子: 在提交完成前进行校验
- 定期维护: 定期执行进行仓库优化
- 强制推送前测试: 始终使用验证操作
- 团队沟通: 告知团队成员可能造成影响的操作
- 学习Git内部原理: 理解Git的运行机制可以避免很多问题
- 保持Git版本更新: 使用最新的稳定版本
Additional troubleshooting guides are available in the
directory:
- - Step-by-step recovery procedures
- - Diagnostic and recovery scripts
- - Problem diagnosis workflows
- Git error message database
- Recovery procedure documentation
- Git internal structure guides
- Common pitfall documentation
- - 分步恢复流程
- - 诊断和恢复脚本
- - 问题诊断工作流
- Git错误提示数据库
- 恢复流程文档
- Git内部结构指南
- 常见陷阱文档