Skip to content

Commit

Permalink
add get-git-(active|default)-branch
Browse files Browse the repository at this point in the history
  • Loading branch information
balupton committed Nov 11, 2023
1 parent 916be66 commit 0d76d23
Show file tree
Hide file tree
Showing 2 changed files with 109 additions and 0 deletions.
44 changes: 44 additions & 0 deletions commands/get-git-active-branch
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env bash

function get_git_active_branch() (
source "$DOROTHY/sources/bash.bash"

# =====================================
# Arguments

function help {
cat <<-EOF >/dev/stderr
ABOUT:
Get the active branch of the local repository.
USAGE:
get-git-active-branch
EOF
if test "$#" -ne 0; then
echo-error "$@"
fi
return 22 # EINVAL 22 Invalid argument
}

# process
local item
while test "$#" -ne 0; do
item="$1"
shift
case "$item" in
'--help' | '-h') help ;;
'--'*) help "An unrecognised flag was provided: $item" ;;
*) help "An unrecognised argument was provided: $item" ;;
esac
done

# =======================================================
# Action

git rev-parse --abbrev-ref HEAD
)

# fire if invoked standalone
if test "$0" = "${BASH_SOURCE[0]}"; then
get_git_active_branch "$@"
fi
65 changes: 65 additions & 0 deletions commands/get-git-default-branch
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#!/usr/bin/env bash

function get_git_default_branch() (
source "$DOROTHY/sources/bash.bash"

# =====================================
# Arguments

function help {
cat <<-EOF >/dev/stderr
ABOUT:
Get the default branch of the local repository.
USAGE:
get-git-default-branch
EOF
if test "$#" -ne 0; then
echo-error "$@"
fi
return 22 # EINVAL 22 Invalid argument
}

# process
local item
while test "$#" -ne 0; do
item="$1"
shift
case "$item" in
'--help' | '-h') help ;;
'--'*) help "An unrecognised flag was provided: $item" ;;
*) help "An unrecognised argument was provided: $item" ;;
esac
done

# =======================================================
# Action

function branch_exists {
local branch="$1"
git rev-parse --abbrev-ref "$branch" &>/dev/null
return
}

local default_local default_global
default_local="$(git config init.defaultBranch 2>/dev/null || :)"
default_global="$(git config --global init.defaultBranch 2>/dev/null || :)"

if test -n "$default_local" && branch_exists "$default_local"; then
print_line "$default_local"
elif test -n "$default_global" && branch_exists "$default_global"; then
print_line "$default_global"
elif branch_exists 'main'; then
print_line 'main'
elif branch_exists 'master'; then
print_line 'master'
else
echo-error 'Unable to determine the default branch.'
return 1
fi
)

# fire if invoked standalone
if test "$0" = "${BASH_SOURCE[0]}"; then
get_git_default_branch "$@"
fi

0 comments on commit 0d76d23

Please sign in to comment.