#!/usr/bin/env bash
#
# branchname - print current branchname, including during rebase
#
# https://stackoverflow.com/questions/34213120/find-branch-name-during-git-rebase

set -e

branchname=$(git bn)
if [ "$branchname" = "HEAD" ]; then
  branchoutput=$(git branch --list | grep rebasing)
  if [ ! $? -eq 0 ]; then
    exit 1
  fi

  regex="rebasing ([^)]+)\)"
  if [[ $branchoutput =~ $regex ]]; then
    branchname="${BASH_REMATCH[1]}"
  else
    exit 2
  fi
fi

printf $branchname