DEV Community

Christophe Colombier
Christophe Colombier

Posted on

git interactive patch

I will talk about something I'm using a lot on a daily basis, the patch mode.

what is patch about ?

The idea is to help you to choose what you want to add /remove in everything you have locally.

You may have a file with 3 changes, you will commit either in different commits or in different branches.

It's always a pain for me before I started using patch, because I had to cancel local code or play with temporary files.

Further reading

https://www.codementor.io/@maksimivanov/add-specific-lines-with-git-patch-eais7k69j

choose the modifications you want to add to the index

git add --patch
Enter fullscreen mode Exit fullscreen mode

choose the modifications you want to add to a new stash

git stash --patch
Enter fullscreen mode Exit fullscreen mode

remove the modifications you want to add to the index

git reset --patch
Enter fullscreen mode Exit fullscreen mode

restore committed changes you want from the last commit

git restore --patch HEAD^1
git commit --amend --no-edit
Enter fullscreen mode Exit fullscreen mode

Here:

  • HEAD^1 refers to the state before the last commit.
  • git commit --amend tells git to commit the changes and merge them with the last commit.
  • --no-edit allows avoiding reopening the editor

Top comments (0)