#!/bin/bash

# This file has been floating around in my development environment for years,
# but I have no idea of the source, and searching found nothing.
# Regularly useful, nice use of color.

usage() {
    cat <<EOF
git when:
    For each file, show the most recent commit that changed it.

    Dotfiles are ignored by default.

USAGE
    git when [-a] [item [..item]]

Optional arguments
    -a    Also include dotfiles

EOF
}

while getopts ":h" opt; do
  case $opt in
    h)
      usage ; exit ; ;;
  esac
done

dotfiles=0

if [ "$1" = "-a" ]; then
    shift
    dotfiles=1
fi

if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
    git rev-parse --is-inside-work-tree
    exit 1
fi

Cgreen='\033[0;32m'
Cred='\033[0;31m'
Cgrey='\033[0;37m'
Creset='\033[0m'

FORMAT="\
%C(bold green)\
%<(20)\
%ar\
%C(reset)\
%C(bold blue)\
%h\
%C(reset)\
%n\
%C(yellow)\
%s\
%C(reset)"

# %ar: author date, relative
# %h: abbreviated commit hash
# %n: newline
# %s: subject

if [ "$dotfiles" -eq 1 ]; then
    shopt -s dotglob
fi

if [ "$#" -ne 0 ]; then
    files=$@
else
    files=*
fi

for file in $files; do
    if [ "$file" = ".git" ]; then
        continue
    fi

    printf "%-20s\t" "$file"

    status="$(git status --porcelain "$file")"

    if [[ "$status" == "??"* ]]; then
        echo -en "${Cred}Untracked$Creset"

    elif [[ "$status" == "A"* ]]; then
        echo -en "${Cgreen}Staged$Creset"

    elif git check-ignore "$file" > /dev/null; then
        echo -en "${Cgrey}Gitignored$Creset"

    else
        git log -1 --color=always --pretty=format:"$FORMAT" "$file" \
            | tr "\n" "\t"
    fi

    echo
done
