工作原理
git merge 的主要用途是合并两个分支。
它还用于将多个提交合并到一个历史记录中。
在下图中, git merge 接受两个分支提示,并在它们之间找到一个常见的案例提交。
公共基础提交创建一个新提交,合并每个合并提交的序列更改。
这里我们有两个分支:master 和 stage。
我们应该将 stage 分支合并到 master 分支。
合并提交是独一无二的,因为它们有两个父提交。
创建新的合并提交时,Git 会自动合并单独的历史记录。
它不会合并两个历史记录中更改的数据。
这就是所谓的“版本控制冲突”。
快进合并
快进合并发生在从当前分支到目标分支的路径是线性的。
快进合并结合了历史,因为从目标分支可到达的所有提交都可以通过当前分支获得。
下面是一个快进合并的例子:
当两个历史出现分歧时,Git 使用 3 路合并作为替代。
三路合并使用专用提交来组合两个历史记录。
快进合并用于修复错误和小功能,而 3 路合并用于集成长时间运行的功能。
以下示例使用快进合并:
# Start the stage git checkout -b stage master # Edit some files git add <file> git commit -m "Start with the stage" # Edit some files git add <file> git commit -m "Finish with the stage" # Merge in the stage branch git checkout master git merge stage git branch -d stage
我们运行 git branch -d 来删除 stage 分支,因为现在可以从 master 分支访问 stage。
如果在快进合并期间需要合并提交以将指定分支合并到当前分支中,则运行带有 --no-ff 选项的 git merge 命令始终生成合并提交(同样,在快速合并的情况下)向前合并):
git merge --no-ff <branch>
如何呈现冲突
在发生冲突的情况下,Git 会编辑受影响文件的内容,并在冲突内容的两侧都有视觉标记。
合并冲突仅在 3 路合并的情况下发生。
这些标记是:<<<<<<<、=="======"和>>>>>>>。
它们搜索这些指标的项目(item)(item)以找到冲突的部分。
here is some content not affected by the conflict <<<<<<< master this is conflicted text from master ======= this is conflicted text from stage branch
找到冲突部分后,对冲突文件执行 git add 以指示 Git 解决它们。
接下来,运行 git commit 以生成合并提交。
三路合并
另一个示例需要在主分支进行时进行 3 路合并,而阶段正在进行。
这在团队成员同时处理大型功能时使用:
# Start the stage git checkout -b stage master # Edit some files git add <file> git commit -m "Start with the stage" # Edit some files git add <file> git commit -m "Finish with the stage" # Develop the master branch git checkout master # Edit some files git add <file> git commit -m "Make some super-stable changes to master" # Merge in the stage branch git merge stage git branch -d stage
在上面的例子中,stage 是一个更大的特性,需要花费很多时间来开发,这就是我们使用 3 路合并的原因。
如果你的功能很小,你最好使用快进合并来防止不必要的提交弄乱项目(item)(item)历史。
git合并流程
在合并过程之前,我们应该采取一些步骤。
- 首先,调用 git status 以便将 HEAD 指向正确的合并接收分支。
运行 git checkout <receiving branch> 切换到接收分支。
- 下一步是获取最新的远程提交。接收分支和合并分支应使用最新的远程更改进行更新。调用 git fetch 来拉取最新的远程提交。
在获取过程之后调用 git pull 来更新主分支。
- 最后一步是执行 git merge <branch name> 这是要合并到接收分支的分支的名称。
解决冲突
当你想合并两个分支时,同一个文件的同一部分发生了变化,会出现合并冲突,因为 Git 无法确定使用哪个版本。
发生这种情况时,它会在合并提交之前停止以解决该冲突。
Git 合并过程使用edit/stage/commit 工作流来解决合并冲突。
当发生冲突时,执行git status 会显示需要解决的文件。
当 example.txt 文件的相同部分发生更改时,将显示以下图片:
On branch master Unmerged paths: (use "git add/rm ..." as appropriate to mark resolution) both modified: example.txt
定义
git merge 命令将独立的开发线集成到单个分支中。
git merge 命令与 git checkout 命令一起选择当前分支和带有 -d 标志的 git branch 命令删除过时的目标分支。
在我们之前的章节中阅读这些命令。