From 908fdd0fa3b64f79ca91df20aa7608e8ca34d72a Mon Sep 17 00:00:00 2001 From: ElisarEisenbach Date: Sun, 13 Jul 2025 18:03:29 +0300 Subject: [PATCH] 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. --- plugins/git/git.plugin.zsh | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/plugins/git/git.plugin.zsh b/plugins/git/git.plugin.zsh index ca2753e0b..bb2583205 100644 --- a/plugins/git/git.plugin.zsh +++ b/plugins/git/git.plugin.zsh @@ -31,25 +31,29 @@ function git_develop_branch() { 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 - - local ref - ref=$(git symbolic-ref --quiet refs/remotes/origin/HEAD 2>/dev/null) - if [[ $? -eq 0 && -n "$ref" ]]; then - echo "${ref##*/}" - return - fi - - # 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 + + local remote ref + for remote in origin upstream; do + ref=$(command git symbolic-ref --quiet refs/remotes/$remote/HEAD 2>/dev/null) + if [[ -n $ref ]]; then + echo ${ref#refs/remotes/$remote/} + return 0 + fi + done + + # 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 - echo "master" # Default fallback + # If no main branch was found, fall back to master but return error + echo master return 1 } @@ -433,4 +437,4 @@ for old_alias new_alias ( print -Pu2 \"%F{yellow}[oh-my-zsh] '%F{red}${old_alias}%F{yellow}' is a deprecated alias, using '%F{green}${new_alias}%F{yellow}' instead.%f\" $new_alias" done -unset old_alias new_alias +unset old_alias new_alias \ No newline at end of file