scripts/check-commit-message 2.5 KiB raw
1
#!/bin/sh
2
# Checks a commit message against the format described in CONTRIBUTING:
3
# summary style and length, blank line after it, trailer syntax and body line
4
# width. Git-generated subjects (fixup!, squash!, amend!, Merge) are
5
# not checked.
6
#
7
# Usage: check-commit-message FILE
8
#
9
# FILE `-` reads standard input. Comment lines and everything after the
10
# scissors line are ignored, as git does when cleaning up a message. Problems
11
# are printed on standard error and make the exit status 1.
12
13
if [ $# -ne 1 ]; then
14
    echo "usage: check-commit-message FILE" >&2
15
    exit 2
16
fi
17
msg=$1
18
if [ "$msg" != - ] && [ ! -f "$msg" ]; then
19
    echo "check-commit-message: $msg: no such file" >&2
20
    exit 2
21
fi
22
23
cc=$(git config core.commentChar 2>/dev/null)
24
case $cc in
25
    '' | auto) cc='#' ;;
26
esac
27
28
[ "$msg" = - ] && msg=/dev/stdin
29
30
problems=$(COMMENT_CHAR=$cc awk '
31
    BEGIN { cc = ENVIRON["COMMENT_CHAR"]; n = 0 }
32
33
    # Mimic git cleanup: drop comment lines, stop at the scissors line.
34
    index($0, cc " ------------------------ >8 ------------------------") == 1 { exit }
35
    index($0, cc) == 1 { next }
36
    { lines[++n] = $0 }
37
38
    END {
39
        first = 1
40
        while (first <= n && lines[first] ~ /^[ \t]*$/) first++
41
        last = n
42
        while (last >= first && lines[last] ~ /^[ \t]*$/) last--
43
44
        subject = lines[first]
45
        if (subject ~ /^(fixup|squash|amend)! / || subject ~ /^Merge /) exit
46
47
        text = subject
48
        if (match(text, /^[a-z0-9_.\/-]+: /)) text = substr(text, RLENGTH + 1)
49
        if (subject == "") print "empty summary"
50
        else if (text !~ /^[A-Z`]/) print "summary is not capitalized"
51
        if (subject ~ /\.$/) print "summary ends with a period"
52
        if (subject ~ /[ \t]$/) print "summary ends with whitespace"
53
        if (length(subject) > 50) print "summary is longer than 50 characters"
54
55
        for (i = first + 1; i <= last; i++) {
56
            line = lines[i]
57
            ln = i - first + 1
58
            if (ln == 2 && line != "") print "no blank line after the summary"
59
            if (line ~ /^Assisted-by:/) {
60
                if (line !~ /^Assisted-by: [^: ]+:[^ ]+$/) print "malformed trailer: " line
61
                continue
62
            }
63
            if (line ~ /^[A-Z][A-Za-z]*(-[A-Za-z]+)+: /) continue
64
            if (line ~ /[ \t]$/) print "line " ln " ends with whitespace"
65
            if (length(line) > 72 && line !~ /^ / && line !~ /https?:\/\//)
66
                print "line " ln " is longer than 72 characters"
67
        }
68
    }
69
' "$msg")
70
71
[ -n "$problems" ] || exit 0
72
printf '%s\n' "$problems" | sed 's/^/check-commit-message: /' >&2
73
exit 1