Replace branch completely with another branch

Viewed 2851

I have 3 branches: development, qa, and staging. I have almost the same code in both development and qa, so making a pr from development to qa doesn't yield too many changes (and or conflicts).

But now I have a move all the stuff from qa to staging. And qa code is practically completely different and new from staging, so what's the best option? I searched and found this other answer:

git checkout qa
git merge -s ours staging
git checkout staging
git merge qa

Is this a good idea for my case? Thanks in advance!

EDIT: I don't want to lose all the commits from staging branch.

2 Answers

If you want to "completely replace", I'll go with git reset:

git checkout staging
git reset origin/qa --hard

This will make staging have the exact same content as qa but this will "erase" commits that may have been done on staging (the commits won't be deleted yet but they won't be visible in the history of staging anymore).

Gaël J's answer is good, but there is a shorter (i.e. single) command, which doesn't require you to switch branches and doesn't interfere with your current working tree:

git branch -f staging origin/qa

If the branch is already shared with others (= pushed), you have to force-push to the remote repository and inform others that they have to rebase any existing work based on this branch.

If you want to put all staging commits on top of the remote-tracking branch origin/qa, use rebase:

git rebase origin/qa staging

Or, if you want to replace the content of tree referenced by staging, but still keep its old history, use the merge strategy -s ours. See my answer on "How do I 'overwrite', rather than 'merge', a branch on another branch in Git?"

Related