简化“git add”在“git diff”之后的操作

4
在将任何文件添加到 Git 之前,我总是调用 git diff <filename> 命令,并经常使用额外的选项(例如 "-w"、"--word-diff" 等)。
diff 显示良好时,我通过 "git add <filename>" 将文件暂存以进行提交。 我目前的做法是通过修改以前的命令行 git diff 来实现这一点,即删除 diff 和任何选项,这种方法效率低下且冗余。
如何通过命令行执行 diff 并可选地执行 add

4
我认为你正在寻找交互模式,可以通过 git add -i(或 -p)进入。 - Vasan
1
有很多集成开发环境和Git工具可以处理这样的工作流程。但是 git add -p 可以实现你想要的:在添加和拒绝 Hunks 的同时查看差异。否则,你可能需要编写一个定制的可执行文件来完全满足你的需求。在 PATH 中命名为 git-foo 的任何可执行文件都将作为 git foo 可用;这只是一些语法糖。 - Schwern
2
以上建议都很好,但是假设你使用的是zsh或bash(也许其他Unix shell),一个有用的技巧是在输入转义字符后跟着一个“.”,可以插入上一个命令的最后一个参数。因此,你可以为git diff设置别名gd,为git add设置别名ga,然后就可以使用gd <文件名>,接着使用ga <esc> . - mikej
2
@mikej 你可以用 Alt 键代替 ESC 键。对于大多数其他 ESC/Alt 命令也是如此;ESC 只是为不支持 Alt 的键盘提供兼容性选项。 - 0x5453
2
@mikej 这可能是你想要的:https://superuser.com/a/85010/401176 - 0x5453
显示剩余3条评论
1个回答

2

若要选择性地应用差异块,请使用-p选项,也称--patch选项。 git add -p将从工作树应用到索引,git checkout -p将从索引或命名提交应用到索引和工作树,git reset -p将从提交中应用到索引。

每个差异块的选项如下:

Apply this hunk to index [y,n,q,a,d,/,j,J,g,e,?]? 
y - apply this hunk to index
n - do not apply this hunk to index
q - quit; do not apply this hunk or any of the remaining ones
a - apply this hunk and all later hunks in the file
d - do not apply this hunk or any of the later 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

你可以通过输入问号或回车键来获取帮助信息。

为了避免在命令行中重复输入相同的内容,$_ 会展开为上一个命令的最后一个参数,例如 git diff --word-diff @ path/to/file 后可以直接使用 git add $_。还有历史扩展功能,它可以从历史记录中提取单词,并且因不同的 shell 而略有不同,!$ 表示“上一行的最后一个单词”,!#$ 表示“当前行的最后一个单词”,因此可以使用 sort -nrk2,2 -o mylist !#$ 来进行原地排序。


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