为什么 git 合并有时创建提交,有时不创建提交?

当我从另一个分支处理 git merge到当前工作区时,git 有时会做一个新的提交:

Merge remote-tracking branch xxx into xxx

有时,情况并非如此:

Fast-forward
... src files ...

那么是什么决定了是否应该创建提交呢?

18632 次浏览

You can use the --no-ff option to force a new commit to avoid the fast-forward.

A fast forward means that a commit has already happened and is stored in your log, and your HEAD (pointer) has moved forward to that commit. You can check out merge behavior here

When no fast-forward --no-ff option is presented git will not create a commit if the head of the branch you are merging in is the ancestor of the merged branch. In this case (no --no-ff option) it will just move the head (it's a fast-forward).

So-called "Fast-forward" merges don't produce a commit, whereas other merges (often refered to as "octopus merge" (now you see why github's mascott is an octocat)) produce commits.

Basically, a Fast-forward happens when your branches did not diverge.

Say you want to merge a branch foo in the master branch. If these branches did not diverge, you would have an history like this (each * represents a commit):

*---* (master)
\
*---*---* (foo)

In this situation, the merge is fast-forward because (according to the graph theory, which is the underlying foundation of a git graph), master is reachable from foo. In other words, you just have to move the master reference to foo, and you're done:

*---*
\
*---*---* (master, foo)

When your branches diverge:

*---*---* (master)
\
*---*---* (foo)

You have to create a commit to "join" the two branches:

                ↓
*---*---*-------* (master)
\         /
*---*---* (foo)

The commit pointed by the arrow is the merge commit and has two parent commits (the former master branch tip, and the current foo branch tip).

Note that you can force Git to create a merge commit for a fast-forward merge with the --no-ff option.

I highly recommend reading http://think-like-a-git.net/ for a good understanding of how the graph theory applies to git (you don't need to know the graph theory, everything you need to know is on the website), which will make working with Git incredibly easier :)