Quickly Sending Code as a Git Patch

The other day at work I was helping a coworker troubleshoot something remotely, and we eventually decided to split up and troubleshoot individually to try and cover more ground. He hadn't pushed his changes from his branch and I didn't want to completely drop what I was doing on my branch, so I decided to just send him a patch instead.

When I eventually landed on a working solution, I committed my changes, and ran this:

git format-patch commit-hash~

Of course you'll need to substitute commit-hash with the actual commit hash. The ~ at the end of the commit hash is important too, so don't leave it out (and don't put a space between it and the hash). This will give you a file, called 0001-Your-commit-message.patch, which you can then send to your recipient. Again, Your-commit-message would be your actual commit message, just with the spaces replaced with hyphens. All the person on the other end needs to do is copy that file into the directory of the git repo, and run this:

git am 0001-your-commit-message.patch

With that, they should then have a new commit from you, with the changes you made in your code. Afterwards, that patch file can be deleted.

While I used this particular approach for sending code to a coworker without interrupting my task too much, this is also a good way to contribute to open source projects that accept patch submissions via email. Feel free to reach out if you have any troubles with this method and I'd be happy to help!