Creating and Applying Git Patch Files

12 Feb 2017

I was recently reviewing code on a project where I didn’t have write access,
and wanted to suggest a small code change to the team.
As I couldn’t send a pull request to make the change,
I had to look into how to create a patch that I could then email.

Creating a patch

In this example, we will add a line to a Rails project’s Gemfile.
When we add a gem 'rspec-rails' line, git diff looks like this:

Now let’s look at what happens when you add a new file to the working directory.
Create a notes.txt, add a couple of lines there, and run git diff.
You will notice that the new file is not present in the diff.
To get it, you will need to stage all the files and then run git diff --cached.

Applying a patch

Now that we have looked at the different ways to create patches,
let’s see how we can apply a patch file to the working directory.
Let’s checkout a review-rspec-patch branch from master first.
Now let’s apply one of the patch files we created earlier:

git apply 0001-Add-rspec-to-gemfile.patch

Using git apply provides the patch as unstaged changes in your branch.
If you want to apply the patches as commits, you can use git am.

Links

Hi, I’m Nithin Bekal.
I work at Shopify in Ottawa, Canada.
Previously, co-founder of
CrowdStudio.in and
WowMakers.
Ruby is my preferred programming language,
and the topic of most of my articles here,
but I'm also a big fan of Elixir.
Tweet to me at @nithinbekal.