#
# Common functionality
#

# shell output
warn() { echo "$@" >&2; }
die() { warn "$@"; exit 1; }

escape() {
	echo "$1" | sed 's/\([\.\+\$\*]\)/\\\1/g'
}

# set logic
has() {
	local item=$1; shift
	echo " $@ " | grep -q " $(escape $item) "
}

# basic math
min() { [ "$1" -le "$2" ] && echo "$1" || echo "$2"; }
max() { [ "$1" -ge "$2" ] && echo "$1" || echo "$2"; }

# basic string matching
startswith() { [ "$1" != "${1#$2}" ]; }
endswith() { [ "$1" != "${1%$2}" ]; }

# convenience functions for checking shFlags flags
flag() { local FLAG; eval FLAG='$FLAGS_'$1; [ $FLAG -eq $FLAGS_TRUE ]; }
noflag() { local FLAG; eval FLAG='$FLAGS_'$1; [ $FLAG -ne $FLAGS_TRUE ]; }

#
# Git specific common functionality
#

git_local_branches() { git branch --no-color | sed 's/^[* ] //'; }
git_remote_branches() { git branch -r --no-color | sed 's/^[* ] //'; }
git_all_branches() { ( git branch --no-color; git branch -r --no-color) | sed 's/^[* ] //'; }

git_current_branch() {
  git branch -l | grep "*" | cut -d " " -f 2
}

git_now_first_commit() {
  local common=$1
  if [ $# -eq 1 ]; then
    git log ${common}.. --pretty=oneline --grep="${PREFIX}" | tail -n 1 | cut -d " " -f 1
  else
    git log --pretty=oneline --grep="${PREFIX}" | tail -n 1 | cut -d " " -f 1
  fi
}

git_now_my_first_commit() {
  local author=$(escape `git config --get user.name`)
  local common=$1
  if [ $# -eq 1 ]; then
      git log ${common}.. --pretty=oneline --author=${author} --grep="${PREFIX}" | tail -n 1 | cut -d " " -f 1
  else
      git log --pretty=oneline --author=${author} --grep="${PREFIX}" | tail -n 1 | cut -d " " -f 1
  fi
}

git_now_initial_commit() { git log --pretty=oneline | tail -n 1 | cut -d " " -f 1; }

# vim: set ff=unix ft=sh
