Friday, April 8, 2016

How to create and apply a patch with Git

Hi, Today we will learn how to create and apply a patch with Git.

To make creating patches easier, there are some common git practices we should follow. It’s not necessary, but it will make our life easier.

If you fix a bug or create a new feature – we should do it in a separate branch!

Let’s say we want to create a patch for my branch branch1. We clone repository and create a new branch for the fix we have in mind. In this sample we’ll do an imaginary fix for branch2.

git clone git://github.com/username/branch1.git
cd branch1
git checkout -b branch2

Now, in the new branch2 branch we can hack whatever we need to fix. Write tests, update code etc. etc.

When we’re satisfied with all our changes, it’s time to create our patch.

Creating the patch
Okay, We’ve made some commits, in branch2 branch:

Okay, now it’s time to go and make a patch! All we really want are the two latest commits, stuff them in a file and apply them. But, since we created a separate branch, we don’t have to worry about commits at all!

git format-patch master --stdout > branch2_patch.patch

This will create a new file branch2_patch.patch with all changes from the current (branch2) against master. Normally, git would create a separate patch file for each commit, but that’s not what we want. All we need is a single patch file.

Now, you have a patch for the fix we wrote.

Applying the patch

First, take a look at what changes are in the patch. We can do this easily with git apply

git apply --stat branch2_patch.patch

Note that this command does not apply the patch, but only shows us the stats about what it’ll do. After peeking into the patch file with our favorite editor, we can see what the actual changes are.

Next, we’re interested in how troublesome the patch is going to be. Git allows us to test the patch before we actually apply it.

git apply --check branch2_patch.patch

If we don’t get any errors, the patch can be applied cleanly. Otherwise we may see what trouble we’ll run into. To apply the patch, We’ll use git am instead of git apply. The reason for this is that git am allows us to sign off an applied patch. This may be useful for later reference.

git am --signoff < branch2_patch.patch

Okay, patches were applied cleanly and our master branch has been updated.

In our git log, we’ll find that the commit messages contain a “Signed-off-by” tag. This tag will be read by Github and others to provide useful info about how the commit ended up in the code.

Thanks.

No comments:

Post a Comment