Friday, October 5, 2018

Git: Forcing Local to Match Remote

Every now and then I've found myself making changes directly on a branch that can't be updated from local to remote. Let's say we have the "master" branch and from that we create the "working" branch. It is impossible (by rules) to update "master" directly. Instead, we must create a pull request so that our code may be reviewed. But sometimes I've already done the work on "master", committed my changes locally on "master" and tried to push them to the remote repository. That, of course, leads to an error message along the lines of "Pushes to this branch are not permitted; you must use a pull request to update this branch." That's exactly the error message we want to see, but now I'm stuck with code in the wrong branch and my "master" doesn't match the remote "master". Here's the super easy way to fix that.

git fetch --prune
git checkout -b new-branch-with-my-changes
git push --set-upstream origin new-branch-with-my-changes
git checkout master
git reset --hard origin/master

These simple steps will 1) create a new branch called new-branch-with-my-changes on the local and remote repositories, and 2) overwrite the local master branch to match the remote master branch.

Super simple, but I always have to Google it so now it's here for future me to find it more easily next time.

No comments:

Post a Comment