Commit 82374d9825040914a3cfd8ceeaf60f76b93fe638

Carlos Martín Nieto 2014-11-08T20:00:17

branch: add getter for the upstream remote name This gets the value from branch.<foo>.remote.

diff --git a/include/git2/branch.h b/include/git2/branch.h
index f284100..8887810 100644
--- a/include/git2/branch.h
+++ b/include/git2/branch.h
@@ -260,6 +260,17 @@ GIT_EXTERN(int) git_branch_remote_name(
 	git_repository *repo,
 	const char *canonical_branch_name);
 
+
+/**
+ * Retrieve the name fo the upstream remote of a local branch
+ *
+ * @param buf the buffer into which to write the name
+ * @param repo the repository in which to look
+ * @param refname the full name of the branch
+ * @return 0 or an error code
+ */
+ GIT_EXTERN(int) git_branch_upstream_remote(git_buf *buf, git_repository *repo, const char *refname);
+
 /** @} */
 GIT_END_DECL
 #endif
diff --git a/src/branch.c b/src/branch.c
index 5276085..c24904a 100644
--- a/src/branch.c
+++ b/src/branch.c
@@ -384,6 +384,29 @@ cleanup:
 	return error;
 }
 
+int git_branch_upstream_remote(git_buf *buf, git_repository *repo, const char *refname)
+{
+	int error;
+	const char *str;
+	git_config *cfg;
+
+	if (!git_reference__is_branch(refname))
+		return not_a_local_branch(refname);
+
+	git_buf_sanitize(buf);
+	if ((error = git_repository_config_snapshot(&cfg, repo)) < 0)
+		return error;
+
+	if ((error = retrieve_upstream_configuration(&str, cfg, refname, "branch.%s.remote")) < 0)
+		goto cleanup;
+
+	error = git_buf_puts(buf, str);
+
+cleanup:
+	git_config_free(cfg);
+	return error;
+}
+
 int git_branch_remote_name(git_buf *buf, git_repository *repo, const char *refname)
 {
 	git_strarray remote_list = {0};
diff --git a/tests/refs/branches/upstream.c b/tests/refs/branches/upstream.c
index ce35698..abf7933 100644
--- a/tests/refs/branches/upstream.c
+++ b/tests/refs/branches/upstream.c
@@ -61,6 +61,15 @@ void test_refs_branches_upstream__trying_to_retrieve_a_remote_tracking_reference
 	cl_assert_equal_i(GIT_ENOTFOUND, git_branch_upstream(&upstream, branch));
 }
 
+void test_refs_branches_upstream__upstream_remote(void)
+{
+	git_buf buf = GIT_BUF_INIT;
+
+	cl_git_pass(git_branch_upstream_remote(&buf, repo, "refs/heads/master"));
+	cl_assert_equal_s("test", buf.ptr);
+	git_buf_free(&buf);
+}
+
 static void assert_merge_and_or_remote_key_missing(git_repository *repository, const git_commit *target, const char *entry_name)
 {
 	git_reference *branch;