
Git Under the Hood: Advanced Rebase, Cherry-Pick, and Reflog Rescue
Almost every developer uses Git daily, but many only know basic commands like add, commit, pull, and push. When collaborative workflows get messy, or commits are accidentally deleted, panic sets in.
Understanding how Git works under the hood allows you to utilize advanced commands to rewrite history, selectively apply changes, and rescue "lost" code.
1. Git Rebase: Clean History
Rebasing is the process of moving or combining a sequence of commits to a new base commit. Unlike git merge, which creates an extra "merge commit," rebasing rewrites the project history by creating brand new commits for each commit in the original branch.
Interactive Rebase
One of the most powerful Git commands is interactive rebasing. It lets you modify individual commits, squash multiple commits into one, or delete commits entirely.
To rewrite the last 3 commits on your current branch, run:
git rebase -i HEAD~3An editor will open, showing a list of your commits. You can change the action keyword (e.g., changing pick to squash to combine a commit with the one before it).
2. Cherry-Pick: Selectively Apply Commits
Have you ever made a commit on the wrong branch, or wanted to pull a single bug fix from a development branch into production without merging everything? That is what git cherry-pick is for.
git cherry-pick takes a commit from another branch and applies it as a new commit on your current branch.
# Get the hash of the commit you want
git log --oneline
# Switch to the target branch
git checkout main
# Apply the commit
git cherry-pick <commit-hash>3. Git Reflog: The Ultimate Safety Net
Did you perform a hard reset (git reset --hard) and lose your last three commits? Or did a rebase go completely wrong, wiping out your work?
Before you panic: Git rarely deletes files immediately.
Git records every single state change of your repository head (such as branch switches, rebases, and resets) in the Reference Log (Reflog).
To view this history, run:
git reflogYou will see a list of commits with references like HEAD@[0], HEAD@[1], and so on (where brackets represent curly braces in the output), even if those commits are no longer part of any branch.
To restore your repository to exactly how it was before the disaster:
# Find the state you want to go back to (using curly braces around the index)
git reset --hard HEAD@[2]Your lost commits are back!
Conclusion
Git is a database of snapshots. Once you understand that commits are content nodes and branches are just references pointing to those nodes, tools like interactive rebase, cherry-pick, and reflog become intuitive safety nets that make you a more confident developer.