git create commit from diff between two branches

2020-05-11 21:20发布

I have two branches which have very little similar history, but are related to each other.

I want the changes between those two in one git commit.

files have been deleted and created between those patches and I want the patch to reflect that

i.e.: the following stuff will not work:

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

标签: git
3条回答
可以哭但决不认输i
2楼-- · 2020-05-11 21:47

If you have two branches:

  1. has-changes
  2. needs-changes

And you want to move the changes from has-changes onto needs-changes, then do the following:

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
查看更多
手持菜刀,她持情操
3楼-- · 2020-05-11 22:01

It all comes down to a git reset --soft branch_b on top of a temp branch based on branch_a, and the result committed back to branch_b.

This is a step-by-step walking through the process:

#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
查看更多
够拽才男人
4楼-- · 2020-05-11 22:04

A simple way to do it is:

  • create and checkout branch tmp at branch_a (git branch tmp branch_a && git checkout tmp)
  • git reset --soft branch_b
  • git commit

that commit must have all the diff

查看更多
登录 后发表回答