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?

4
  • 1
    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>. Commented Dec 10, 2019 at 18:28
  • use emacs magit Commented Dec 19, 2019 at 11:48
  • 2
    Could you perhaps show one of these hunks that bothers you? Better than what? In what text? Commented Dec 19, 2019 at 15:15
  • @torek it won't always be a perl script: stackoverflow.com/a/59382252/6309 Commented Dec 20, 2019 at 8:56

1 Answer 1

13
+500

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.