16

I have a very out of date master branch in a git repository.

All of my work has been done in another branch.

What is the best way to merge the two?

I don't care about anything in master, it is way out of date.

Tobia Tesan
  • 1,938
  • 17
  • 29
Zuriar
  • 11,096
  • 20
  • 57
  • 92

4 Answers4

13

If you are fine with losing the history of your master branch you just let master point to the head of your current branch (your don't "overwrite" master - the branch - per se):

git checkout yourotherbranch
git branch -D master
git checkout -b master

Of course if you have a remote clone, you'll then have to

git push -f origin master 

Nota bene: this specifically applies to replacing the whole of your master branch and throwing the old master away as the title suggests. Otherwise, you should be fine with git merge master --strategy=ours.

Tobia Tesan
  • 1,938
  • 17
  • 29
  • 1
    Thanks for acknowledging the alternative - I would imagine that a merge would do fine, but if they wanted to replace the entire history, then that's another matter entirely. – Makoto Apr 25 '15 at 20:54
13

Let's assume your work is in a branch called dev:

git checkout dev 
git merge --strategy=ours master
git checkout master 
git merge dev

The merge option --strategy=ours is meant to be used to supersede old development history of side branches (quote).

Community
  • 1
  • 1
Яois
  • 3,838
  • 4
  • 28
  • 50
  • This is not enough. ours strategy work on conflicts when there are files on master not existing on dev that is not covered. – Rafael May 20 '21 at 10:31
5

Lots of these questions are answered with the git merge strategy=ours solution, but I think it misses the point of the question. I interpret the question as "i didn't follow good practice and basically the master is useless, and i want nothing from the master". common for solo projects.

git push -f origin branch_ive_been_working_for_months:master fully replaces your remote master with your remote branch. then, just git pull origin master after locally checking out master is the solution that directly answers question IMO.

Azeli
  • 698
  • 7
  • 16
  • 1
    This is the most succinct answer, fulfilling exactly the intent of the original poster. – JoeAC Oct 08 '20 at 23:59
2

A complete overwrite isn't merging the other content, it's abandoning it.

git checkout -B master anotherbranch

This has the advantage over a delete-and-recreate of retaining your branch settings and reflogs.

If there's some administrative requirement to retain worthless commits in your history, follow that with git merge -s ours master@{1}. I prefer this sequence because it generates an unusual merge message, which will alert scanning --oneline logs that the merge is unusual.

jthill
  • 55,082
  • 5
  • 77
  • 137