git-troubleshooting
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGit 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问题、从操作失误中恢复、修复损坏的仓库以及处理常见错误场景的全面指南。
When to Use
适用场景
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
恢复丢失的提交
Using Reflog
使用Reflog
bash
undefinedbash
undefinedView reflog (local history of HEAD)
View reflog (local history of HEAD)
git reflog
git reflog
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
git cherry-pick abc123
git cherry-pick abc123
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
git reset --hard abc123
undefinedgit reset --hard abc123
undefinedFinding Dangling Commits
查找悬挂提交
bash
undefinedbash
undefinedFind all unreachable objects
Find all unreachable objects
git fsck --lost-found
git fsck --lost-found
Output:
Output:
dangling commit abc123
dangling commit abc123
dangling blob def456
dangling blob def456
View dangling commit
View dangling commit
git show abc123
git show abc123
Recover dangling commit
Recover dangling commit
git branch recovered abc123
git branch recovered abc123
Or merge it
Or merge it
git merge abc123
undefinedgit merge abc123
undefinedRecovering Deleted Branch
恢复已删除的分支
bash
undefinedbash
undefinedFind branch commit in reflog
Find branch commit in reflog
git reflog
git 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
undefinedgit log --all --oneline | grep "feature"
git branch feature-branch def456
undefinedRecovering After Reset
重置操作后的恢复
bash
undefinedbash
undefinedAfter accidental reset --hard
After accidental reset --hard
git reflog
git reflog
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
git reset --hard def456
git reset --hard def456
Or create recovery branch
Or create recovery branch
git branch recovery def456
undefinedgit branch recovery def456
undefinedResolving Detached HEAD
解决分离HEAD问题
Understanding Detached HEAD
理解分离HEAD
bash
undefinedbash
undefinedDetached 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
undefinedundefinedRecovering from Detached HEAD
从分离HEAD状态恢复
bash
undefinedbash
undefinedCheck current state
Check current state
git status
git status
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
git checkout main
git checkout main
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:
git reflog
git reflog
Find the commits
Find the commits
git branch recovery-branch abc123
undefinedgit branch recovery-branch abc123
undefinedPreventing Detached HEAD
预防分离HEAD问题
bash
undefinedbash
undefinedInstead 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"
undefinedgit symbolic-ref -q HEAD && echo "attached" || echo "detached"
undefinedFixing 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
基础冲突解决
bash
undefinedbash
undefinedWhen merge conflict occurs
When merge conflict occurs
git status
git status
both modified: file.go
both modified: file.go
View conflict
View conflict
cat file.go
cat file.go
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
git add file.go
git add file.go
Complete merge
Complete merge
git commit
undefinedgit commit
undefinedAborting Operations
中止操作
bash
undefinedbash
undefinedAbort merge
Abort merge
git merge --abort
git merge --abort
Abort rebase
Abort rebase
git rebase --abort
git rebase --abort
Abort cherry-pick
Abort cherry-pick
git cherry-pick --abort
git cherry-pick --abort
Abort revert
Abort revert
git revert --abort
git revert --abort
Abort am (apply mailbox)
Abort am (apply mailbox)
git am --abort
undefinedgit am --abort
undefinedComplex Conflict Resolution
复杂冲突解决
bash
undefinedbash
undefinedUse merge tool
Use merge tool
git mergetool
git mergetool
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
git diff --check
git diff --check
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
git add .
git commit
undefinedgit add .
git commit
undefinedFixing Botched Rebase
修复失败的变基操作
Recovering from Failed Rebase
从失败的变基中恢复
bash
undefinedbash
undefinedAbort current rebase
Abort current rebase
git rebase --abort
git rebase --abort
Find state before rebase
Find state before rebase
git reflog
git reflog
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
undefinedgit reset --hard ORIG_HEAD
undefinedRebase Conflicts
变基冲突
bash
undefinedbash
undefinedDuring rebase conflict
During rebase conflict
git status
git status
both modified: file.go
both modified: file.go
Resolve conflicts
Resolve conflicts
Edit file.go
Edit file.go
git add file.go
git rebase --continue
git add file.go
git rebase --continue
Skip problematic commit
Skip problematic commit
git rebase --skip
git rebase --skip
Edit commit during rebase
Edit commit during rebase
git commit --amend
git rebase --continue
undefinedgit commit --amend
git rebase --continue
undefinedRebase onto Wrong Branch
变基到错误分支
bash
undefinedbash
undefinedFind original branch point
Find original branch point
git reflog
git reflog
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
undefinedgit rebase correct-branch
undefinedRepository Corruption
仓库损坏问题
Detecting Corruption
检测损坏
bash
undefinedbash
undefinedCheck repository integrity
Check repository integrity
git fsck --full
git fsck --full
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
undefinedgit verify-pack -v .git/objects/pack/*.idx
undefinedFixing Corrupted Objects
修复损坏的对象
bash
undefinedbash
undefinedRemove 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
git fetch origin
git fetch origin
Rebuild object database
Rebuild object database
git gc --prune=now
git gc --prune=now
Aggressive cleanup
Aggressive cleanup
git gc --aggressive --prune=now
undefinedgit gc --aggressive --prune=now
undefinedFixing Index Corruption
修复索引损坏
bash
undefinedbash
undefinedRemove corrupted index
Remove corrupted index
rm .git/index
rm .git/index
Rebuild index
Rebuild index
git reset
git reset
Or reset to HEAD
Or reset to HEAD
git reset --hard HEAD
undefinedgit reset --hard HEAD
undefinedRecovering from Bad Pack File
从损坏的Pack文件中恢复
bash
undefinedbash
undefinedUnpack 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
git repack -a -d
git repack -a -d
Verify integrity
Verify integrity
git fsck --full
undefinedgit fsck --full
undefinedFixing References
修复引用问题
Corrupted Branch References
损坏的分支引用
bash
undefinedbash
undefinedView all references
View all references
git show-ref
git show-ref
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
undefinedgit update-ref -d refs/heads/bad-branch
undefinedFixing HEAD Reference
修复HEAD引用
bash
undefinedbash
undefinedHEAD 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
Verify HEAD
Verify HEAD
git symbolic-ref HEAD
undefinedgit symbolic-ref HEAD
undefinedPruning Stale References
清理过时引用
bash
undefinedbash
undefinedRemove stale remote references
Remove stale remote references
git remote prune origin
git remote prune origin
Remove all stale references
Remove all stale references
git fetch --prune
git fetch --prune
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
undefinedgit branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -D
undefinedUndoing Changes
撤销变更
Undo Last Commit (Keep Changes)
撤销最近一次提交(保留变更)
bash
undefinedbash
undefinedSoft reset (changes staged)
Soft reset (changes staged)
git reset --soft HEAD~1
git reset --soft HEAD~1
Mixed reset (changes unstaged)
Mixed reset (changes unstaged)
git reset HEAD~1
undefinedgit reset HEAD~1
undefinedUndo Last Commit (Discard Changes)
撤销最近一次提交(丢弃变更)
bash
undefinedbash
undefinedHard reset
Hard reset
git reset --hard HEAD~1
git reset --hard HEAD~1
Can still recover via reflog
Can still recover via reflog
git reflog
git reset --hard HEAD@{1}
undefinedgit reflog
git reset --hard HEAD@{1}
undefinedUndo Multiple Commits
撤销多次提交
bash
undefinedbash
undefinedReset to specific commit
Reset to specific commit
git reset --hard abc123
git reset --hard abc123
Revert multiple commits (creates new commits)
Revert multiple commits (creates new commits)
git revert HEAD~3..HEAD
git revert HEAD~3..HEAD
Interactive rebase to remove commits
Interactive rebase to remove commits
git rebase -i HEAD~5
git rebase -i HEAD~5
Mark commits with 'drop' or delete lines
Mark commits with 'drop' or delete lines
undefinedundefinedUndo Changes to File
撤销文件的变更
bash
undefinedbash
undefinedDiscard uncommitted changes
Discard uncommitted changes
git checkout -- file.go
git checkout -- file.go
Or in Git 2.23+
Or in Git 2.23+
git restore file.go
git restore file.go
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
undefinedgit checkout abc123 -- file.go
undefinedUndo Public Commits
撤销已公开的提交
bash
undefinedbash
undefinedNever 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
undefinedgit revert -m 1 merge-commit-hash
undefinedHandling Force Push Issues
处理强制推送问题
Recovering After Force Push
强制推送后的恢复
bash
undefinedbash
undefinedIf you were force pushed over
If you were force pushed over
git reflog
git reflog
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
git branch backup-branch
git branch backup-branch
Merge with force-pushed branch
Merge with force-pushed branch
git pull origin main
git merge backup-branch
undefinedgit pull origin main
git merge backup-branch
undefinedPreventing Force Push Damage
预防强制推送造成的损失
bash
undefinedbash
undefinedAlways fetch before force push
Always fetch before force push
git fetch origin
git fetch origin
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
undefinedgit config --global push.default simple
undefinedLarge File Issues
大文件问题
Finding Large Files
查找大文件
bash
undefinedbash
undefinedFind 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 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
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
undefinedgit ls-files | xargs ls -lh | sort -k 5 -h -r | head -20
undefinedRemoving Large Files
移除大文件
bash
undefinedbash
undefinedUsing 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
Using BFG
Using BFG
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
undefinedgit reflog expire --expire=now --all
git gc --prune=now --aggressive
git push --force origin main
undefinedPreventing Large Files
预防大文件提交
bash
undefinedbash
undefinedConfigure 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
undefinedcat > .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
undefinedAuthentication Issues
身份验证问题
SSH Key Problems
SSH密钥问题
bash
undefinedbash
undefinedTest SSH connection
Test SSH connection
ssh -T git@github.com
ssh -T git@github.com
Check SSH key
Check SSH key
ls -la ~/.ssh
ls -la ~/.ssh
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
undefinedcat > ~/.ssh/config << EOF
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
EOF
undefinedHTTPS Authentication
HTTPS身份验证
bash
undefinedbash
undefinedCache 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
git remote set-url origin https://github.com/user/repo.git
git remote set-url origin https://github.com/user/repo.git
Use personal access token
Use personal access token
git clone https://TOKEN@github.com/user/repo.git
undefinedgit clone https://TOKEN@github.com/user/repo.git
undefinedPermission Denied
权限被拒绝
bash
undefinedbash
undefinedCheck remote URL
Check remote URL
git remote -v
git remote -v
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
git remote set-url origin https://github.com/user/repo.git
git remote set-url origin https://github.com/user/repo.git
Verify permissions
Verify permissions
ls -la .git/
chmod -R u+rw .git/
undefinedls -la .git/
chmod -R u+rw .git/
undefinedSubmodule Issues
子模块问题
Submodule Not Initialized
子模块未初始化
bash
undefinedbash
undefinedInitialize 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
undefinedgit submodule update --init --recursive
undefinedDetached HEAD in Submodule
子模块出现分离HEAD
bash
undefinedbash
undefinedEnter submodule
Enter submodule
cd submodule-dir
cd submodule-dir
Create branch
Create branch
git checkout -b main
git checkout -b main
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"
undefinedcd ..
git add submodule-dir
git commit -m "chore: update submodule"
undefinedSubmodule Conflicts
子模块冲突
bash
undefinedbash
undefinedCheck submodule status
Check submodule status
git submodule status
git 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
undefinedgit submodule deinit -f path/to/submodule
git rm -f path/to/submodule
git submodule add <url> path/to/submodule
undefinedPerformance Issues
性能问题
Slow Operations
操作缓慢
bash
undefinedbash
undefinedOptimize repository
Optimize repository
git gc --aggressive
git gc --aggressive
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
git prune --expire now
git prune --expire now
Clean up unnecessary files
Clean up unnecessary files
git clean -fdx
undefinedgit clean -fdx
undefinedLarge Repository
大型仓库处理
bash
undefinedbash
undefinedShallow 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
undefinedgit sparse-checkout init --cone
git sparse-checkout set folder1 folder2
undefinedMemory Issues
内存问题
bash
undefinedbash
undefinedIncrease 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
undefinedgit config --global pack.compression 0
undefinedCommon Error Messages
常见错误提示
"fatal: refusing to merge unrelated histories"
"fatal: refusing to merge unrelated histories"
bash
undefinedbash
undefinedAllow merging unrelated histories
Allow merging unrelated histories
git pull origin main --allow-unrelated-histories
undefinedgit pull origin main --allow-unrelated-histories
undefined"fatal: not a git repository"
"fatal: not a git repository"
bash
undefinedbash
undefinedReinitialize repository
Reinitialize repository
git init
git init
Or check if .git directory exists
Or check if .git directory exists
ls -la .git
ls -la .git
Restore from backup if corrupted
Restore from backup if corrupted
undefinedundefined"error: Your local changes would be overwritten"
"error: Your local changes would be overwritten"
bash
undefinedbash
undefinedStash 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
undefinedgit reset --hard HEAD
git pull
undefined"error: failed to push some refs"
"error: failed to push some refs"
bash
undefinedbash
undefinedFetch and merge first
Fetch and merge first
git pull origin main
git pull origin main
Or rebase
Or rebase
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
undefinedgit push --force-with-lease origin main
undefined"fatal: unable to access: SSL certificate problem"
"fatal: unable to access: SSL certificate problem"
bash
undefinedbash
undefinedDisable 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
undefinedgit config --global http.sslCAInfo /path/to/cacert.pem
undefinedDiagnostic Commands
诊断命令
Repository Health Check
仓库健康检查
bash
undefinedbash
undefinedFull integrity check
Full integrity check
git fsck --full --strict
git fsck --full --strict
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
Check reflog
Check reflog
git reflog expire --dry-run --all
git reflog expire --dry-run --all
Analyze repository
Analyze repository
git count-objects -vH
undefinedgit count-objects -vH
undefinedDebug Information
调试信息
bash
undefinedbash
undefinedEnable 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
undefinedgit config --list --show-origin
git config --list --show-scope
undefinedPrevention 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
git gc - Test Before Force Push: Always verify with
--dry-run - 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 gc - 强制推送前测试: 始终使用验证操作
--dry-run - 团队沟通: 告知团队成员可能造成影响的操作
- 学习Git内部原理: 理解Git的运行机制可以避免很多问题
- 保持Git版本更新: 使用最新的稳定版本
Resources
资源
Additional troubleshooting guides are available in the directory:
assets/- - Step-by-step recovery procedures
troubleshooting/ - - Diagnostic and recovery scripts
scripts/ - - Problem diagnosis workflows
checklists/
See directory for:
references/- Git error message database
- Recovery procedure documentation
- Git internal structure guides
- Common pitfall documentation
assets/- - 分步恢复流程
troubleshooting/ - - 诊断和恢复脚本
scripts/ - - 问题诊断工作流
checklists/
请查看 目录获取:
references/- Git错误提示数据库
- 恢复流程文档
- Git内部结构指南
- 常见陷阱文档