summaryrefslogtreecommitdiffstats
path: root/gitlint/files/commit-msg
blob: e468290f31a13cb491ffdae259c4eee5c435d26f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/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 ###