如何在 git 添加交互式补丁模式中获得更好的帅哥?

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

我经常使用 git add -p somefile 以交互方式仅暂存给定文件中的部分内容。但是,如果文件有更复杂的更改,默认的 diff 就会出错,交互式补丁命令提供的 hunks 也会出错。

git diff 命令有许多选项可以改进或自定义 diff 输出,包括非常有用的 --anchored=<text>,但是有什么方法可以从 git add -p 获得更好的 hunks 吗?

您可以尝试以下方法:

  • 定义一个custom hunk header suitable for your case as mentioned

  • 尝试不同的 diff algorithm by passing it as a standalone configuration parameter to git add -p as mentioned

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

    根据 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".

  • 使用git-gui to manually select lines/hunks you wish to stage for commit as mentioned here and here见下方工具截图

来自 git docs,

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

但是,基于

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).

, 这个 参数默认设置(为 true)。所以可能,尝试将其设置为 false 如果 完全有帮助。