如何挑选多个提交

1493
我有两个分支。一个分支的头是提交 a,而另一个分支在 a 之上有 bcdef。我想将 cdef 移动到第一个分支,而不包括提交 b。使用 cherry-pick 很容易实现:切换到第一个分支,逐个 cherry-pick cf,然后将第二个分支变基到第一个分支上。但是否有一种方法可以用一条命令来 cherry-pick 所有的 c-f
以下是该场景的可视化描述(感谢 JJD):

A commit showing a 'before' and 'after' state. In the 'before' state, commits a through f are connected in one contiguous sequence. In the after state, commits c through f have been relocated to directly connect to a without reordering, leaving the b commit behind.


17
你提到的变基对于这个问题并不是真正相关的,对吧?(我知道你可能希望以后将'b'基于'f',但这与挑选提交无关。) - Superole
还有一种与此相反的推论:在git中还原一系列提交 - Gabriel Staples
17个回答

10

挑选多个提交记录:

切换到你想要挑选提交记录的分支

使用以下命令:(通过部分哈希值)

git cherry-pick 1e038f10 1e038f11 1e038f12 ...

3
实际上,最简单的方法可能是:
  1. record the merge-base between the two branches: MERGE_BASE=$(git merge-base branch-a branch-b)
  2. fast-forward or rebase the older branch onto the newer branch
  3. rebase the resulting branch onto itself, starting at the merge base from step 1, and manually remove commits that are not desired:

    git rebase ${SAVED_MERGE_BASE} -i
    

    Alternatively, if there are only a few new commits, skip step 1, and simply use

    git rebase HEAD^^^^^^^ -i
    

    in the first step, using enough ^ to move past the merge-base.

您将在交互式变基中看到类似以下的内容:
pick 3139276 commit a
pick c1b421d commit b
pick 7204ee5 commit c
pick 6ae9419 commit d
pick 0152077 commit e
pick 2656623 commit f

然后删除b行(以及您想删除的所有其他行)


2

我需要优先从一个分支中挑选一个提交并将其转移到另一个分支,但这里的提交很难理解,希望下面的内容能够帮助您轻松理解:


以下是操作步骤:

  1. 从“dev”分支获取名称为“Remove Last Name field”的1个提交
  2. 将其提交到“hotfix1”分支

1. 从“dev”分支获取提交详细信息

// Go to "dev" branch
git checkout dev

// Get the commit id (1e2e3e4e1 here)
git log --oneline

    > ...
    > ...
    > 1e2e3e4e1     Remove Last Name field
    > ...
    > ...

2. 将提交推送到“hotfix1”分支。

// Go to "hotfix1" branch
git checkout hotfix1

// Get the commit (1e2e3e4e1) from "dev" branch to "hotfix1" branch
git cherry-pick 1e2e3e4e1

// verify changes are correct
gitk

// push to "hotfix1" branch
git push

为了一次性执行多个操作,只需要在上述命令中做一个更改,按顺序提供所有提交ID:
git cherry-pick 1e2e3e4e1 1e2e3e4e2 1e2e3e4e3


0
这是一个脚本,它允许您通过告诉脚本要挑选哪些源分支和目标分支以及提交次数来一次性挑选多个提交。

https://gist.github.com/nickboldt/99ac1dc4eb4c9ff003a1effef2eb2d81

从你的分支往主分支挑选(使用当前分支作为源):

./gcpl.sh -m

从您的6.19.x分支挑选最新的5个提交并合并到主分支:

./gcpl.sh -c 5 -s 6.19.x -t master

为什么你可以直接用 Git 完成这个操作,还需要这个脚本吗?... - code_dredd
少打字,我的脚本会自动为您选择提交,因此您不必根据SHA挑选每个提交。无论如何,你的情况可能有所不同。 - nickboldt
如果你不理解脚本的作用和原理,就不要使用它。否则你将永远无法学会Git。 - Bora Sumer

0

或者使用GitHub桌面应用程序,

您可以在源分支的历史选项卡中多选提交,然后右键单击以获取“挑选所选提交”的选项。


0

除了 commit-ish,您还可以从标准输入中输入 SHA 列表

git rev-list --reverse ..main -- path/ | git cherry-pick --stdin 

rev-list 基本上是 git-log 的“不太好看但很快的表亲”命令。

请注意需要使用--reverse

您可以通过这种方式进行更高级的操作,而不仅仅是一个提交范围。


-4
git format-patch --full-index --binary --stdout range... | git am -3

70
请添加评论以说明其作用。 - Mr_and_Mrs_D

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接