将一个分支中的最后一个提交合并到主分支中

8

我使用以下命令创建了一个测试代码库

mkdir test-repo
cd test-repo/
git init

我在目录中创建了一个文件并提交了更改

echo 0 > file.txt
git add file.txt
git commit -m '0'

我创建了一个新的分支用于开发

git checkout -b A

文件现在在A分支中被修改,下一行添加了“1”。
file.txt
0
1

提交到分支A

git add file.txt
git commit -m '1'

在'A'中添加了一个空的新文件file1.txt,然后进行了提交。
git add file1.txt
git commit -m 'new file'

现在,reflog命令显示如下:
76633b7 (HEAD -> A) HEAD@{0}: commit: new file
070f015 HEAD@{1}: commit: 1
dfab60f (master) HEAD@{2}: checkout: moving from master to A
dfab60f (master) HEAD@{3}: commit (initial): 0

现在我想将分支A合并到主分支,但只想包含最后一个提交'76633b7',不想将'master'中的提交'commit:1'(070f015)包含进来。我该如何处理?运行'git merge A'会将所有更改提交到'master'分支。

你想要除了 76633b7 以外的所有内容都在主分支中吗?还是只想要将 76633b7 合并到主分支中?如果是后者,那么可以使用 "git cherry-pick 76633b7" 命令将其从主分支中提取出来。 - Taj Uddin
没错,那个有效了...我试过了。 - Jaango Jayaraj
我已经添加了第二种情况的答案。你可能想看一下 :) - Taj Uddin
4个回答

10

有两种情况。

1)您只想将最后一个提交(76633b7)合并到主分支。 - 在这种情况下,请按照以下步骤操作

 i)  git checkout master
 ii) git cherry-pick 76633b7

2) 你想将分支A的所有内容合并到主分支上,但除了倒数第二个提交。 - 这有点棘手,你需要按照以下步骤操作:

 i) Change the order of last and second last commit


  git rebase -i HEAD~2

  Next, change the order of the commits in the prompt.

  pick 76633b7 
  pick 070f015

  to 

  pick 070f015
  pick 76633b7 

现在你的第二次提交位于顶部,你想要合并的所有其他内容都在第二个提交下面。

ii) 现在你可以简单地使用旧的第一次提交的提交ID(现在是第二个)进行合并。

git merge 76633b7

4

您可以提供修订版本的id进行 cherry-pick (如先前所述),但是如果您要 cherry-pick 一个分支,只有最后一个修订版本会被 cherry-pick,因此这也可以起作用:

git checkout master
git cherry-pick A

1

这个问题没有直接的解决方案。你的提交 76633b7 基于提交 070f015,并且理论上可能依赖于你在那里所做的操作。

你可以做以下几点:

git checkout -b B master # create a new branch B from master
git cherry-pick 76633b7 # apply the commit 76633b7 and resolve conflicts if any

现在B分支只包含您想合并到主分支的提交。


@JaangoJayaraj在这种情况下,请接受这个答案,以便其他人可以看到这个问题已经解决。 - Chris Maes

1
为了从另一个分支合并最新的提交,您可以使用cherry pick命令,后面跟随您想要选择最新提交的分支名称。 https://git-scm.com/docs/git-cherry-pick#_examples 应用主分支顶部提交引入的更改,并创建一个包含此更改的新提交。
git checkout develop // the branch you want to merge commit into
git cherry-pick master // the branch you want to get commit from

我尝试使用git cherry-pick commitid,但出现了错误:commit commitid是一个合并请求,但未提供 -m 选项。 然而,通过使用分支名称和 cherry-pick,我成功地将最新的提交合并到了一个分支中。


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