0

I have three branches:

master
old
test

Master and old are exactly the same, and test holds all my changes and the whole new project. I want to replace master branch with test branch, and test branch (and old branch) to remain unchanged. How can I do this?

I've been thinking about:

git checkout test
git merge -s ours master
git checkout master
git merge test

Is this the safe way to do this?

user99999
  • 1,994
  • 5
  • 24
  • 45
  • You could just delete master and `git checkout test; git checkout -b master`. This is much closer to "replace" semantic that you seek. – Sergio Tulentsev Aug 10 '16 at 11:02

3 Answers3

3

I would not suggest a merge. This might coincidentally be what you want (in case your test branch has master as a parent); but it is a complex operation that's not required here, since you seem to want to throw away your old master anyways. Instead:

git branch -f master test

That's it; it will make master point to whatever commit test is pointing to; test and old will be unchanged.

AnoE
  • 8,048
  • 1
  • 21
  • 36
  • this helped to make everything look good in the repository, however, i am getting merge conflicts after i do "git pull" after this move – user151496 Sep 02 '21 at 12:15
  • @user151496, I would be surprised why you want to do a pull after this operation; the statement in my answer overwrites the local ref "master" to point to something else. Maybe open a new question with all the details from your problem so someone can look at that specifically. – AnoE Sep 02 '21 at 12:30
  • i have ended up merging "want to be new master" branch into master, then instead of solving deleting everything except from .git directory, and then copying there every file from the other branch. that way, the new branch replaces old master and you can just `git pull` everywhere safely everywhere even on production. the above solution is practical only when there are no production running branches and no other developers rely only, and you can mess .git history up, but i can't imagine a scenario when that's the case – user151496 Sep 07 '21 at 07:36
2

Example

Here is an implementation using ours merge strategy. Essentially, this will overwrite master with test.

git checkout test
git merge -s ours master
git checkout master
git merge test

The result should be your master is now essentially test.

Merge Strategy

ours - This resolves any number of heads, but the result of the merge is always the current branch head. It is meant to be used to supersede old development history of side branches

Reference

git-merge

e.doroskevic
  • 2,129
  • 18
  • 25
1

Your way is the clean solution (a -s theirs strategy would shorten your command, but git does not have it).

When you are not interested in keeping master mergable, you can do

git checkout master
git reset --hard test
ensc
  • 6,704
  • 14
  • 22