#!/bin/sh
# Checks a commit message against the format described in CONTRIBUTING:
# summary style and length, blank line after it, trailer syntax and body line
# width. Git-generated subjects (fixup!, squash!, amend!, Merge) are
# not checked.
#
# Usage: check-commit-message FILE
#
# FILE `-` reads standard input. Comment lines and everything after the
# scissors line are ignored, as git does when cleaning up a message. Problems
# are printed on standard error and make the exit status 1.

if [ $# -ne 1 ]; then
    echo "usage: check-commit-message FILE" >&2
    exit 2
fi
msg=$1
if [ "$msg" != - ] && [ ! -f "$msg" ]; then
    echo "check-commit-message: $msg: no such file" >&2
    exit 2
fi

cc=$(git config core.commentChar 2>/dev/null)
case $cc in
    '' | auto) cc='#' ;;
esac

[ "$msg" = - ] && msg=/dev/stdin

problems=$(COMMENT_CHAR=$cc awk '
    BEGIN { cc = ENVIRON["COMMENT_CHAR"]; n = 0 }

    # Mimic git cleanup: drop comment lines, stop at the scissors line.
    index($0, cc " ------------------------ >8 ------------------------") == 1 { exit }
    index($0, cc) == 1 { next }
    { lines[++n] = $0 }

    END {
        first = 1
        while (first <= n && lines[first] ~ /^[ \t]*$/) first++
        last = n
        while (last >= first && lines[last] ~ /^[ \t]*$/) last--

        subject = lines[first]
        if (subject ~ /^(fixup|squash|amend)! / || subject ~ /^Merge /) exit

        text = subject
        if (match(text, /^[a-z0-9_.\/-]+: /)) text = substr(text, RLENGTH + 1)
        if (subject == "") print "empty summary"
        else if (text !~ /^[A-Z`]/) print "summary is not capitalized"
        if (subject ~ /\.$/) print "summary ends with a period"
        if (subject ~ /[ \t]$/) print "summary ends with whitespace"
        if (length(subject) > 50) print "summary is longer than 50 characters"

        for (i = first + 1; i <= last; i++) {
            line = lines[i]
            ln = i - first + 1
            if (ln == 2 && line != "") print "no blank line after the summary"
            if (line ~ /^Assisted-by:/) {
                if (line !~ /^Assisted-by: [^: ]+:[^ ]+$/) print "malformed trailer: " line
                continue
            }
            if (line ~ /^[A-Z][A-Za-z]*(-[A-Za-z]+)+: /) continue
            if (line ~ /[ \t]$/) print "line " ln " ends with whitespace"
            if (length(line) > 72 && line !~ /^ / && line !~ /https?:\/\//)
                print "line " ln " is longer than 72 characters"
        }
    }
' "$msg")

[ -n "$problems" ] || exit 0
printf '%s\n' "$problems" | sed 's/^/check-commit-message: /' >&2
exit 1
