#!/bin/sh -e
#
# editlast - opens the last modified file in editor

editlast() {
  case "$(uname)" in
    Darwin)
      gnustat="gstat"
      stat_option='-f'
      stat_format='%m %N'
      ;;
    *)
      gnustat="stat"
      stat_option='-c'
      stat_format='%Y %n'
      ;;
  esac

  file=$(
    git ls-files --cached --other --exclude-standard "$@" -z \
      | xargs -0 "${gnustat}" "${stat_option}" "${stat_format}" \
      | sort -n | tail -1 | cut -d" " -f 2-
  )

  test "${file}" != '' \
    && ${EDITOR:-vi} "${file}"
}

if is-git-repo; then
  editlast "$@"
else
  printf '%s\n' "Not a git repository!" >&2
  exit 1
fi
