Skip to content

Instantly share code, notes, and snippets.

@sascha-wolf
Last active May 28, 2024 14:59
Show Gist options
  • Save sascha-wolf/c63ba089fd732a359e64d7a556964d8b to your computer and use it in GitHub Desktop.
Save sascha-wolf/c63ba089fd732a359e64d7a556964d8b to your computer and use it in GitHub Desktop.
Elixir pre-push hook for git - ensures files are formatted correctly and credo is satisfied
#!/bin/bash
ask() {
# https://djm.me/ask
local prompt default reply
while true; do
if [ "${2:-}" = "Y" ]; then
prompt="Y/n"
default=Y
elif [ "${2:-}" = "N" ]; then
prompt="y/N"
default=N
else
prompt="y/n"
default=
fi
# Ask the question (not using "read -p" as it uses stderr not stdout)
echo -n "$1 [$prompt] "
# Read the answer (use /dev/tty in case stdin is redirected from somewhere else)
read reply </dev/tty
# Default?
if [ -z "$reply" ]; then
reply=$default
fi
# Check if the reply is valid
case "$reply" in
Y*|y*) return 0 ;;
N*|n*) return 1 ;;
esac
done
}
format() {
echo "> mix format --check-formatted"
if mix format --check-formatted; then
echo "Everything formatted ✓"
else
ask "Format now?" Y &&
mix format &&
git commit -am 'Format: Run `mix format` on codebase'
fi
}
credo() {
if ask "Run credo?" Y; then
echo "> mix credo"
mix credo
fi
}
# Stash uncommited changes away, to ensure they don't interfere with the checks
old_stash=$(git rev-parse -q --verify refs/stash)
git stash push --keep-index --include-untracked --quiet
new_stash=$(git rev-parse -q --verify refs/stash)
EXIT_STATUS=0
format || EXIT_STATUS=$?
credo || EXIT_STATUS=$?
# Get uncommited changes back
[ "$old_stash" = "$new_stash" ] || git stash pop --index --quiet
if [ $EXIT_STATUS -ne 0 ]; then
ask "Some commands failed, abort push?" Y && exit $EXIT_STATUS
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment