96

我有两个分支,它们的历史非常相似,但彼此相关。

我想要在一个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
4

3 回答 3

138

将“来自 branch_b..branch_a 的差异”转换为提交的简单方法是:

  1. 在 branch_a ( git branch tmp branch_a && git checkout tmp) (或git reset --hard branch_a现有分支上)创建和签出分支 tmp
  2. git reset --soft branch_b
  3. git commit

该提交将包括 branch_b 和 branch_a 之间的所有差异。


这有效,因为

  • 1.导致文件反映 branch_a。这是您想要的分支的“最终结果”
  • 2.“将 head 重置为 branch_b”,但“将所有更改的文件 [即 branch_a head] 保留为“要提交的更改”,就像 gitstatus所说的那样。” ←( git reset --softdocs , 添加了这个例子的分支)
于 2013-06-26T15:49:48.267 回答
36

如果你有两个分支:

  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
于 2018-12-04T21:53:56.137 回答
12

这一切都归结为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
于 2019-05-03T17:29:14.267 回答