Generating Patch Emails With Git

By Andrew Price, 2008-04-07 19:20:58 in General.

Today was the first time I've used git to produce an email containing a patch that I'd written and I was impressed at how simple it is. I thought I'd share how it was done to help other git learners, and to help me remember it for next time. For this to make sense, assume that I had just cloned the git tree so that I'm working with a new, clean tree.

First I created a new branch to keep my work separate, using:

git checkout -b mybranch

Then I edited some code, tested that my fix worked, and committed my changes using:

git commit -a

When you commit, git opens an editor (in my case, vim) in which to enter your commit message. It's worth noting here that the first line of the commit message is used as the short log (the 'title' of the commit), and the rest is used as the body of the log message. The short log will become the 'subject' header of your email later.

Once my changes were committed, I used format-patch to produce the email with my patch in it, like so:

git format-patch -1 -s --subject-prefix='PATCH][BUILD'

This produced a nicely formatted email-able text file containing my patch. The file includes the 'From' email header which it generates using the email address and name stored in your git config. You can find information about all the possible format-patch options from the man page but the ones I used were:

I then used mutt to send the patch by using its -H option which loads a template email:

mutt -H 0001-Example-patch-name.patch

Then all I needed to do was tell mutt which address to send the email to, and hit y to send. Simple as that.