Commit 41233c40c0e9cb8556a8ba131aa97a0ffbe46cb1

Vicent Marti 2011-04-08T12:42:18

Add new method `git_repository_is_empty`

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