#!/bin/sh ### gitlint commit-msg hook start ### # Determine whether we have a tty available by trying to access it. # This allows us to deal with UI based gitclient's like Atlassian SourceTree. # NOTE: "exec < /dev/tty" sets stdin to the keyboard stdin_available=1 (exec < /dev/tty) 2> /dev/null || stdin_available=0 if [ $stdin_available -eq 1 ]; then # Set bash color codes in case we have a tty RED="\033[31m" YELLOW="\033[33m" GREEN="\033[32m" END_COLOR="\033[0m" # Now that we know we have a functional tty, set stdin to it so we can ask the user questions :-) exec < /dev/tty else # Unset bash colors if we don't have a tty RED="" YELLOW="" GREEN="" END_COLOR="" fi run_gitlint(){ echo "gitlint: checking commit message..." python -m gitlint.cli --staged --msg-filename "$1" gitlint_exit_code=$? } # Prompts a given yes/no question. # Returns 0 if user answers yes, 1 if no # Reprompts if different answer ask_yes_no_edit(){ ask_yes_no_edit_result="no" # If we don't have a stdin available, then just return "No". if [ $stdin_available -eq 0 ]; then ask_yes_no_edit_result="no" return; fi # Otherwise, ask the question until the user answers yes or no question="$1" while true; do read -p "$question" yn case $yn in [Yy]* ) ask_yes_no_edit_result="yes"; return;; [Nn]* ) ask_yes_no_edit_result="no"; return;; [Ee]* ) ask_yes_no_edit_result="edit"; return;; esac done } run_gitlint "$1" while [ $gitlint_exit_code -gt 0 ]; do echo "-----------------------------------------------" echo "gitlint: ${RED}Your commit message contains the above violations.${END_COLOR}" ask_yes_no_edit "Continue with commit anyways (this keeps the current commit message)? [y(es)/n(no)/e(dit)] " if [ $ask_yes_no_edit_result = "yes" ]; then exit 0 elif [ $ask_yes_no_edit_result = "edit" ]; then EDITOR=${EDITOR:-vim} $EDITOR "$1" run_gitlint "$1" else echo "Commit aborted." echo "Your commit message: " echo "-----------------------------------------------" cat "$1" echo "-----------------------------------------------" exit $gitlint_exit_code fi done echo "gitlint: ${GREEN}OK${END_COLOR} (no violations in commit message)" exit 0 ### gitlint commit-msg hook end ###