Git power tool: patch

mathijs81

Mathijs Vogelzang

Posted on November 15, 2022

Git power tool: patch

Git has many tools that you don't normally encounter in day-to-day use.

One very powerful one I've started using recently is the "patch" flag.

Say you're working on a branch, and you discover you need something you've already implemented on a different branch. Not the whole change, just a tiny bit (in case you want the whole change, git cherry-pick or git merge are more appropriate).

Instead of manual switching and code-copying, you can use git checkout --patch (or git checkout -p for short).

It works like this:
I'm on branch featureA and want to copy things from branch featureB.

I execute:

$ git checkout -p featureB
Enter fullscreen mode Exit fullscreen mode

(If you know which particular file or directory you want to patch, you can also add that as the last argument, like git checkout -p featureB src/my_page.tsx)

I now get walked to all parts of the change (called hunks) and get asked if I want to apply them or not:
Screenshot of patching with git

Very convenient!

💖 💪 🙅 🚩
mathijs81
Mathijs Vogelzang

Posted on November 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Git power tool: patch
git Git power tool: patch

November 15, 2022