Git入门之Git分支管理(二)
Git解决冲突
解决冲突
准备新的feature1
分支,继续新分支开发:
$ git switch -c feature1
开发完成后进行提交
$ git add <file>
$ git commit -m "AND simple"
切换分支
$ git switch master
进行与新分支方案不同的开发并提交:
$ git add <file>
$ git commit -m "& simple"
即master
和feature1
各自都有新的提交,如图:
这种情况无法“快速合并”,只能将各自的修改合并起来,但这种合并可能会有冲突:
$ git merge feature1
# CONFLICT(content): Merge conflict in <file>
# Automatic merge failed; fix conficts and then commit the result.
出现冲突了,Git提示我们文件存在冲突,必须手动解决冲突后再提交,用git status
也能看到冲突的文件:
例如文件readme.txt
的内容如下:
Git is a distributed version control system.
Git is free software distributed under the GPL.
Git has a mutable index called stage.
Git tracks changes of files.
<<<<<<< HEAD
Creating a new branch is quick & simple.
=======
Creating a new branch is quick AND simple.
>>>>>>> feature1
Git用<<<<<<<,=======,>>>>>>>
标记出不同分支的内容,修改如下后保存:
Creating a new branch is quick and simple.
再提交:
$ git add readme.txt
$ git commit -m "conflict fixed"
此时分支情况如下图所示:
用带参数的git log
也可以看到分支的合并情况:
$ git log --graph --pretty=oneline --abbrev-commit
* fb8b190 (HEAD -> master) conflict fixed
|\
| * 2443c95 (feature1) add simple
* | 06e5e3a & simple
|/
* 4aac6c7 branch test
* 599dbdb understand how stage works
* 1985ccf append GPL
* 27f9df6 add distributed
* e372504 wrote a readme file
最后删除feature1
分支:
$ git branch -d feature1
git cherry-pick
将代码从一个分支转移到另一个分支
- 你需要另一分支的所有代码变动,则采用合并
git merge
. - 你只需要部分代码变动(某几个提交),则采用
Cherry pick
git cherry-pick 基本用法
$ git cherry-pick <commitHash>
举例来说,有下面两个分支:
a - b - c - d Master
\
e - f - g Feature
现在我们要将f
应用到master
分支
$ git checkout master
$ git cherry-pick f
执行完上面的语句后代码库就变成了下面这样
a - b - c - d - f Master
\
e - f - g Feature
git cherry-pick
后面的参数除了哈希值也可以是分支名,表示转移该分支的最新提交
$ git cherry-pick feature
上面代码表示将feature
分支的最近一次提交,转移到当前分支。
git cherry-pick 转移多个提交
$ git cherry-pick <HashA> <HashB>
上述命令将A和B提交到当前分支,生成两个对应的新提交,如需转移一系列的连续提交可以使用简便语法
$ git cherry-pick A..B
上述代码表示转移从A到B的所有提交,且顺序不能错,A提交时间应早于B(注意,命令失败不会报错),上面这种方法不包含A,包含A参考以下写法:
$ git cherry-pick A^..B
git cherry-pick 配置项
常用配置项如下:
-e, --edit: 打开外部编辑器,编辑提交信息
-n,--no-commit: 只更新工作区和暂存区,不产生新的提交。
-x: 在提交信息的末尾追加一行cherry picked from commit ...,方便以后查到这个提交是如何产生的。
-s,--signoff: 在提交信息的末尾追加一行操作者的签名,表示是谁进行了这个操作。
-m parent-number,--mainline parent-number: 如果原始提交是一个合并节点,来自于两个分支的合并,那么 Cherry pick 默认将失败,因为它不知道应该采用哪个分支的代码变动。
-m 配置项告诉 Git,应该采用哪个分支的变动。它的参数parent-number是一个从1开始的整数,代表原始提交的父分支编号。git cherry-pick -m 1 <commitHash>表示,Cherry pick 采用提交commitHash来自编号1的父分支的变动。一般来说,1号父分支是接受变动的分支,2号父分支是作为变动来源的分支。
git cherry-pick 代码冲突
(1) -continue
解决代码冲突后,将修改的文件重新加入暂存区(git add .
), 在使用下面的命令,让Cherry pick
过程继续执行
$ git cherry-pick --continue
(2) -abort
发生冲突后,放弃合并,回到操作前的样子
(3) -quit
发生冲突后,退出cherry pick
,但是不回到操作前的样子
git cherry-pick 转移到另一个代码库
-
将该库添加为远程仓库(下面以远程仓库
target
为例)$ git remote add target git://gitUrl
-
将远程代码抓取到本地
$ git fetch target
-
检查要从远程仓库转移的提交,获取哈希值
$ git log target/master
-
使用
git cherry-pick
命令转移提交$ git cherry-pick <commitHash>