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

1

5

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?

Rebel answered 10/12, 2019 at 15:6 Comment(4)
git add -p is actually a perl script: git --exec-path tells you where it lives; look in this directory for git-add--interactive. You should be able to modify this to invoke git diff with --anchored=<text>.Paolo
use emacs magitFreeswimming
Could you perhaps show one of these hunks that bothers you? Better than what? In what text?Mansard
@Paolo it won't always be a perl script: https://mcmap.net/q/328721/-multiple-staging-areasTrollop
L
10

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

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.

Louislouisa answered 19/12, 2019 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.