What is the best (and safest) way to merge a Git branch into master?

1,897,989

Solution 1

How I would do this

git checkout master
git pull origin master
git merge test
git push origin master

If I have a local branch from a remote one, I don't feel comfortable with merging other branches than this one with the remote. Also I would not push my changes, until I'm happy with what I want to push and also I wouldn't push things at all, that are only for me and my local repository. In your description it seems, that test is only for you? So no reason to publish it.

git always tries to respect yours and others changes, and so will --rebase. I don't think I can explain it appropriately, so have a look at the Git book - Rebasing or git-ready: Intro into rebasing for a little description. It's a quite cool feature

Solution 2

This is a very practical question, but all the answers above are not practical.

Like

git checkout master
git pull origin master
git merge test
git push origin master

This approach has two issues:

  1. It's unsafe, because we don't know if there are any conflicts between test branch and master branch.

  2. It would "squeeze" all test commits into one merge commit on master; that is to say on master branch, we can't see the all change logs of test branch.

So, when we suspect there would some conflicts, we can have following git operations:

git checkout test
git pull 
git checkout master
git pull
git merge --no-ff --no-commit test

Test merge before commit, avoid a fast-forward commit by --no-ff,

If conflict is encountered, we can run git status to check details about the conflicts and try to solve

git status

Once we solve the conflicts, or if there is no conflict, we commit and push them

git commit -m 'merge test branch'
git push

But this way will lose the changes history logged in test branch, and it would make master branch to be hard for other developers to understand the history of the project.

So the best method is we have to use rebase instead of merge (suppose, when in this time, we have solved the branch conflicts).

Following is one simple sample, for advanced operations, please refer to http://git-scm.com/book/en/v2/Git-Branching-Rebasing

git checkout master
git pull
git checkout test
git pull
git rebase -i master
git checkout master
git merge test

Yep, when you have uppers done, all the Test branch's commits will be moved onto the head of Master branch. The major benefit of rebasing is that you get a linear and much cleaner project history.

The only thing you need to avoid is: never use rebase on public branch, like master branch.

Never do operations like the following:

git checkout master
git rebase -i test

Details for https://www.atlassian.com/git/tutorials/merging-vs-rebasing/the-golden-rule-of-rebasing

appendix:

Solution 3

Neither a rebase nor a merge should overwrite anyone's changes (unless you choose to do so when resolving a conflict).

The usual approach while developing is

git checkout master
git pull
git checkout test
git log master.. # if you're curious
git merge origin/test # to update your local test from the fetch in the pull earlier

When you're ready to merge back into master,

git checkout master
git log ..test # if you're curious
git merge test
git push

If you're worried about breaking something on the merge, git merge --abort is there for you.

Using push and then pull as a means of merging is silly. I'm also not sure why you're pushing test to origin.

Solution 4

I would first make the to-be-merged branch as clean as possible. Run your tests, make sure the state is as you want it. Clean up the new commits by git squash.

Besides KingCrunches answer, I suggest to use

git checkout master
git pull origin master
git merge --squash test
git commit
git push origin master

You might have made many commits in the other branch, which should only be one commit in the master branch. To keep the commit history as clean as possible, you might want to squash all your commits from the test branch into one commit in the master branch (see also: Git: To squash or not to squash?). Then you can also rewrite the commit message to something very expressive. Something that is easy to read and understand, without digging into the code.

edit: You might be interested in

So on GitHub, I end up doing the following for a feature branch mybranch:

Get the latest from origin

$ git checkout master
$ git pull origin master

Find the merge base hash:

$ git merge-base mybranch master
c193ea5e11f5699ae1f58b5b7029d1097395196f

$ git checkout mybranch
$ git rebase -i c193ea5e11f5699ae1f58b5b7029d1097395196f

Now make sure only the first is pick, the rest is s:

pick 00f1e76 Add first draft of the Pflichtenheft
s d1c84b6 Update to two class problem
s 7486cd8 Explain steps better

Next choose a very good commit message and push to GitHub. Make the pull request then.

After the merge of the pull request, you can delete it locally:

$ git branch -d mybranch

and on GitHub

$ git push origin :mybranch

Solution 5

Old thread, but I haven't found my way of doing it. It might be valuable for someone who works with rebase and wants to merge all the commits from a (feature) branch on top of master. If there is a conflict on the way, you can resolve them for every commit. You keep full control during the process and can abort any time.

Get Master and Branch up-to-date:

git checkout master
git pull --rebase origin master
git checkout <branch_name>
git pull --rebase origin <branch_name>

Merge Branch on top of Master:

git checkout <branch_name>
git rebase master

Optional: If you run into Conflicts during the Rebase:

First, resolve conflict in file. Then:

git add .
git rebase --continue

You could abort the rebase anytime with:

git rebase --abort

Push your rebased Branch:

git push origin <branch_name>

If you have this branch pushed before, you need to override it with a force push:

git push origin -f <branch_name>

Before doing so, check always whether your current local branch matches your expectations, because the force push overrides the old one in the remote repository.

Now you've got two options:

  • A) Create a PR (e.g. on GitHub) and merge it there via the UI
  • B) Go back on the command line and merge the branch into master
git checkout master
git merge --no-ff <branch_name>
git push origin master

Done.

Share:
1,897,989
moe
Author by

moe

Web Developer!

Updated on August 28, 2022

Comments

  • moe
    moe over 1 year

    A new branch from master is created, we call it test.

    There are several developers who either commit to master or create other branches and later merge into master.

    Let's say work on test is taking several days and you want to continuously keep test updated with commits inside master.

    I would do git pull origin master from test.

    Question 1: Is this the right approach? Other developers could have easily worked on same files as I have worked btw.


    My work on test is done and I am ready to merge it back to master. Here are the two ways I can think of:

    A:

    git checkout test
    git pull origin master
    git push origin test
    git checkout master
    git pull origin test 
    

    B:

    git checkout test
    git pull origin master
    git checkout master
    git merge test
    

    I am not using --rebase because from my understanding, rebase will get the changes from master and stack mine on top of that hence it could overwrite changes other people made.

    Question 2: Which one of these two methods is right? What is the difference there?

    The goal in all of this is to keep my test branch updated with the things happening in master and later I could merge them back into master hoping to keep the timeline as linear as possible.

    • Junchen Liu
      Junchen Liu over 8 years
      no.. rebase never overwrite, it just trying to achieve a cleaner history. by reattach(or fake) the history to the late point of the master
    • zundi
      zundi almost 8 years
      rebase doesn't overwrite your commits. It undoes your commits, applies the commits in the master branch to your test branch, then applies your commits back to test.
    • information_interchange
      information_interchange almost 4 years
      What if we don't have write access to master? Any way to fix conflicts pre-emptively on the feature branch? Probably not I guess, since the histories have probably diverged
    • user1034912
      user1034912 over 2 years
      Why is this question not closed as it is opinon based? Please close this question please. That's they main purpose of stack overflow, to close down questions
  • iBug
    iBug almost 10 years
    This process will increase number of commits, every time you switch between branches, you have to commit your branch.
  • raylu
    raylu almost 10 years
    What? Are you saying it will increase the number of commits every time you switch branches? Or are you saying that every time you switch branches, you have to "commit your branch"? The first is untrue and I'm not sure what the second means.
  • iBug
    iBug almost 10 years
    before checkout, you have to commit branch. that is what i am saying
  • msanford
    msanford almost 10 years
    You don't: that's (one of the things) git stash is for.
  • Duncanmoo
    Duncanmoo over 9 years
    git merge test gives me fatal: 'test' does not point to a commit. I have to look in git log for the commit point on the test branch, switch back to master branch then do git merge 0f37d3154abbf52a4cbbbb5109f08af6a7567234.
  • KingCrunch
    KingCrunch over 9 years
    @Duncanmoo Well, of course the branch test must exist. Sure, you can use the commit hash instead, but it's usually easier to use the branch name. Internally it just retrieves the hash of HEAD of the branch.
  • KingCrunch
    KingCrunch over 8 years
    @shanyangqu To get the latest changes from the remote. If you work alone and only with one system ever there is no problem. But when there are changes pushed from a different system (probably from a different developer) you'll see a conflict as soon as you try to push your merge back (the 4th step). The only solution now is to merge your local master into the remotes master, which ends up in a pretty ugly "merged master into origin/master" merge commit. So it's always a good idea to make a pull before the merge
  • KingCrunch
    KingCrunch over 8 years
    I'd recommend git checkout test; git pull instead of git merge origin/test. Even better is git pull --rebase. Anyway, you forgot to pull the changes, so before git merge origin/test you should git fetch origin test (git fetch .. && git merge .. is exactly, what git pull .. does :))
  • raylu
    raylu over 8 years
    In theory, if test is at a different remote than master, yes. But since you generally only have one remote, pulling once updates both and then you can just merge (or rebase).
  • Jordan Morris
    Jordan Morris over 8 years
    You might want to push test if it will only be backed up when it is on your central git server. This is especially fine if you are working on your own fork.
  • John Yin
    John Yin about 8 years
    if you are not sure the rebase operation, please refer to: git-scm.com/book/en/v2/Git-Branching-Rebasing
  • whihathac
    whihathac about 8 years
    Or you could ammend your last commit (in local branch) and make it the perfect one before pushing.
  • le0diaz
    le0diaz about 8 years
    I agree rebasing the test branch for later merging into master is the way to go. Even the other answers are correct this will keep history of changes of branch test in the head of master as the auther mention "you get a liner and much cleaner project" which is the purpose of version control system.
  • Joey Baruch
    Joey Baruch about 8 years
    this shows the commits to the fb (test branch) as if committed straight into master, as opposed to showing the commits on their original fb, and just the merge into master (as seen with gitk, or on gitlab "network")
  • Paul van Leeuwen
    Paul van Leeuwen almost 8 years
    The statement "it's not one safety way, cause we don't know is there any conflicts between test branch and master branch" is not true: one can always abort the merge. And even if there are no conflicts you can always undo the last local commit as long as it is not pushed. Without correct understanding of git some things may seem a bit scary or unclear, but "unsafe" is just incorrect in any way. Please be careful not to confuse others with incorrect information.
  • ziggy
    ziggy over 7 years
    Is it not safer to merge origin/master into test first before before merging test into master? Wouldn't the above make test out of date?
  • KingCrunch
    KingCrunch over 7 years
    @ziggy Well... It depends. On the workflow. For example many only commit features and bug-fixes into develop and only hotfixes (and maybe important bugfixes) into master. Then they forward-port the hotfixes from develop into master (that's technically what you said). However, if there is no hotfix (which is always good :)), then develop is always in front of master. So yeah, you are right, but depending on the workflow it is maybe simply not necessary. (I used develop here, because it's more common than test).
  • Juan
    Juan over 7 years
    agree with @PaulvanLeeuwen, when you git merge the test branch into master, you will be notified about conflicts, and thats where you'll step in and merge the changes. Once you're done, you will commit the merge and push back. If you regret or cant seem to merge it correctly, you can always discard your work and pull from master again. So it is definitely not unsafe..
  • Prasad
    Prasad over 7 years
    @sterling Archer bow and arrow don't change but aim and strategy may change :-)
  • Afghan Host
    Afghan Host over 7 years
    " In your description it seems, that test is only for you? So no reason to publish it." You might want to push your local branch up to a server if, for example, that server provides a backup against your local drive failing or if you don't have another means to do a backup.
  • MushyPeas
    MushyPeas almost 7 years
    why rebase -i ?
  • Chris Vilches
    Chris Vilches over 6 years
    -1 It doesn't explain in which repository you must execute these commands. Surprisingly high score considering how useless it is.
  • Nawaz
    Nawaz over 6 years
    @FeloVilches: If you understand the commands, then you know which branch you're executing these commands on.
  • Chris Vilches
    Chris Vilches over 6 years
    @Nawaz valid point, but the title says safest way, so I'm not sure how safe it is to execute these commands in a random branch.
  • Nawaz
    Nawaz over 6 years
    @FeloVilches: It is not random branch! Safe or not, that is a different question altogether. But then that is not what your initial concern was!
  • KingCrunch
    KingCrunch over 6 years
    @FeloVilches The answer starts with git checkout master. Assuming you read gits output you are probably on master afterwards. You can even safely execute git checkout master on a random branch :)
  • Ikke
    Ikke about 6 years
    Rebasing is inherently more unsafe than merging. Proposing rebasing as a more safer option to merging is wrong. Rebasing is a valid strategy, but comes with more caveats that the user should beware of.
  • Cocowalla
    Cocowalla about 6 years
    "which should only be one commit in the master branch", well not necessarily; you may wekk want to keep the history
  • Martin Thoma
    Martin Thoma about 6 years
    Sure. But then simply don't squash the commits
  • Rich Steinmetz
    Rich Steinmetz almost 6 years
    "...Also I would not push my changes, until I'm happy with what I want to push..." why not pushing for the sake of having your code backed up, in case your local machines dies and days of efforts are gone?
  • bkribbs
    bkribbs over 5 years
    I think --first-parent seems to be the best solution. davidchudzicki.com/posts/first-parent
  • Lasithds
    Lasithds about 5 years
    For those who had conflicts when rebase, you can resolve the conflicts and run git rebase --continue. I managed to successfully merge my dev branch. So It's now safe to delete the dev branch if i'm not using it anymore?
  • asimovwasright
    asimovwasright about 5 years
    This answer seems wrong to me. The OP is asking how to keep the test branch updated with the master - and this answer is only showing how to merge the test into master.
  • Oliver D
    Oliver D about 4 years
    @KingCrunch Should I delete the branch after merged?
  • KingCrunch
    KingCrunch about 4 years
    @OliverD Sure, why not? If a branch is merged, it means, that the commits are now present in more than 1 branch. Deleting the source branch wont drop the changes. On the other hand re-creating the branch is just a single line away :) git checkout -b foo master
  • Upulie Han
    Upulie Han over 3 years
    If git merge test gives fatal: refusing to merge unrelated histories then git merge test --allow-unrelated-histories work.
  • Muhammad Tariq
    Muhammad Tariq over 3 years
    In step-1, you are checking out some feature branch and then in step-2 you are again checking out the master branch. I am confused, why to check out the feature branch in the first place ?? Please explain
  • shdr
    shdr over 3 years
    It's because that in this scenario it's first made fetch from origin (remote) "feature" branch. after that in order to merge "feature" to "master" you need to checkout "master" and merge "feature" to it.
  • Muhammad Tariq
    Muhammad Tariq over 3 years
    Then in first case, git fetch origin feature shouldn't be second command after checking out remote feature branch to sync local with remote feature?
  • LonelySoul
    LonelySoul over 3 years
    One more thing .. new git are using "main" and not "master"
  • kenecaswell
    kenecaswell about 3 years
    I like this way as well. One thing you forgot to mention is that you often have to force push your <branch_name> after you rebase.
  • Robin Wieruch
    Robin Wieruch over 2 years
    Edited. Thanks!
  • alper
    alper over 2 years
    Seems like git rebase -i master overwrite into the branch with what master has, is it normal?