Fixing Git History
Overview of Git History Repair Techniques
Git provides powerful tools to clean, modify, and restructure repository history, ensuring a clean and meaningful project timeline.
Commit Modification Strategies
1. Modifying Recent Commits
## Modify the most recent commit
git commit --amend
## Interactive commit editing
git rebase -i HEAD~3
2. Commit Message Correction
## Change last commit message
git commit --amend -m "New corrected commit message"
History Rewriting Techniques
Interactive Rebase
gitGraph
commit id: "Initial Commit"
commit id: "Messy Commit"
commit id: "Another Commit"
commit id: "Final Commit"
Interactive rebase allows comprehensive history manipulation:
Action |
Description |
Command |
pick |
Use commit as-is |
pick |
reword |
Change commit message |
reword |
edit |
Modify commit |
edit |
squash |
Combine commits |
squash |
drop |
Remove commit |
drop |
Practical Rebase Example
## Start interactive rebase
git rebase -i HEAD~3
## In the editor, modify commit actions
## Save and close to apply changes
Cleaning Large Repository History
Removing Large Files
## Install BFG Repo-Cleaner
sudo apt-get install openjdk-11-jre-headless
wget https://repo1.maven.org/maven2/com/madgag/bfg/1.14.0/bfg-1.14.0.jar
## Remove large files
java -jar bfg-1.14.0.jar --strip-blobs-bigger-than 100M repo.git
Branch Management and Cleanup
Merging and Pruning Branches
## Delete local branch
git branch -d feature-branch
## Delete remote branch
git push origin --delete feature-branch
Advanced History Reconstruction
Recovering Lost Commits
## Find lost commits
git reflog
## Restore specific commit
git checkout <commit-hash>
Removing Sensitive Data
## Use filter-branch to remove sensitive files
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch PATH_TO_FILE" \
--prune-empty --tag-name-filter cat -- --all
LabEx Pro Tip
Practice history modification in LabEx's safe, isolated environments to build confidence in Git management skills.
Best Practices
- Always backup repository before major changes
- Communicate with team before history modifications
- Avoid rewriting public/shared branches
- Use interactive rebase for clean history
Warning Signs
- Excessive history modifications
- Frequent force pushes
- Uncoordinated branch management
Recommended Workflow
graph TD
A[Identify Problem] --> B[Choose Repair Strategy]
B --> C[Backup Repository]
C --> D[Apply Modification]
D --> E[Verify Changes]
E --> F[Commit/Push]
Common Pitfalls to Avoid
- Randomly modifying shared history
- Incomplete understanding of rebase
- Neglecting team communication