Add new method `git_repository_is_empty`
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
diff --git a/include/git2/repository.h b/include/git2/repository.h
index 00c1f20..200f350 100644
--- a/include/git2/repository.h
+++ b/include/git2/repository.h
@@ -182,6 +182,18 @@ GIT_EXTERN(void) git_repository_free(git_repository *repo);
*/
GIT_EXTERN(int) git_repository_init(git_repository **repo_out, const char *path, unsigned is_bare);
+/**
+ * Check if a repository is empty
+ *
+ * An empty repository has just been initialized and contains
+ * no commits.
+ *
+ * @param repo Repo to test
+ * @return 1 if the repository is empty, 0 if it isn't, error code
+ * if the repository is corrupted
+ */
+GIT_EXTERN(int) git_repository_is_empty(git_repository *repo);
+
/** @} */
GIT_END_DECL
#endif
diff --git a/src/repository.c b/src/repository.c
index abbbd12..471c024 100644
--- a/src/repository.c
+++ b/src/repository.c
@@ -473,3 +473,18 @@ cleanup:
return error;
}
+int git_repository_is_empty(git_repository *repo)
+{
+ git_reference *head, *branch;
+ int error;
+
+ error = git_reference_lookup(&head, repo, "HEAD");
+ if (error < GIT_SUCCESS)
+ return error;
+
+ if (git_reference_type(head) != GIT_REF_SYMBOLIC)
+ return GIT_EOBJCORRUPTED;
+
+ return git_reference_resolve(&branch, head) == GIT_SUCCESS ? 0 : 1;
+}
+
diff --git a/tests/t12-repo.c b/tests/t12-repo.c
index adf20cf..876f0c5 100644
--- a/tests/t12-repo.c
+++ b/tests/t12-repo.c
@@ -244,6 +244,19 @@ BEGIN_TEST(open2, "Open a bare repository with a relative path escaping out of t
rmdir_recurs(TEMP_REPO_FOLDER);
END_TEST
+BEGIN_TEST(empty0, "test if a repository is empty or not")
+
+ git_repository *repo_empty, *repo_normal;
+
+ must_pass(git_repository_open(&repo_normal, REPOSITORY_FOLDER));
+ must_be_true(git_repository_is_empty(repo_normal) == 0);
+ git_repository_free(repo_normal);
+
+ must_pass(git_repository_open(&repo_empty, EMPTY_BARE_REPOSITORY_FOLDER));
+ must_be_true(git_repository_is_empty(repo_empty) == 1);
+ git_repository_free(repo_empty);
+END_TEST
+
BEGIN_SUITE(repository)
ADD_TEST(odb0);
ADD_TEST(odb1);
@@ -253,5 +266,6 @@ BEGIN_SUITE(repository)
ADD_TEST(open0);
ADD_TEST(open1);
ADD_TEST(open2);
+ ADD_TEST(empty0);
END_SUITE