The quickest way to create a Git patch
Git patches are text files that contain code and metadata that represent a set of changes to make in a code repository. Think of them as commits but packaged as a file.
In the era of pull requests many people don't create, apply or send patches around manually. I would argue that they still have their use cases even in pull request workflows, e.g. for sending simple fixes and proposals to colleagues without messing with their branches.
Many of you most likely used the git diff
command to see changes before making a commit. It looks like this:
The beauty of the git diff output is that it actually produces a valid patch that can be copy pasted and applied elsewhere. With a Linux/Unix shell like Bash it is then trivial to make a file out of the output:
git diff > mypatch.patch
And just like that, we have created a Git patch file!
Such patch file can be opened and examined in a code editor with syntax highlighting:
However, the most useful thing is that we can send the file to other developers and they can examine the changes even if the code is not commited anywhere. Or we can store the changes for our future reference as an alternative to Git stash.
Now only the last question remains. How to use the patch if we received it from someone else or want to use the changes we saved previously?
Then it is just:
git apply mypatch.patch
Git apply will take the change set and apply it to your current version of the files in the repository, without committing them. You can then stage and commit the changes or discard them afterwards.