Merging from trunk to a branch

You created a branch in subversion, and while you were working on it, trunk progressed. You now want to include the trunk updates in your branch. What should you do? Maybe merge from trunk into your branch?

svn merge ${url}/trunk branches/mybranch

Nope! This isn’t it. Think about the simple case: branch out, edit the branch, merge back. What does ‘merge’ mean in this case? If I understand correctly, it means replaying on trunk all the changes you made to your branch.

What happens when you run the above command then? You replay all the changes you made to trunk, on top of your branch. Once that is done, what happens when you want to merge your branch back to trunk? One of the changes to be replayed is the merge you did, but it contains changes that have already been made on trunk, and the merge does not work.

How to do it properly then? What you probably meant to do, is to have your branch as if you started your branch-work on the newer trunk. Let’s first consider the simple case, where you branch out and then merge back.

svn cp ${url}/trunk ${url}/branches/mybranch
svn update
...editing your branch...
svn commit -m "edits to my branch"
svn merge ${url}/branches/mybranch trunk
svn commit -m "merging mybranch back to trunk"

That works. And it cannot really be more complex than that. Maybe if you’re a subversion whiz, but I’m not, so I like to stick to simple scenarios I can understand.

Let’s try to accommodate an updated trunk into the above workflow. It starts as usual:

svn cp ${url}/trunk ${url}/branches/mybranch
svn update
...editing your branch...
svn commit -m "edits to my branch"

So far so good. Let’s say there are some updates to trunk we want to see in our branch. You would think: “Why didn’t I start working on my branch later, I would have all the updates already in my branch!”. It turns out, you can do that! You can create an new branch from the new trunk, and then replay all the changes from your branch on top of it. The result? You still have your changes in a separate branch, and you have the updates to trunk too.

svn status
# Make sure this returns nothing ‒ your working copy is clean.
svn cp ${url}/trunk ${url}/branches/mybranch2
svn update
svn merge ${url}/branches/mybranch branches/mybranch2
# There is potential for code conflicts here, you need to resolve them.
svn commit -m "Replaying changes made to mybranch onto mybranch2."
svn rm ${url}/branches/mybranch
# Let's go to the original branch name.
svn mv ${url}/branches/mybranch2 ${url}/branches/mybranch
svn update

Your branch is now updated and looks as if you’ve started to work on it using the new trunk. You can use the regular merging procedure.

svn merge ${url}/branches/mybranch trunk
svn commit -m "merging mybranch back to trunk"

Your changes are now merged back to trunk.

Author: automatthias

You won't believe what a skeptic I am.