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

Jaa*_*raj 8 git github git-merge git-branch

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

mkdir test-repo
cd test-repo/
git init
Run Code Online (Sandbox Code Playgroud)

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

echo 0 > file.txt
git add file.txt
git commit -m '0'
Run Code Online (Sandbox Code Playgroud)

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

git checkout -b A
Run Code Online (Sandbox Code Playgroud)

文件现在在分支 A 中更改,在下一行添加“1”

file.txt
0
1
Run Code Online (Sandbox Code Playgroud)

致力于分支A

git add file.txt
git commit -m '1'
Run Code Online (Sandbox Code Playgroud)

在“A”中添加了一个空的新文件 file1.txt。然后承诺

git add file1.txt
git commit -m 'new file'
Run Code Online (Sandbox Code Playgroud)

现在 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
Run Code Online (Sandbox Code Playgroud)

现在我想将分支 A 合并到 master,仅使用“76633b7”(最后一个)提交。我不想在主控中使用“commit:1”(070f015)。我怎样才能做到这一点?。git merge A 会将所有更改提交给 master。

Taj*_*din 10

有两种情况。

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

 i)  git checkout master
 ii) git cherry-pick 76633b7
Run Code Online (Sandbox Code Playgroud)

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 
Run Code Online (Sandbox Code Playgroud)

现在,您的第二次提交位于顶部,而您要合并的其他所有内容都位于第二次提交下方。

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

git merge 76633b7
Run Code Online (Sandbox Code Playgroud)