refactor(git): enhance git_main_branch function for better default branch detection

Updated the `git_main_branch` function to first check for the default branch using `git symbolic-ref` for both `origin` and `upstream`. If no symbolic reference is found, it now searches for common branch names in a more structured way. The function retains a fallback to "master" while returning an error if no main branch is found, improving reliability and compatibility.
This commit is contained in:
ElisarEisenbach 2025-07-13 18:03:29 +03:00
commit 908fdd0fa3

View file

@ -31,25 +31,29 @@ function git_develop_branch() {
return 1 return 1
} }
unction git_main_branch() { # Get the default branch name from remote HEAD or fallback to common branch names
function git_main_branch() {
command git rev-parse --git-dir &>/dev/null || return command git rev-parse --git-dir &>/dev/null || return
local ref local remote ref
ref=$(git symbolic-ref --quiet refs/remotes/origin/HEAD 2>/dev/null) for remote in origin upstream; do
if [[ $? -eq 0 && -n "$ref" ]]; then ref=$(command git symbolic-ref --quiet refs/remotes/$remote/HEAD 2>/dev/null)
echo "${ref##*/}" if [[ -n $ref ]]; then
return echo ${ref#refs/remotes/$remote/}
fi return 0
# Fallback if origin/HEAD is not set
for branch in main master trunk default stable; do
if git show-ref -q --verify "refs/heads/$branch"; then
echo "$branch"
return
fi fi
done done
echo "master" # Default fallback # Fallback: search for common main branch names in order of preference
for ref in refs/{heads,remotes/{origin,upstream}}/{main,trunk,mainline,default,stable,master}; do
if command git show-ref -q --verify $ref; then
echo ${ref:t}
return 0
fi
done
# If no main branch was found, fall back to master but return error
echo master
return 1 return 1
} }