I have a repository in Git. I made a branch, then did some changes both to the master and to the branch.
Then, tens of commits later, I realized the branch is in much better state than the master, so I want the branch to “become” the master and disregard the changes on master.
I cannot merge it, because I don’t want to keep the changes on master. What should I do?
Extra: In this case, the ‘old’ master has already been
push-ed to another repository such as GitHub. How does this change things?
The problem with the other two answers is that the new master doesn’t have the old master as an ancestor, so when you push it, everyone else will get messed up. This is what you want to do:
git checkout better_branch git merge --strategy=ours master # keep the content of this branch, but record a merge git checkout master git merge better_branch # fast-forward master up to the merge
If you want your history to be a little clearer, I’d recommend adding some information to the merge commit message to make it clear what you’ve done. Change the second line to:
git merge --strategy=ours --no-commit master git commit # add information to the template merge message
Make sure everything is pushed up to your remote repository (GitHub):
git checkout main
Overwrite “main” with “better_branch”:
git reset --hard better_branch
Force the push to your remote repository:
git push -f origin main
Edit: You didn’t say you had pushed to a public repo! That makes a world of difference.
There are two ways, the “dirty” way and the “clean” way. Suppose your branch is named
new-master. This is the clean way:
git checkout new-master git branch -m master old-master git branch -m new-master master # And don't do this part. Just don't. But if you want to... # git branch -d --force old-master
This will make the config files change to match the renamed branches.
You can also do it the dirty way, which won’t update the config files. This is kind of what goes on under the hood of the above…
mv -i .git/refs/new-master .git/refs/master git checkout master