I recently learned a nice little trick that has come in handy in a few situations already! 🤓
Sometimes we want to share changes to one or more files in a git repository that are temporary and don't warrant their own branch or commit.
For example, we might want to share a line of code that throws an error in a certain place to test error handling:
JSX
// api.jsasync function fetchUser() {throw new Error('User not found')const { user } = await api.get('/users/me')return user}
If you run git diff
, you can see the one-line-change:
DIFF
diff --git a/api.js b/api.jsindex 98293fe..820a715 100644--- a/api.js+++ b/api.js@@ -1,4 +1,5 @@async function fetchUser() {+ throw new Error('User not found')const { user } = await api.get('/users/me')return user
To share this exact change with somebody else, we can simply store the output of git diff
in a file:
BASH
$ git diff api.js > simulate-error.patch
We can then send that file to a colleague, who can apply it using git apply
:
BASH
$ git apply simulate-error.patch
Note that git apply
needs to be run from the root of the repository!
You can also upload the patch-file to a Gist for example (quickly create one with gist.new) so it can be applied like so (using the file's raw URL):
BASH
$ curl https://gist.githubusercontent.com/.../simulate-error.patch | git apply
Bonus Tip: GitHub Pull Requests as Raw Patch Files
Thanks to my Twitter friend Max (he has the exact same name as me, don't be confused ^_^) for this tip:
You can add ".patch" to a pull request's URL and it will give you a raw patch-file that contains all the changes in that PR.
E.g. opening
https://github.com/microsoft/playwright/pull/7644.patch
in your browser will redirect you to
https://patch-diff.githubusercontent.com/raw/microsoft/playwright/pull/7644.patch
which is a patch-file. 🔥