Git

Git Merge

Posted by Randle on April 5, 2020

Git Merge 简介

git merge 的基本用法为把一个分支或或某个 commit 的修改合并到现在的分支上。

  1. 用于git-pull中,来整合另一代码仓库中的变化(即:git pull = git fetch + git merge)
  2. 用于从一个分支到另一个分支的合并

我们可以运行 git merge -h 和 git merge –help 查看其命令。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
usage: git merge [options] [<commit>...]
   or: git merge [options] <msg> HEAD <commit>
   or: git merge --abort

    -n                    do not show a diffstat at the end of the merge
    --stat                show a diffstat at the end of the merge
    --summary             (synonym to --stat)
    --log[=<n>]           add (at most <n>) entries from shortlog to merge commit message
    --squash              create a single commit instead of doing a merge
    --commit              perform a commit if the merge succeeds (default)
    -e, --edit            edit message before committing
    --ff                  allow fast-forward (default)
    --ff-only             abort if fast-forward is not possible
    --rerere-autoupdate   update the index with reused conflict resolution if possible
    -s, --strategy <strategy>
                          merge strategy to use
    -X, --strategy-option <option=value>
                          option for selected merge strategy
    -m, --message <message>
                          merge commit message (for a non-fast-forward merge)
    -v, --verbose         be more verbose
    -q, --quiet           be more quiet
    --abort               abort the current in-progress merge
    --progress            force progress reporting
    -S, --gpg-sign[=<key id>]
                          GPG sign commit
    --overwrite-ignore    update ignored files (default)

git merge [options] <msg> HEAD <commit> 这里的 HEAD 其实就是分支名,用于说明把 HEAD 分支合并到当前分支。

参数

–commit,–no-commit

--commit参数使得合并后产生一个合并结果的commit节点。该参数可以覆盖--no-commit--no-commit参数使得合并后,为了防止合并失败并不自动提交,能够给使用者一个机会在提交前审视和修改合并结果。

–edit, -e, –no-edit

--edit-e用于在成功合并、提交前调用编辑器编辑自动生成的合并信息。 --no-edit参数用于接受自动合并的信息(通常情况下并不鼓励这样做)。

如果在合并时已经给定了-m参数(下文介绍),使用 --edit(或-e)依然是有用的,可以在编辑器中进一步编辑-m所含的内容。

–ff

--ff是指 fast-forward 命令。当使用 fast-forward 模式进行合并时,不会提交一个新的 commit 节点。默认情况下,git-merge 采用 fast-forward 模式。简单描述,把待合并分支上的提交,按照提交顺序,完全整合到合并分支上。不保留原分支信息。

–ff-only

除非当前HEAD节点已经up-to-date(更新指向到最新节点)或者能够使用fast-forward模式进行合并,否则的话将拒绝合并,并返回一个失败状态。

–no-ff

保留原分支信息,创建 merge commit。

–squash,–no-squash

本地文件内容与不使用该选项的合并结果相同,但是不保留待合并分支上的历史信息,也不提交、不移动 HEAD,因此需要一条额外的 commit 命令。其效果相当于将 another 分支上的多个 commit 合并成一个,放在当前分支上,原来的 commit 历史则没有拿过来。 判断是否使用 –squash 选项最根本的标准是,待合并分支上的历史是否有意义。如果在开发分支上提交非常随意,甚至写成微博体,那么一定要使用 –squash 选项。版本历史记录的应该是代码的发展,而不是开发者在编码时的活动。只有在开发分支上每个 commit 都有其独自存在的意义,并且能够编译通过的情况下(能够通过测试就更完美了),才应该选择缺省的合并方式来保留 commit 历史。

–log[=<n>], –no-log

--log[=<n>]将在合并提交时,除了含有分支名以外,还将含有最多n个被合并commit节点的日志信息。 --no-log并不会列出该信息。

–stat, -n, –no-stat

--stat参数将会在合并结果的末端显示文件差异的状态。文件差异的状态也可以在git配置文件中的merge.stat配置。 相反,-n, --no-stat参数将不会显示该信息。

参考资料