#!/bin/bash

log () {
  printf "[\033[1;37mpre-commit\033[0m] $1\n"
}

rustfmt +nightly --version &>/dev/null
if [ $? != 0 ]; then
    log "\033[0;33mWARN\033[0m: rustfmt +nightly not found, skipping pre-commit hook"
    exit 0
fi

files=()

for file in $(git diff --diff-filter=d --name-only --cached); do
    if [ ${file: -3} == ".rs" ]; then
        rustfmt +nightly --check $file &>/dev/null
        if [ $? != 0 ]; then
            files+=($file)
        fi
    fi
done

if [ -n "$files" ]; then
  log "the following files have improper formatting:\n"
  for file in "${files[@]}"; do
    printf "\033[0;33m\t$file\n"
  done
  printf "\n\033[0m"
  log "aborting commit"
  exit 1
fi

exit 0
