Hey! In this post, get a quick glimpse of what is a git patch? How can you create and apply that? What are its use cases, etc? Let’s get started. 🙂
1. What is git ?
Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. And it’s easy to learn and get started. I wrote a tutorial here on git-github when I first learned it, available here: Git Github Tutorial (1)
2. What is a git patch ?
If you have experience with git, then a patch is none other than the git-diff. It simply contains the changes done (previous and new states), or we can say that it contains the patch that fixes or add something upon the previous state. A typical patch looks like this:
diff --git a/file1 b/file1 index 839cf35..18a4bf8 100644 --- a/file1 +++ b/file1 @@ -1,3 +1,3 @@ -This is a line in a file +This is the changed line1 in a file This is line2 in the same file
Here, plus ( + ) sign indicates additions and minus ( – ) sign indicates deletions.
3. Why do we need a git patch ?
- To send your changes to someone else.
- To copy your changes from a git branch to paste it into another branch (in case git merge is not a feasible option).
- Just in case you need to save a copy of your changes.
4. Create a patch of specific git commit
To create a patch just redirect your git-diff of a commit to a file. Simple!
git diff 11111commit1111hash11111856d7865615 > ./patchfile
To create a patch for current git diff:
git diff > ./patchfile
Note: The name patchfile is trivial, you can use any name of your choice.
5. Create a patch of combined commits of a git branch
To create a patch for the whole branch changes compare to the base or any other branch:
git diff base_branch derived_branch > patchfile
6. Apply a git patch
To apply a git patch we’ll use git-apply:
git apply path/to/patchfile
When required, patches are lovely! A couple of times I share my changes with friends without sending them a PR on GitHub. You may have your reasons as well 🙂
Thanks for reading!
See you in the next post 🙂
PS: Git is full of surprises!
8. Further read