Skip to content

Commit 4cc3b2c

Browse files
committed
repo: add git_repository_initialbranch
Provide a helper function to get the initial branch for a repository, respecting the `init.defaultBranch` configuration option, if set, and returning the "default default" (currently `master`) otherwise.
1 parent e411aae commit 4cc3b2c

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/repository.c

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2354,6 +2354,40 @@ static int repo_contains_no_reference(git_repository *repo)
23542354
return error;
23552355
}
23562356

2357+
int git_repository_initialbranch(git_buf *out, git_repository *repo)
2358+
{
2359+
git_config *config;
2360+
git_config_entry *entry = NULL;
2361+
const char *branch;
2362+
int error;
2363+
2364+
if ((error = git_repository_config__weakptr(&config, repo)) < 0)
2365+
return error;
2366+
2367+
if ((error = git_config_get_entry(&entry, config, "init.defaultbranch")) == 0) {
2368+
branch = entry->value;
2369+
}
2370+
else if (error == GIT_ENOTFOUND) {
2371+
branch = GIT_BRANCH_DEFAULT;
2372+
}
2373+
else {
2374+
goto done;
2375+
}
2376+
2377+
if ((error = git_buf_puts(out, GIT_REFS_HEADS_DIR)) < 0 ||
2378+
(error = git_buf_puts(out, branch)) < 0)
2379+
goto done;
2380+
2381+
if (!git_reference_is_valid_name(out->ptr)) {
2382+
git_error_set(GIT_ERROR_INVALID, "the value of init.defaultBranch is not a valid reference name");
2383+
error = -1;
2384+
}
2385+
2386+
done:
2387+
git_config_entry_free(entry);
2388+
return error;
2389+
}
2390+
23572391
int git_repository_is_empty(git_repository *repo)
23582392
{
23592393
git_reference *head = NULL;

src/repository.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,4 +232,10 @@ extern size_t git_repository__reserved_names_posix_len;
232232
bool git_repository__reserved_names(
233233
git_buf **out, size_t *outlen, git_repository *repo, bool include_ntfs);
234234

235+
/*
236+
* The default branch for the repository; the `init.defaultBranch`
237+
* configuration option, if set, or `master` if it is not.
238+
*/
239+
int git_repository_initialbranch(git_buf *out, git_repository *repo);
240+
235241
#endif

0 commit comments

Comments
 (0)