Image for 'This Week I Learned' blog post featuring tips on managing Git branches including renaming and syncing with remote changes.

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
Emily Morehouse's profile picture
Emily Morehouse

Cofounder, Director of Engineering

Related Posts

Image from the "TWIL" blog post showing how Firebase tools integrate with JavaScript and React-Native for app development.
October 29, 2019 • Frank Valcarcel

TWIL 2019-10-25

Join us for this week’s “TWIL” where Marisa guides us on how Firebase’s Firestore, Storage, and Cloud Functions work in unison with JavaScript and React-Native to update documents in real-time applications.

Illustration of Emily presenting the Archive Branches Helper, a Git tool for archiving branches, depicting a tidy
May 21, 2019 • Frank Valcarcel

TWIL 2019-05-17

Join us in this week’s “TWIL” as Emily introduces the Archive Branches Helper, a powerful Git tool designed to streamline your version control process. Discover how this simple shell command can transform your workflow, allowing you to maintain a clean and efficient coding workspace by effortlessly archiving old Git branches.