13

git cherry-pick 同步修改到另一个分支 - 大数据王小皮

 2 years ago
source link: https://www.cnblogs.com/shuofxz/p/16994923.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

我们在开发中有时会遇到,需要将另一个分支部分修改同步到当前分支。
如下图,想把 devA 分支中 commit E 和 F,同步到下面绿色的 devB 分支中。

image.png

这时候就可以使用 git cherry-pick 来完成这项任务。
(cherry-pick 有筛选、精选的意思)

一、基本用法#

转移单个提交

git cherry-pick <commitHash>
# 切换到 devB 分支
$ git checkout devB

# Cherry pick 操作
$ git cherry-pick <HashE>

解决冲突后,commit 即可

二、转移多个提交#

如果我有一堆连续的 commit 都想同步过去,那么可以用下面的语法:
下面的命令可以转移从 E 到 F 的所有 commit。 注意按顺序写:提交 E 必须早于提交 F

git cherry-pick <HashE>..<HashF>

还要注意上面命令是左开右闭的,即不包含 commit_E,如果需要两边都包括,用下面的语法:

git cherry-pick <HashE>^..<HashF>

如果是分开的几个 commit,可以这样写:

git cherry-pick <HashE> <HashG>

三、参数#

文档中是这样写的:

usage: git cherry-pick [<options>] <commit-ish>...
   or: git cherry-pick <subcommand>

    --quit                end revert or cherry-pick sequence
    --continue            resume revert or cherry-pick sequence
    --abort               cancel revert or cherry-pick sequence
    --skip                skip current commit and continue
    --cleanup <mode>      how to strip spaces and #comments from message
    -n, --no-commit       don't automatically commit
    -e, --edit            edit the commit message
    -s, --signoff         add a Signed-off-by trailer
    -m, --mainline <parent-number>
                          select mainline parent
    --rerere-autoupdate   update the index with reused conflict resolution if possible
    --strategy <strategy>
                          merge strategy
    -X, --strategy-option <option>
                          option for merge strategy
    -S, --gpg-sign[=<key-id>]
                          GPG sign commit
    -x                    append commit name
    --ff                  allow fast-forward
    --allow-empty         preserve initially empty commits
    --allow-empty-message
                          allow commits with empty messages
    --keep-redundant-commits
                          keep redundant, empty commits

提几个会用得到的:
1)-n 如果你想转移多个 commit 并在新分支中只想有一个 commit,那就可以添加 -n 参数,不自动提交代码,都转移后一次性手动提交。(注意如果有 conflict 情况就不是很好用)(为了分辨是从其他分支转移过来的,可以新开一个分支同步这些 commit,然后再 merge 到目标分支)

    -n, --no-commit       don't automatically commit

2)-x 在提交信息的末尾追加一行(cherry picked from commit ...),方便以后查到这个提交是如何产生的。

    -x                    append commit name

3)不建议同步「合并(merge)节点」,得到的结果应该不是你想要的(有兴趣可以自己尝试)。

四、代码冲突#

1)--continue
同步代码不可避免遇到冲突情况,解决冲突后,将修改的文件重新加入暂存区 git add .,然后使用下面命令继续:

git cherry-pick --continue

2)--abort
处理过程中可能有误操作,那么可以放弃合并,回到操作前的样子。

git cherry-pick --abort

(3)--quit
发生代码冲突后,退出 cherry pick,但是不回到操作前的样子。

git cherry-pick --quit

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK