Commit 471ed794d8bc8ce783964eda180c21234b2fe591

Edward Thomson 2020-07-13T10:05:04

clone: respect init.defaultBranch when empty When cloning an empty repository, we need to guess what the branch structure should be; instead of hardcoding `master`, use the `init.defaultBranch` setting it if it provided.

diff --git a/src/clone.c b/src/clone.c
index 8ca6cea..9214fa9 100644
--- a/src/clone.c
+++ b/src/clone.c
@@ -137,6 +137,31 @@ static int update_head_to_new_branch(
 	return error;
 }
 
+static int update_head_to_default(git_repository *repo)
+{
+	git_buf initialbranch = GIT_BUF_INIT;
+	const char *branch_name;
+	int error = 0;
+
+	if ((error = git_repository_initialbranch(&initialbranch, repo)) < 0)
+		goto done;
+
+	if (git__prefixcmp(initialbranch.ptr, GIT_REFS_HEADS_DIR) != 0) {
+		git_error_set(GIT_ERROR_INVALID, "invalid initial branch '%s'", initialbranch.ptr);
+		error = -1;
+		goto done;
+	}
+
+	branch_name = initialbranch.ptr + strlen(GIT_REFS_HEADS_DIR);
+
+	error = setup_tracking_config(repo, branch_name, GIT_REMOTE_ORIGIN,
+		initialbranch.ptr);
+
+done:
+	git_buf_dispose(&initialbranch);
+	return error;
+}
+
 static int update_head_to_remote(
 		git_repository *repo,
 		git_remote *remote,
@@ -155,8 +180,7 @@ static int update_head_to_remote(
 
 	/* We cloned an empty repository or one with an unborn HEAD */
 	if (refs_len == 0 || strcmp(refs[0]->name, GIT_HEAD_FILE))
-		return setup_tracking_config(
-			repo, "master", GIT_REMOTE_ORIGIN, GIT_REFS_HEADS_MASTER_FILE);
+		return update_head_to_default(repo);
 
 	/* We know we have HEAD, let's see where it points */
 	remote_head = refs[0];
diff --git a/tests/clone/empty.c b/tests/clone/empty.c
index 8e59d2b..94847bc 100644
--- a/tests/clone/empty.c
+++ b/tests/clone/empty.c
@@ -2,6 +2,7 @@
 
 #include "git2/clone.h"
 #include "repository.h"
+#include "repo/repo_helpers.h"
 
 static git_clone_options g_options;
 static git_repository *g_repo;
@@ -22,6 +23,7 @@ void test_clone_empty__initialize(void)
 
 void test_clone_empty__cleanup(void)
 {
+	cl_fixture_cleanup("tmp_global_path");
 	cl_git_sandbox_cleanup();
 }
 
@@ -66,6 +68,21 @@ void test_clone_empty__can_clone_an_empty_local_repo_barely(void)
 		expected_tracked_branch_name));
 }
 
+void test_clone_empty__respects_initialbranch_config(void)
+{
+	git_buf buf = GIT_BUF_INIT;
+
+	create_tmp_global_config("tmp_global_path", "init.defaultbranch", "my_default_branch");
+
+	cl_set_cleanup(&cleanup_repository, "./empty");
+
+	g_options.bare = true;
+	cl_git_pass(git_clone(&g_repo_cloned, "./empty_bare.git", "./empty", &g_options));
+	cl_git_pass(git_branch_upstream_name(&buf, g_repo_cloned, "refs/heads/my_default_branch"));
+	cl_assert_equal_s("refs/remotes/origin/my_default_branch", buf.ptr);
+	git_buf_dispose(&buf);
+}
+
 void test_clone_empty__can_clone_an_empty_local_repo(void)
 {
 	cl_set_cleanup(&cleanup_repository, "./empty");