How to merge the current branch into another branch

前端 未结 8 973
忘了有多久
忘了有多久 2020-12-04 04:44

I have two branches, master and dev. I always work on dev and only check code into the master branch once it\'s been approved for production use. When I do so, I have to do

8条回答
  •  盖世英雄少女心
    2020-12-04 05:26

    To merge the current branch into another branch without checking out the other branch:

    Fast-forward merge

    This is really easy. By definition, a fast-forward merge simply means the branch pointer is moved ahead in the commit tree. So all you need to do is just simulate that:

    git branch -f master dev
    

    Caveats: This assumes that master points to a commit that is also in dev branch or some other branch. If it doesn't, you risk losing work! Unlike git merge which will create a merge commit (or complain) when fast-forward is not possible, this method silently forces the branch pointer to point to another commit.

    This also assumes you're the only one working on the repo, and/or you know what you're doing.

    Tip: If you did a git fetch and you have new commits in origin/master, you can move the master branch without checking out using:

    git branch -f master origin/master
    

    Merge via merge commit

    This is not always possible. To create a merge commit, you have to do a merge operation. And to do a merge operation, you should have commits in the other branch that are not in the current branch.

    If you do have commits in the master branch which are not in dev branch, you can:

    Disclaimer: This is merely a proof-of-concept, just to show it's sometimes possible to do a merge to the other branch without checking out. If you would want to use it everyday, you probably want to make an alias for it using shell redirection or make a shell script for it. Then again, you can also make a shell script for the shorter process shown in the question.

    git checkout -b temp
    git merge --no-ff -e master
    git branch -f master temp
    git checkout dev
    git branch -D temp
    

    Explanation:

    1. Check out a temporary branch that points to the same commit as current branch.
    2. Merge master into the temporary branch and launch commit message editor. If you want the merge commit to look like you had merged the dev branch into master, edit it from this:

      Merge branch 'master' into temp
      

      to this:

      Merge branch 'dev'
      

      Tip: You can use -m "Merge branch 'dev'" instead of -e to be quicker.

    3. Update the master branch pointer to point to the merge commit.
    4. Check out the dev branch.
    5. Force delete the temporary branch.

    This still touches your working tree, but minimally so. It doesn't roll back the tree all the way to state of the original master just to bring in the development changes once again. Some may not care, but for others it may be important.

提交回复
热议问题