refactor(git): improve default branch detection in git_main_branch function

Reorganized the `git_main_branch` function to first attempt to retrieve the default branch from remote HEAD symbolic refs for both `origin` and `upstream`. This change enhances the reliability of branch detection by prioritizing symbolic references before falling back to common branch names. The function still defaults to "master" if no main branch is found, maintaining backward compatibility.
This commit is contained in:
ElisarEisenbach 2025-07-14 10:47:03 +03:00
commit 86977d2bdf

View file

@ -36,18 +36,19 @@ function git_main_branch() {
command git rev-parse --git-dir &>/dev/null || return command git rev-parse --git-dir &>/dev/null || return
local remote ref local remote ref
for remote in origin upstream; do
ref=$(command git symbolic-ref --quiet refs/remotes/$remote/HEAD 2>/dev/null) for ref in refs/{heads,remotes/{origin,upstream}}/{main,trunk,mainline,default,stable,master}; do
if [[ -n $ref ]]; then if command git show-ref -q --verify $ref; then
echo ${ref#refs/remotes/$remote/} echo ${ref:t}
return 0 return 0
fi fi
done done
# Fallback: search for common main branch names in order of preference # Fallback: try to get the default branch from remote HEAD symbolic refs
for ref in refs/{heads,remotes/{origin,upstream}}/{main,trunk,mainline,default,stable,master}; do for remote in origin upstream; do
if command git show-ref -q --verify $ref; then ref=$(command git symbolic-ref --quiet refs/remotes/$remote/HEAD 2>/dev/null)
echo ${ref:t} if [[ -n $ref ]]; then
echo ${ref#refs/remotes/$remote/}
return 0 return 0
fi fi
done done