git add -p
命令允许对文件的块或部分进行交互式分级(https://git-scm.com/book/en/v2/Git-Tools-Interactive-Staging)。
是否存在一种非交互式的方式来呈现大块内容?比如说,我有这些大块头:
$ git diff
diff --git a/test.txt b/test.txt
index 77e67ac..34eabb1 100644
--- a/test.txt
+++ b/test.txt
@@ -1,4 +1,4 @@
-this is the first change
+this is the first change, don't stage it!
@@ -6,5 +6,5 @@ this is the first change
-this is the first change
+this is the second change, stage it!
不通过交互菜单,运行像git add -p 2
这样的单个命令来执行第二大块会很好。
注意:这里提到了一个解决方案(如何在git中非交互式地处理块?),但它涉及多个命令和编辑补丁文件的额外步骤。
这在什么时候有用?说我正在编辑一个长而重复的JSON文件,在运行git diff
之后,我知道我想要阶段每一个其他块。我不想逐个讲解;我只是想告诉git"第二,第四,第六,第八等大块头"。
这在尝试使用自定义脚本与Sourcetree(它支持与hunks一起工作)交互时也很有用。
如果您能够手动或自动(例如,由于sed
)编辑补丁(由于git diff
生成的补丁),则可以使用以下命令非交互式地执行块:
git apply --cached patchfile
PS:我可以在这里找到你问题的答案:https://stackoverflow.com/a/31498768/7009806
这个答案更多的是为了练习和寻找解决方案的乐趣。我不太确定这是否真的适用于现实世界的情况。它还展示了如何在给定所需选项列表的情况下使用git add -p
的解决方案。
git add --patch
从stdin读取,因此您可以准备您的交互操作,例如,在一个文件中(为了本例的目的而称为/tmp/foo
),每一行都是您想要的动作,然后执行:
git add -p < /tmp/foo
下面是一个完整的例子:
我创建了一个文件,每行从0到100的数字,提交它并将0替换为a
。diff的开头看起来像这样:
diff --git a/my-file b/my-file
index 3b53b00..8f9a65c 100644
--- a/my-file
+++ b/my-file
@@ -1,4 +1,4 @@
-0
+a
1
2
3
@@ -8,7 +8,7 @@
7
8
9
-10
+1a
11
12
13
@@ -18,7 +18,7 @@
17
18
19
-20
+2a
21
22
23
@@ -28,7 +28,7 @@
27
28
29
-30
+3a
31
32
33
@@ -38,7 +38,7 @@
37
38
39
-40
+4a
41
42
43
现在,我想只进行一次更改,然后我创建我的foo
文件:
echo `y
n
y
n
y
n
y
n
y
n
y' > /tmp/foo
这个文件的创建可以自动,也可以不自动。
然后我运行它:
git add -p < /tmp/foo
and I get stage:
> git diff --cached
diff --git a/my-file b/my-file
index 3b53b00..00010f9 100644
--- a/my-file
+++ b/my-file
@@ -1,4 +1,4 @@
-0
+a
1
2
3
@@ -18,7 +18,7 @@
17
18
19
-20
+2a
21
22
23
@@ -38,7 +38,7 @@
37
38
39
-40
+4a
41
42
43
[.....]
和unstaged:
> git diff
diff --git a/my-file b/my-file
index 3b53b00..00010f9 100644
--- a/my-file
+++ b/my-file
@@ -1,4 +1,4 @@
-0
+a
1
2
3
@@ -18,7 +18,7 @@
17
18
19
-20
+2a
21
22
23
@@ -38,7 +38,7 @@
37
38
39
-40
+4a
41
42
43
[...]
另一种不使用文件的方法是:
echo 'y
n
y
n
y
n
y
n
y
n
y' | git add --patch