Commit eb095435f338b97f305148e122d6e12fd81621ca

Justin Love 2010-11-30T21:28:39

add git_commit_parent to retrieve a parent by index

diff --git a/src/commit.c b/src/commit.c
index b8d9f87..8af92bf 100644
--- a/src/commit.c
+++ b/src/commit.c
@@ -272,6 +272,20 @@ unsigned int git_commit_parentcount(git_commit *commit)
 	return count;
 }
 
+git_commit * git_commit_parent(git_commit *commit, unsigned int n)
+{
+	git_commit_parents *parent;
+
+	assert(commit);
+	CHECK_FULL_PARSE();
+
+	for (parent = commit->parents; parent != NULL && n > 0; parent = parent->next) {
+		n--;
+	}
+
+	return parent ? parent->commit : NULL;
+}
+
 void git_commit_set_tree(git_commit *commit, git_tree *tree)
 {
 	assert(commit && tree);
diff --git a/src/git/commit.h b/src/git/commit.h
index cc4e7a0..70b08e9 100644
--- a/src/git/commit.h
+++ b/src/git/commit.h
@@ -102,6 +102,14 @@ GIT_EXTERN(const git_tree *) git_commit_tree(git_commit *commit);
 GIT_EXTERN(unsigned int) git_commit_parentcount(git_commit *commit);
 
 /**
+ * Get the specified parent of the commit.
+ * @param commit a previously loaded commit.
+ * @param n the position of the entry
+ * @return a pointer to the commit; NULL if out of bounds
+ */
+GIT_EXTERN(git_commit *) git_commit_parent(git_commit *commit, unsigned int n);
+
+/**
  * Add a new parent commit to an existing commit
  * @param commit the commit object
  * @param new_parent the new commit which will be a parent
diff --git a/tests/t0402-details.c b/tests/t0402-details.c
index 65a3492..a01a708 100644
--- a/tests/t0402-details.c
+++ b/tests/t0402-details.c
@@ -31,7 +31,8 @@ BEGIN_TEST(query_details_test)
 		const git_person *author, *committer;
 		const char *message, *message_short;
 		time_t commit_time;
-		unsigned int parents;
+		unsigned int parents, p;
+		git_commit *parent;
 
 		git_oid_mkstr(&id, commit_ids[i]);
 
@@ -52,6 +53,12 @@ BEGIN_TEST(query_details_test)
 		must_be_true(strchr(message_short, '\n') == NULL);
 		must_be_true(commit_time > 0);
 		must_be_true(0 <= parents && parents <= 2);
+		for (p = 0;p < parents;p++) {
+			parent = git_commit_parent(commit, p);
+			must_be_true(parent != NULL);
+			must_be_true(git_commit_author(parent) != NULL); // is it really a commit?
+		}
+		must_be_true(git_commit_parent(commit, parents) == NULL);
 	}
 
 	git_repository_free(repo);