I'm available to work on new projects starting August 2018! Get in touch!

Back to post list

How to apply a feature to another branch in git

10-06-2016

Let's imagine the following use-case:

You maintain a package that's compatible for laravel 5.1 and 5.2. Let's just say you have two branches with the same name.

You have developed a new feature on the 5.2 branch and would like to apply it to the 5.1 branch as well. Now, it's important to know that the two branches differ from each other more than just this feature difference. If this wasn't the case you could just merge the 5.2 branch into the 5.1 branch.

Git Format

However, if both branches have a different history but would still like to apply a change from one branch to another you can use the following command:

git format-patch -1 <commit hash>

Where <commit hash> is the hash of the commit you want to use. -1 would be the amount of commits since the given hash. You can also use HEAD instead of the hash to take from the latest version.

This will create a .patch file in the root of your project. Now all you have to do is switch to the 5.1 branch (in this example) and apply the patch. To apply a patch, you can use the following command:

git apply your_file_name.patch

Now you have your feature applied to your other branch without having merged the full branch.

Read up on git-scm manual page for more information about the git format-patch command.

I'm available to work on new projects starting August 2018! Get in touch!

Finally, file streams, and deferred execution in PHP Securing your server checklist