Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get better hunks in git add interactive patch mode?

I often use git add -p somefile to interactively stage only parts of the in the given file. However, if the file has more complicated changes, the default diff goes awry and so do the hunks offered by the interactive patch command.

The git diff command has a number of options to improve or customize the diff output, including the extremely useful --anchored=<text>, but are there any means get better hunks from git add -p?

like image 369
jotik Avatar asked Mar 03 '23 01:03

jotik


1 Answers

You could try the following :

  • Define a custom hunk header suitable for your case as mentioned here

  • Try a different diff algorithm by passing it as a standalone configuration parameter to git add -p as mentioned here

    git -c diff.algorithm=<algo-name> add -p
    

    The available diff-algorithms as per git docs,

-diff-algorithm={patience|minimal|histogram|myers}

Choose a diff algorithm. The variants are as follows:

default, myers The basic greedy diff algorithm. Currently, this is the default.

minimal Spend extra time to make sure the smallest possible diff is produced.

patience Use "patience diff" algorithm when generating patches.

histogram This algorithm extends the patience algorithm to "support low-occurrence common elements".

  • Use git-gui to manually select lines/hunks you wish to stage for commit as mentioned here and here (See the screenshot of the tool below)

git-gui

  • Modify the hunk's size itself

  • Set this diff.indentHeuristic parameter

    git -c diff.indentHeuristic=true add -p
    

From git docs,

diff.indentHeuristic
Set this option to true to enable experimental heuristics that shift diff hunk boundaries to make patches easier to read.

However, based on this

With Git 2.25 (Q1 2020), you don't even have to specify --indent-heuristic anymore (since it is the default for quite some times now).

, this parameter is set (to true) by default. So probably, try setting it to false if at all it helps.

like image 172
Saurabh P Bhandari Avatar answered Mar 05 '23 14:03

Saurabh P Bhandari