Monday, January 28, 2013

Patching with git

In this post I will show you how to make a patch with git and then apply it.
The first thing we will need is a test project.
We will begin by cloning a repository from github.com, with read only access.
git clone git://github.com/gulyan/gulyan.github.git test
cd test
This will clone a very simple git project.
The first thing we will do is make a new branch. It's considered best-practice to commit your fixes in a separate branch:
git checkout -b my_fix_branch
To view your current branch, you can type:
> git branch
master
* my_fix_branch
Now you can play around and add a couple of commits to this branch.
When you are read to make a patch, you will use the format-patch command.
If you run it without the --stdout argument, it will create a patch file for every commit.
We want to put all the commits in a single file so we use --stdout and we redirect it to a file like this:
git format-patch master..HEAD --stdout > my_fix.patch

Now let's try and apply this patch. First we go back to the master branch:
git checkout master

Before we apply the path, we want to make sure it will not cause problems.
The first thing we should do is run git apply with the --stat argument. This command will show us what the patch will modify:
> git apply --stat my_fix.patch
README |    4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
After this we run git apply with the --check argument. This will not apply the patch. If we don't get any errors we can safely apply the patch.
git apply --check my_fix.patch
In order to apply the patch we will use the git am command:
git am my_fix.patch
This will apply the patch and the commit messages.
If we use git am, we can also signoff on the commits by adding the --signoff argument.

You could also apply the patch with git apply:
git apply my_fix.patch
This will apply the patch to the files, but it will not commit the changed to the branch.
You need to add the files and commit them manually.
For most use cases, I recommend you use git am.

If you have any problems, with git am you can fix the files, add them to the index and then run git am --resolved. To abort a patch use git am --abort.

No comments:

Post a Comment