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:
We can save this as a patch file, without committing the code.
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.
Now the patch looks like:
What if the new file we added was a binary file?
This time we will add a logo.jpeg file and stage it.
We can use the --binary option.
The patch file will look like this:
Creating patches from commits
Suppose you have created a new branch and made two commits -
one for adding rspec to Gemfile, and another for the notes file.
You can create a patch file for the commits by using git format-patch.
This will create a patch file for each commit.
Let’s take a look at what one of the files looks like:
If you don’t want to create multiple patch files, you can do this:
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:
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.
Hi, I’m Nithin!
This is my blog about programming.
Ruby is my programming language of choice
and the topic of most of my articles here,
but I occasionally also write about Elixir,
and sometimes about the books I read.
If you want to subscribe to this blog,
the feed is available here.