15

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,918
  • 14
  • 27
Zuriar
  • 10,078
  • 18
  • 51
  • 89

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,918
  • 14
  • 27
  • 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
11

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,718
  • 3
  • 25
  • 47
  • 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
3

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
  • 640
  • 6
  • 15
  • 1
    This is the most succinct answer, fulfilling exactly the intent of the original poster. – JoeAC Oct 08 '20 at 23:59
1

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
  • 48,781
  • 4
  • 72
  • 120