I have two branches, email and staging. staging is the latest one and I no longer need the old changes in email branch, yet I don’t want to delete them.
So I just want to dump all the contents of staging into email so that they both point to the same commit. Is that possible?
You can use the ‘ours’ merge strategy:
The question requires the commits of the
emailbranch to be kept. They must not be made unreachable, which rules out anyreset-based approaches or deleting and recreating the branch.To keep commits of both branches reachable, one or more references must exist that point to those commits. You can always keep two references (
stagingandemail), but the question asks to get rid of one of the refs. Therefore, the branches need to be merged somehow.EDIT 2020-07-30:
I thought a bit more about this question and possible solutions. If you absolutely require the merge parents in the correct order, need to perform this action with a single command line invocation, and don’t mind running plumbing commands, you can do the following:
This basically acts like the (non-existent)
merge -s theirsstrategy.You can find the resulting history in the
plumbingbranch of the demo repositoryNot very readable and not as easy to remember compared to the
-s oursswitch, but it does the job. The resulting tree is again the same as branch B:EDIT 2020-07-29:
There seems to be a lot of confusion as to what the difference between
-s oursand-X ours(the latter being equivalent to-s recursive --strategy-option ours) is. Here’s a small example to show the two results from using these two methods. I also recommend reading the question and answers of (Git Merging) When to use 'ours' strategy, 'ours' option and 'theirs' option?First, setup a repository with 2 branches and 3 commits (1 base commit, and 1 commit per branch). You can find the sample repository on GitHub
Now, let’s try the strategy option (doesn’t really matter if we use theirs or ours for this explanation):
We end up with a merge of both branches’ contents (branch "strategy-option" in the sample repo). Compare that to using the merge strategy (re-init your repository or reset branch, before executing the next steps):
The result is quite different (branch "merge-strategy" in the sample repo). With the strategy option, we get a merge result of both branches, with the strategy we throw away any changes which happened in the other branch.
You will also notice that the commit created by the merge-strategy in fact points to the exact same tree as the latest commit of "our" branch, while the strategy-option created a new, previously-unseen tree:
OP indeed asked for "I no longer need the old changes in […] branch" and "So I just want to dump all the contents of [A] into [B]", which is not possible to do with a strategy option. Using the ‘ours’ merge strategy is one possibility of many, but likely the easiest (other possibilities include using low level commands of Git such as
write-treeandcommit-tree).