仅将分支的最后一次提交合并到 master

Merge only the last commit from a branch into master

我使用以下命令创建了一个测试存储库

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 合并到 master,只有带有“76633b7”的提交(最后一个)。我不想要 master 中的 'commit:1'(070f015)。我怎样才能做到这一点?。 git 合并 A 会将所有更改提交给 master。

没有直接的解决方案。您的提交 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 分支仅包含您要合并到 master 中的提交。

有两种情况。

1) 您只想将最后一次提交 (76633b7) 合并到 master。 - 在这种情况下,只需按照

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

2) 除了倒数第二个提交之外,您想要 master 分支 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

您可以向 cherry-pick 提供修订版的 ID(如前所述),但如果您要求 cherry-pick 一个分支 只有最后一个修订版将 cherry-picked 所以这也将起作用:

git checkout master
git cherry-pick A