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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
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;