Git:git-merge 的用法总结

前言

git-merge 有可能是最难搞清楚的,又是最常遇到的一个命令,其实这么想来,原来 SVN 时代、 CVS 时代,冲突都是一个不好解决的问题;或者说,冲突是最难自动解决的一个问题了,无论是在代码中,还是实际生活中。

博客

原帖收藏于IT老兵驿站

正文

git-merge 使用来把两个或更多的开发历史合并。

参考里面是官网的讲解,这个帖子,我看了可能至少有五六遍了,但是要是说完全掌握明白,好像还是没有。

这两天又阅读了几遍,似乎看明白了一点。

git merge [-n] [–stat] [–no-commit] [–squash] [–[no-]edit] [–no-verify] [-s ] [-X ] [-S[]] [–[no-]allow-unrelated-histories] [–[no-]rerere-autoupdate] [-m ] [-F ] […​]
git merge (–continue | –abort | –quit)

仅仅就这个命令形式,我就看过了好多遍,就没太看明白。

第一行是 git merge 的基本使用方式,而我理解和所使用到的方式就是在一个分支上,可以把另外一个分支的内容合并过,但是这里都没有出现。

Incorporates changes from the named commits (since the time their histories diverged from the current branch) into the current branch. This command is used by git pull to incorporate changes from another repository and can be used by hand to merge changes from one branch into another.

这里写的是,merge 是把那些从当前分支开始分出去的提交合并到当前分支。这也是 git pull 所使用的方式。从这个角度来说,倒是能说的通上面的问题。

第二行是如果你执行了上面的第一行命令,可能就会处于一种需要选择的状态,谈不上进退两难,但我之前的情况是更多是要选择后退。

Warning: Running git merge with non-trivial uncommitted changes is discouraged: while possible, it may leave you in a state that is hard to back out of in the case of a conflict.

有趣的是,这段话提醒了我,造成这个问题的原因有可能是因为有太多的内容需要合并—-那其实思路还是一样(和写代码很多地方的思路是一样的),就是小步地提交,频繁地合并。

-s
–strategy=
Use the given merge strategy; can be supplied more than once to specify them in the order they should be tried. If there is no -s option, a built-in list of strategies is used instead (git merge-recursive when merging a single head, git merge-octopus otherwise).
-X

这段是需要搞明白的内容,合并的策略是什么,就是 git 怎么去合并呢?git是有一些内建策略的。

确认了策略,然后可以确认策略的选项。

另外一篇文章《Git:merge的时候全部采用某一个端的文件》是原来总结的一篇文章,总结了一种 merge 的用法,那篇文章只是从很小的一个片段去总结了一下。

Recursive git merge -s recursive branch1 branch2 This operates on two
heads. Recursive is the default merge strategy when pulling or merging
one branch. Additionally this can detect and handle merges involving renames, but currently cannot make use of detected copies. This is the default merge strategy when pulling or merging one branch.

Resolve git merge -s resolve branch1 branch2 This can only resolve two heads using a 3-way merge algorithm. It tries to carefully detect cris-cross merge ambiguities and is considered generally safe and fast.

上面是两种最常见的合并策略,还没有完全看明白区别。

参考

https://git-scm.com/docs/git-merge
https://www.atlassian.com/git/tutorials/using-branches/merge-strategy