以下操作可以让你实现大部分需求:
$ clean=`git diff --cached -b`; \
git apply --cached <(git diff --cached -R); \
echo "$clean" | git apply --cached -; \
clean=
对于早期版本的git(1.7.0之前),如果一个或多个文件发生了全空格更改,此方法将无法成功。例如:
$ git diff --cached -b
diff --git a/file1 b/file1
index b2bd1a5..3b18e51 100644
diff --git a/file2 b/file2
new file mode 100644
index 0000000..092bfb9
--- /dev/null
+++ b/file2
[...]
上面的示例中,
file1
的空差异(实际上应该被忽略)会使
git-apply
产生错误:
fatal: patch with only garbage at line 3
更新:git 1.7.0版本
已修复此问题。
假设我们的代码库处于以下状态:
$ git diff --cached
diff --git a/foo b/foo
index 3b18e51..a75018e 100644
--- a/foo
+++ b/foo
@@ -1 +1,2 @@
-hello world
+hello world
+howdy also
我们可以运行以上命令来分叉索引和工作树:
$ git diff --cached
diff --git a/foo b/foo
index 3b18e51..1715a9b 100644
--- a/foo
+++ b/foo
@@ -1 +1,2 @@
hello world
+howdy also
$ git diff
diff --git a/foo b/foo
index 1715a9b..a75018e 100644
--- a/foo
+++ b/foo
@@ -1,2 +1,2 @@
-hello world
+hello world
howdy also
如果所有更改都是只包含空格,则会看到以下内容:
error: No changes
我怀疑修复索引并在工作树中保留不需要的更改将使大多数用户感到惊讶或甚至不满,但这正是问题所要求的行为。