Commit eed378b66960414942ac78840afbcb19bfffbf15

nulltoken 2012-07-20T16:19:04

branch: introduce git_branch_lookup()

diff --git a/include/git2/branch.h b/include/git2/branch.h
index 7442ece..fb30aaa 100644
--- a/include/git2/branch.h
+++ b/include/git2/branch.h
@@ -117,6 +117,30 @@ GIT_EXTERN(int) git_branch_move(
 		const char *new_branch_name,
 		int force);
 
+/**
+ * Lookup a branch by its name in a repository.
+ *
+ * The generated reference must be freed by the user.
+ *
+ * @param branch_out pointer to the looked-up branch reference
+ *
+ * @param repo the repository to look up the branch
+ *
+ * @param branch_name Name of the branch to be looked-up;
+ * this name is validated for consistency.
+ *
+ * @param branch_type Type of the considered branch. This should
+ * be valued with either GIT_BRANCH_LOCAL or GIT_BRANCH_REMOTE.
+ *
+ * @return 0 on success; GIT_ENOTFOUND when no matching branch
+ * exists, otherwise an error code.
+ */
+GIT_EXTERN(int) git_branch_lookup(
+		git_reference **branch_out,
+		git_repository *repo,
+		const char *branch_name,
+		git_branch_t branch_type);
+
 /** @} */
 GIT_END_DECL
 #endif
diff --git a/src/branch.c b/src/branch.c
index 789f52b..f0945b6 100644
--- a/src/branch.c
+++ b/src/branch.c
@@ -205,3 +205,14 @@ cleanup:
 
 	return error;
 }
+
+int git_branch_lookup(
+		git_reference **ref_out,
+		git_repository *repo,
+		const char *branch_name,
+		git_branch_t branch_type)
+{
+	assert(ref_out && repo && branch_name);
+
+	return retrieve_branch_reference(ref_out, repo, branch_name, branch_type == GIT_BRANCH_REMOTE);
+}
diff --git a/tests-clar/refs/branches/lookup.c b/tests-clar/refs/branches/lookup.c
new file mode 100644
index 0000000..2aabf98
--- /dev/null
+++ b/tests-clar/refs/branches/lookup.c
@@ -0,0 +1,35 @@
+#include "clar_libgit2.h"
+#include "refs.h"
+
+static git_repository *repo;
+static git_reference *branch;
+
+void test_refs_branches_lookup__initialize(void)
+{
+	cl_git_pass(git_repository_open(&repo, cl_fixture("testrepo.git")));
+
+	branch = NULL;
+}
+
+void test_refs_branches_lookup__cleanup(void)
+{
+	git_reference_free(branch);
+
+	git_repository_free(repo);
+}
+
+void test_refs_branches_lookup__can_retrieve_a_local_branch(void)
+{
+	cl_git_pass(git_branch_lookup(&branch, repo, "br2", GIT_BRANCH_LOCAL));
+}
+
+void test_refs_branches_lookup__can_retrieve_a_remote_tracking_branch(void)
+{
+	cl_git_pass(git_branch_lookup(&branch, repo, "test/master", GIT_BRANCH_REMOTE));
+}
+
+void test_refs_branches_lookup__trying_to_retrieve_an_unknown_branch_returns_ENOTFOUND(void)
+{
+	cl_assert_equal_i(GIT_ENOTFOUND, git_branch_lookup(&branch, repo, "where/are/you", GIT_BRANCH_LOCAL));
+	cl_assert_equal_i(GIT_ENOTFOUND, git_branch_lookup(&branch, repo, "over/here", GIT_BRANCH_REMOTE));
+}