Subject: [PATCH] diff: support --root --cached combination

From: Nguyễn Thái Ngọc Duy <[email-masked]>
Date: Fri, 29 Oct 2010 16:54:47 +0700

Signed-off-by: Nguyễn Thái Ngọc Duy <[email-masked]>
---
 I have a ritual of doing "git dic" (short for diff --cached) before
 committing and does not want to break it, even on new repos.

 Looks like a good thing and no harm to the rest of the world.

 builtin/diff.c              |    9 +++++++--
 t/t4046-diff-cached-root.sh |   31 +++++++++++++++++++++++++++++++
 2 files changed, 38 insertions(+), 2 deletions(-)
 create mode 100755 t/t4046-diff-cached-root.sh

diff --git a/builtin/diff.c b/builtin/diff.c
index a43d326..45be6f3 100644
--- a/builtin/diff.c
+++ b/builtin/diff.c
@@ -330,8 +330,13 @@ int cmd_diff(int argc, const char **argv, const char *prefix)
 			else if (!strcmp(arg, "--cached") ||
 				 !strcmp(arg, "--staged")) {
 				add_head_to_pending(&rev);
-				if (!rev.pending.nr)
-					die("No HEAD commit to compare with (yet)");
+				if (!rev.pending.nr) {
+					struct object *obj;
+					if (!rev.show_root_diff)
+						die("No HEAD commit to compare with (yet)");
+					obj = (struct object*)lookup_tree((unsigned char*)EMPTY_TREE_SHA1_BIN);
+					add_pending_object(&rev, obj, "HEAD");
+				}
 				break;
 			}
 		}
diff --git a/t/t4046-diff-cached-root.sh b/t/t4046-diff-cached-root.sh
new file mode 100755
index 0000000..82e3ad8
--- /dev/null
+++ b/t/t4046-diff-cached-root.sh
@@ -0,0 +1,31 @@
+#!/bin/sh
+
+test_description='git diff --cached --root test'
+
+. ./test-lib.sh
+
+test_expect_success 'setup' '
+	echo cached >file &&
+	git add file &&
+	echo not-cached >>file
+'
+
+test_expect_success 'diff --cached' '
+	test_must_fail git diff --cached
+'
+
+test_expect_success 'diff --cached --root' '
+	git diff --cached --root >result &&
+	cat >expected <<\EOF &&
+diff --git a/file b/file
+new file mode 100644
+index 0000000..ec9a961
+--- /dev/null
++++ b/file
+@@ -0,0 +1 @@
++cached
+EOF
+	test_cmp expected result
+'
+
+test_done
-- 
1.7.0.2.445.gcbdb3