git从两个分支之间的差异创建提交


76

我有两个分支,它们的相似历史很少,但是彼此相关。

我希望在一个git commit中在这两个之间进行更改。

文件已被删除并在这些补丁之间创建,我希望补丁能反映出来

即:以下内容将不起作用:

git diff branch_a branch_b -- > patchfile
git checkout branch_b
git apply patchfile # deletes and adds are ignored
git commit # we miss the deletes

Answers:


120

一种简单的方法是:

  • 在branch_a(git branch tmp branch_a && git checkout tmp)创建和签出分支tmp
  • git reset --soft branch_b
  • git commit

该提交必须具有所有差异


1
您不需要共同的提交,甚至不需要碰触前面的分支。只需尝试在gitk中进行操作-当您尝试将要消失的新分支时,就可以自由运行了。
2013年

使用git 1.7.9.5为我工作
wischan

10
更精确地讲:git branch tmp branchA && git checkout tmp && git reset --soft branchB && git checkout branchB && git branch -D tmp && git commit
bernstein

分支b名称有错字,应为to_branch_b
hywak

那是git reset --soft <branch_b>git commit
哈利·莫雷诺

25

如果您有两个分支:

  1. has-changes
  2. needs-changes

您想将更改从has-changes移到needs-changes,然后执行以下操作:

git checkout -b deleteme has-changes # Create temporary branch to build commit on
git reset --soft needs-changes       # Move diff into index
git commit                           # Create the diff patch commit
git checkout needs-changes           # Switch to branch that needs changes
git cherry-pick deleteme             # Apply the diff to the needs-changes
git branch -D deleteme               # Delete the temporary branch

8

所有这些都归结为git reset --soft branch_b基于branch_a的临时分支的顶部,并将结果提交回branch_b。

这是逐步进行的过程:

#Start out on the branch with the code we want
git checkout branch_a

#create tmp branch same as branch_a (so that we don't change our local branch_a state during the operation)
git branch tmp

#working directory has all the code that we want, on tmp branch
git checkout tmp

# Change the branch head to the branch we want to be on. All the delta
# between the current source code and branch_b is now staged for commit
git reset --soft branch_b

# Move away from tmp, so our commit will go directly to branch_b
git checkout branch_b

# Now you can examine the proposed commit
git status

# Add the delta we want to the branch
git commit

# Sanity check that the branches have the same content now (should return an empty line)
git diff branch_A..branch_b

# Remove tmp, we don't need it anymore
git branch -D tmp
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.