#!/bin/sh
#
# git-branch-by-date - list branches in reverse chronological order
#
# usage:
#     "git-branch-by-date [ remote ]"
#
# by default local branches are listed and the committer name is omitted
#     -r : list remote branches with committer name
#
# for use in git config as subcommand:
# git config --global alias.branch-by-date '!~/git-utils/git-branch-by-date'

set -e

flag="$1"
no_table="$2"

set -u

format='%(refname)@%(committerdate:relative)'

if [ -n "${flag}" ] && "$(git remote | grep -q "${flag}")"; then
  refs=refs/remotes/${flag}
  if [ "${flag}" = "origin" ]; then
    format='%(refname)@%(committername)@%(committerdate:relative)'
  fi
else
  refs=refs/heads
fi

branch_by_date() {
  git for-each-ref --sort=-committerdate "${refs}" --format="${format}" \
    | sed "s,^${refs}/,,"
}

if [ -n "${no_table}" ]; then
  branch_by_date
else
  branch_by_date | sed 's/,,/, ,/g;s/,,/, ,/g' "$@" | column -s, -t | less -XF
fi
