增加git hunk的粒度

21

我通常使用git add -p添加更改,有时会出现由多个代码块组成的大块,它们之间用空行分隔。

但是,git不会进一步分割这个块,因此我不得不手动编辑。

如何增加块的细粒度,使每个代码块都在单独的块中?

编辑:这与Git:使用git add -i或git add -e时显示更多上下文? 的问题不同,因为我不是要增加每个块周围的上下文,而是要增加块的数量。

3个回答

22

无法完成。

add -p中,以下是您可以执行的选项:

y - stage this hunk
n - do not stage this hunk
q - quit, do not stage this hunk nor any of the remaining ones
a - stage this and all the remaining hunks in the file
d - do not stage this hunk nor any of the remaining hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help

如果您使用s标志,它将选择可视为独立更改的代码块。如果您想进一步拆分它,则需要使用e编辑该块,然后将其添加回到阶段区域。

摘要:

要拆分块,您可以使用s标志。
如果您需要将其拆分成更小的块,则需要使用e选项手动编辑它。

enter image description here


1
谢谢,但我非常清楚add -p的工作原理,并且我正在寻找一种不需要手动编辑的解决方法。 - dimid
3
答案是“无法完成”,我担心你坚持想要做这件事是没有帮助的。 - Marcus Müller

4
如@codeWizard在他的答案中所说,git并不支持你想要的功能,因此无法在git add中完成。
现在,你可以自己编写脚本来执行以下操作:
1.将你本地修改的版本复制到树外的某个位置
2.使用git checkout -- 将修改后的文件恢复到未修改状态
3.编写自己的用户界面以选择要添加的文件范围
4.将修改内容添加到树内
5.git commit
6.如果需要,再次执行第3步

2

git gui 可以让你选择特定行进行暂存。

在 git 存储库中打开 git gui,然后右键单击所需的行 >“为提交暂存行”。

现在,它不会让你编辑文件(我希望它能在您喜欢的编辑器中打开临时文件)。为解决这个问题,您只需在提交消息中标记提醒即可:

AMENDME: Add x
do not forget to rename thing

当你完成编码后,可以使用git rebase -i <原始分支>命令,用edit命令标记“AMENDME”提交并修改该提交。


1
我强烈不同意。我的开发平台非常简单:一个文本编辑器(emacs)和git命令行实用程序。有时我会使用git gui等工具来审查和处理更复杂的提交;当我发现一个错别字时,回到编辑器中进行更正有点麻烦,它可以为我完成这项工作。 - sleblanc
我不认为提交和修改有意义,这会很冗长。 - TUSqasi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接