Dive into this edition of 'TWIL,' our weekly expedition into the ever-evolving landscape of tech wisdom. This week, Emily enlightens us on Git, sharing savvy techniques for Managing and Updating Branches with Rewritten History. Discover how to align your local branch with remote changes, seamlessly renaming branches to preserve your work or to freshen up your repository for that crystal-clear PR.
Managing and Updating Branches with Rewritten History
There are times where you may need to overwrite your local branch to match a remote - maybe the branch was cherry-picked or rebased by another person to fix conflicts, etc.
# Update local branch
# - Retrieve the current version of the branch
git fetch origin <branch_name>
# - Force your local version of the branch to match the new version you fetched
git reset --hard origin/<branch_name>
If you need to force-update a local branch but don't want to lose your history locally, you can rename the branch first:
# - Rename the branch you currently have checked out
git branch -m <new-branch-name>
# - Rename a branch by name
git branch -m <old-branch-name> <new-branch-name>
Alternatively, you can push a local branch to a different name. Often, I'll checkout a new branch with the clean-prs
prefix and cherry-pick to that. That way, my original local branch remains intact.
# Push a branch as a different name
# I usually read the ":" as "as"
# e.g. "push clean-prs/feature/new-thing as feature/new-thing"
git push clean-prs/feature/new-thing:feature/new-thing
- Git