Commit e3f065eae40ae56c374410ed4c73e6d7e1b80ad7

Edward Thomson 2020-07-15T22:13:47

remote: update the default remote branch When the remote does not tell us its default, we have to guess what the default branch should be. Use our local initial branch configuration to inform the remote branch default when we clone.

diff --git a/src/remote.c b/src/remote.c
index 23054c8..51e99dc 100644
--- a/src/remote.c
+++ b/src/remote.c
@@ -2375,29 +2375,36 @@ int git_remote_default_branch(git_buf *out, git_remote *remote)
 	const git_remote_head *guess = NULL;
 	const git_oid *head_id;
 	size_t heads_len, i;
+	git_buf local_default = GIT_BUF_INIT;
 	int error;
 
 	assert(out);
 
 	if ((error = git_remote_ls(&heads, &heads_len, remote)) < 0)
-		return error;
-
-	if (heads_len == 0)
-		return GIT_ENOTFOUND;
+		goto done;
 
-	if (strcmp(heads[0]->name, GIT_HEAD_FILE))
-		return GIT_ENOTFOUND;
+	if (heads_len == 0 || strcmp(heads[0]->name, GIT_HEAD_FILE)) {
+		error = GIT_ENOTFOUND;
+		goto done;
+	}
 
 	git_buf_sanitize(out);
+
 	/* the first one must be HEAD so if that has the symref info, we're done */
-	if (heads[0]->symref_target)
-		return git_buf_puts(out, heads[0]->symref_target);
+	if (heads[0]->symref_target) {
+		error = git_buf_puts(out, heads[0]->symref_target);
+		goto done;
+	}
 
 	/*
 	 * If there's no symref information, we have to look over them
-	 * and guess. We return the first match unless the master
-	 * branch is a candidate. Then we return the master branch.
+	 * and guess. We return the first match unless the default
+	 * branch is a candidate. Then we return the default branch.
 	 */
+
+	if ((error = git_repository_initialbranch(&local_default, remote->repo)) < 0)
+		goto done;
+
 	head_id = &heads[0]->oid;
 
 	for (i = 1; i < heads_len; i++) {
@@ -2412,16 +2419,22 @@ int git_remote_default_branch(git_buf *out, git_remote *remote)
 			continue;
 		}
 
-		if (!git__strcmp(GIT_REFS_HEADS_MASTER_FILE, heads[i]->name)) {
+		if (!git__strcmp(local_default.ptr, heads[i]->name)) {
 			guess = heads[i];
 			break;
 		}
 	}
 
-	if (!guess)
-		return GIT_ENOTFOUND;
+	if (!guess) {
+		error = GIT_ENOTFOUND;
+		goto done;
+	}
+
+	error = git_buf_puts(out, guess->name);
 
-	return git_buf_puts(out, guess->name);
+done:
+	git_buf_dispose(&local_default);
+	return error;
 }
 
 int git_remote_upload(git_remote *remote, const git_strarray *refspecs, const git_push_options *opts)