Skip to content

Commit 787768c

Browse files
committed
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 parent 5e26391 commit 787768c

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

include/git2/errors.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ typedef enum {
5555
GIT_ITEROVER = -31, /**< Signals end of iteration with iterator */
5656
GIT_RETRY = -32, /**< Internal only */
5757
GIT_EMISMATCH = -33, /**< Hashsum mismatch in object */
58+
GIT_EINDEXDIRTY = -34, /**< Unsaved changes in the index would be overwritten */
5859
} git_error_code;
5960

6061
/**

src/index.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -685,7 +685,7 @@ int git_index_read_safely(git_index *index)
685685
if (index->dirty) {
686686
giterr_set(GITERR_INDEX,
687687
"the index has unsaved changes that would be overwritten by this operation");
688-
return -1;
688+
return GIT_EINDEXDIRTY;
689689
}
690690

691691
return git_index_read(index, false);

tests/index/tests.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,28 @@ void test_index_tests__dirty_and_clean(void)
384384
git_repository_free(repo);
385385
}
386386

387+
void test_index_tests__dirty_fails_with_error(void)
388+
{
389+
git_repository *repo;
390+
git_index *index;
391+
git_index_entry entry = {{0}};
392+
393+
/* Index is not dirty after opening */
394+
repo = cl_git_sandbox_init("testrepo");
395+
cl_git_pass(git_repository_index(&index, repo));
396+
397+
/* Index is dirty after adding an entry */
398+
entry.mode = GIT_FILEMODE_BLOB;
399+
entry.path = "test.txt";
400+
cl_git_pass(git_index_add_frombuffer(index, &entry, "Hi.\n", 4));
401+
cl_assert(git_index_is_dirty(index));
402+
403+
cl_git_fail_with(GIT_EINDEXDIRTY, git_checkout_head(repo, NULL));
404+
405+
git_index_free(index);
406+
cl_git_sandbox_cleanup();
407+
}
408+
387409
void test_index_tests__add_frombuffer_reset_entry(void)
388410
{
389411
git_index *index;

0 commit comments

Comments
 (0)