Skip to content

Let's talk about patching

Time to read:
3 minutes

You might have heard of patching, but maybe you never crossed a concrete usage.

In this section I will try to give a simple answer to the three following questions:

  • What exactly is a patch?
  • Why would you need this tool?
  • How is it working?

Definition

Let's start from the beginning: what's a patch?

A patch is a file that describes changes between two versions of one, or more, files.

Applying a patch is an action that takes such a change description to reproduce the set of changes on a repository.

Show the difference

First, you need to have idea on how Git is maintaining the history of your code changes.

When you begin a project you will create new files. Those file contents are stored inside Git repository as commmits.

As project evolves, you need to edit those files and update their content.

  • you may add new lines of code;
  • or you perform cleanup and delete lines of code.

And at the moment you commit your changes, you don't expect that Git is going to save the entire file content again.

Git only stores a description of your changes.

This description is known as the diff (standing for difference) between previous version of the file and the new version.

This is an efficient way to record the history of changed in your repository. A diff is the building block of your repositoty, the way to track and explore changes, and the core tool powering the patch mechanism.

Share the changes

At a given a state of your repository, when you edit a file and save the changes, then Git is able to display this diff as a specific and readable result.

Well, if you can display the diff, then you can also save it into a file that can be shared.

And here is the magic of patching: you can can use this diff to apply it on your repository, or another one, at any time.

In short: you can manually reproduce internal Git behavior.

Git exposes two commands for you:

  • diff is how you can can display your changes as formalized compact text file.
  • patch is using a diff file to apply the changes on a file.

But why would you want to apply a change this way?

Why is patching useful?

You can find multiple use cases to adopt patch workflow.

  • you do pair programming and you need to share edits from one to the other;
  • you need to submit a quick fix but cannot, or don't want to, open a pull request.
  • Your project relies on email workflow to handle changes. For example, this is the way Linux kernel is managed.