Commit 787768c2d70dfcd1c9ebc1854b5d0f67d2e6d4d9

Edward Thomson 2018-06-22T19:07:54

index: return a unique error code on dirty index When the index is dirty, return GIT_EINDEXDIRTY so that consumers can identify the exact problem programatically.

diff --git a/include/git2/errors.h b/include/git2/errors.h
index 6f55802..00fbed1 100644
--- a/include/git2/errors.h
+++ b/include/git2/errors.h
@@ -55,6 +55,7 @@ typedef enum {
 	GIT_ITEROVER        = -31,	/**< Signals end of iteration with iterator */
 	GIT_RETRY           = -32,	/**< Internal only */
 	GIT_EMISMATCH       = -33,	/**< Hashsum mismatch in object */
+	GIT_EINDEXDIRTY     = -34,	/**< Unsaved changes in the index would be overwritten */
 } git_error_code;
 
 /**
diff --git a/src/index.c b/src/index.c
index de242ba..b8aa516 100644
--- a/src/index.c
+++ b/src/index.c
@@ -685,7 +685,7 @@ int git_index_read_safely(git_index *index)
 	if (index->dirty) {
 		giterr_set(GITERR_INDEX,
 			"the index has unsaved changes that would be overwritten by this operation");
-		return -1;
+		return GIT_EINDEXDIRTY;
 	}
 
 	return git_index_read(index, false);
diff --git a/tests/index/tests.c b/tests/index/tests.c
index c2e48c9..d7a1cc5 100644
--- a/tests/index/tests.c
+++ b/tests/index/tests.c
@@ -384,6 +384,28 @@ void test_index_tests__dirty_and_clean(void)
 	git_repository_free(repo);
 }
 
+void test_index_tests__dirty_fails_with_error(void)
+{
+	git_repository *repo;
+	git_index *index;
+	git_index_entry entry = {{0}};
+
+	/* Index is not dirty after opening */
+	repo = cl_git_sandbox_init("testrepo");
+	cl_git_pass(git_repository_index(&index, repo));
+
+	/* Index is dirty after adding an entry */
+	entry.mode = GIT_FILEMODE_BLOB;
+	entry.path = "test.txt";
+	cl_git_pass(git_index_add_frombuffer(index, &entry, "Hi.\n", 4));
+	cl_assert(git_index_is_dirty(index));
+
+	cl_git_fail_with(GIT_EINDEXDIRTY, git_checkout_head(repo, NULL));
+
+	git_index_free(index);
+	cl_git_sandbox_cleanup();
+}
+
 void test_index_tests__add_frombuffer_reset_entry(void)
 {
 	git_index *index;