Denis' Micro Blog

Welcome! 👋

Design | Development | General
Guides | Life | Tips

The wonders of git patches

June 27, 2023 | Development

Ahoy everybody,

hope you're doing well today.

Well... For this one, I got a somewhat practical guide for something which isn't too often talked about.

Git's patch system.

Little TLDR for those of you who don't know what I am talking about.

Basically, they allow you to take differences between the repository file and your local file (even on a line-by-line basis) and then create a file that stores only those differences. You can then apply those or do whatever with them, but that covers the basics of this.

That mysterious file looks a little something like this.

An example of the contents of a git patch file

Okay. So, what is so great that you write an entire (but still small) blog post about that?

Well... Let me elaborate. Okay... I just wanted to solidify my knowledge but let me at least have that one moment of a somewhat consistent story...

Let's imagine a commit where you changed up quite a few things in different text files. Now you want to split up the changes into multiple sensible units (or patches) to separate everything up.

Why could that be a good idea? Well. Think about it. If you got some giant changes upcoming, the other side of the code review got it a bit hard. Those people have to understand what you've been doing, what you're trying to accomplish, and what you've been thinking. That comes a bit easier if you split it up into smaller steps, which are carefully thought out and semantically sensible.

Okay. How do you do that though? That's also one of the cooler parts. There is even an entire interactive mode, which you can access via git add --patch.

An example view of the git patch editor

Git automatically splits up the commit contents into what it thinks are sensible hunks. Of course, you can edit those to your personal needs, but those hunks are surprisingly accurate. Then you can finally add the hunks you need to the commit, and now...

Look at that.

"Line-by-Line" difference-based patches, which you can use for your commits and even save as a file.

Cool. I think you got why this is something interesting. Especially for larger projects, where you don't have to store copies of each file.

Hope you found that one at least a bit interesting.

See ya.