Skip to content

Instantly share code, notes, and snippets.

@tueda
Last active August 12, 2016 09:29
Show Gist options
  • Save tueda/7633695 to your computer and use it in GitHub Desktop.
Save tueda/7633695 to your computer and use it in GitHub Desktop.
A git hook warning too long lines in commit messages, not fitting with 50/72 formatting.
#!/bin/sh
#
# A (client-side) git hook script which warns if there are too long lines in
# the commit message, not fitting with 50/72 formatting.
#
# To use this script, copy it as .git/hooks/commit-msg and give it an executable
# file permission.
#
FILE=$1
msg_lines() {
cat "$FILE" \
| sed 's/^#.*//' \
| sed '/./=' \
| sed '/^$/{p;d}; N; s/^/ /; s/ *\(.\{6,\}\)\n/\1 /' \
| sed -n '/./,$p'
}
first_line() {
msg_lines | head -1
}
second_line() {
msg_lines | head -2 | tail -1
}
rest_lines() {
msg_lines | sed '1,2d'
}
my_warned=false
if first_line | sed -n '/\(.\)\{81\}/p' | grep '.' >/dev/null; then
echo '' >&2
echo 'WARNING: The first line should be 72 characters or less.' >&2
first_line >&2
my_warned=true
elif first_line | sed -n '/\(.\)\{59\}/p' | grep '.' >/dev/null; then
echo '' >&2
echo 'WARNING: The first line is recommended to be 50 characters or less.' >&2
first_line >&2
my_warned=true
fi
if second_line | grep '.' >/dev/null; then
echo '' >&2
echo 'WARNING: The second line should be blank.' >&2
second_line >&2
my_warned=true
fi
if rest_lines | sed -n '/\(.\)\{81\}/p' | grep '.' >/dev/null; then
echo '' >&2
echo 'WARNING: Text should be wrapped at 72 characters.' >&2
rest_lines | sed -n '/\(.\)\{81\}/p' | grep '.' >&2
my_warned=true
fi
if $my_warned; then
echo '' >&2
echo ' use "git commit --amend" etc. to reedit the commit message.' >&2
echo '' >&2
fi
@DanielSundberg
Copy link

DanielSundberg commented Aug 12, 2016

When only having one line in commit message "git commit -m 'test'" I get:

>git commit -m 'test'

WARNING: The second line should be blank.
     1  test

    use "git commit --amend" etc. to reedit the commit message.

[local/test-commit-msgs 4e04f16] test
 1 file changed, 1 insertion(+), 1 deletion(-)

Shouldn't warn in this case?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment