Git — Saving (and sharing) snippets of code without using git-stash.
When working with Git, it’s not uncommon to make changes to your code that you might not want to commit just yet. This is where stashing comes in handy, as it allows you to save your changes without committing them to your codebase.
However, stashes can sometimes get lost in the bunch or worse. And if you want to share these changes with other developers, you’ll find that is outside the scope of git-stash.
Saving
In such cases, you can use the following command to save your changes:
git diff > important-stuff.patch
This command will create a patch file named important-stuff.patch
that contains a list of all the changes you have made in your Git repository. The >
symbol tells the Command Prompt to redirect the output of the git diff
command to a file named important-stuff.patch
. If the file doesn't exist, it will be created. If it does exist, its contents will be overwritten.
You can also diff specific files:
git diff index.ts app.tsx > layout-changes.patch
git diff src/*.tsx > component-changes.patch
git diff src > changes.patch
Sharing
You can then send this patch file to your team members; this is especially helpful if you are sharing mocks to test a specific flow in the code.
When you need to apply the changes you saved in the patch file, you can use the following command:
git apply important-stuff.patch
If you run into the “patch does not apply” error, you can use --3way
flag (see docs) to attempt a 3-way merge and generate conflict markers just like it would with git-stash
:
git apply important-stuff.patch --3way
In conclusion, using git diff > file_name.patch
and git apply file_name.patch
is a handy way to save code snippets. This technique is especially useful when you don't want to lose specific changes, or when you want to collaborate on code with your team members.