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:
// 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 --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:
$ git diff api.js > simulate-error.patch
We can then send that file to a colleague, who can apply it using git apply
:
$ 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):
$ curl https://gist.githubusercontent.com/.../simulate-error.patch | git apply
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. 🔥
Hi, I’m Max! I'm a fullstack JavaScript developer living in Berlin.
When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.
If you need help on a project, please reach out and let's work together.
To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.