Skip to content

Commit 88086ba

Browse files
committed
[build] Add commit-msg hook to wrap commit messages at 90 chars with
formatting This change introduces a commit-msg hook that reformats commit messages to ensure all non-comment lines are wrapped to a maximum of 90 characters. The hook skips comment lines and fenced code blocks, preserving verbose commit diffs and code examples.Wrapping is done by finding the nearest space before the limit, which avoids breaking words awkwardly and prefers natural break points near spaces or punctuation. Blank lines are preserved to maintain paragraph separation. In addition, each wrapped line has two trailing spaces appended, allowing proper line breaks in Markdown renderers. The hook is placed in the repository's active Git hooks directory, respecting the configured core.hooksPath. It will run for both new commits and amended commits, ensuring consistent commit message format across the project.
1 parent e0dcfc9 commit 88086ba

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

gradle/githooks/commit-msg

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#!/bin/sh
2+
# Wrap non-comment commit message lines to <90 chars nicely, with 2 spaces at end.
3+
4+
COMMIT_MSG_FILE="$1"
5+
MAX_LEN=78
6+
7+
tmp_file="$(mktemp)"
8+
in_code_block=0
9+
10+
wrap_line() {
11+
local text="$1"
12+
local len=$MAX_LEN
13+
while [ ${#text} -gt $len ]; do
14+
# Try to break at the last space before $len
15+
local break_pos=$(echo "$text" | awk -v max=$len '{
16+
pos = max
17+
while (pos > 0 && substr($0,pos,1) != " ") pos--
18+
if (pos == 0) pos = max
19+
print pos
20+
}')
21+
22+
printf '%s \n' "${text:0:$break_pos}" >> "$tmp_file"
23+
text="${text:$break_pos}"
24+
# Trim leading spaces from the remainder
25+
text=$(echo "$text" | sed 's/^ *//')
26+
done
27+
28+
if [ -n "$text" ]; then
29+
printf '%s\n' "$text" >> "$tmp_file"
30+
fi
31+
}
32+
33+
while IFS= read -r line || [ -n "$line" ]; do
34+
case "$line" in
35+
'```'*)
36+
# Toggle code block mode
37+
if [ $in_code_block -eq 0 ]; then in_code_block=1; else in_code_block=0; fi
38+
printf '%s\n' "$line" >> "$tmp_file"
39+
continue
40+
;;
41+
\#*)
42+
# Leave comment lines as-is
43+
printf '%s\n' "$line" >> "$tmp_file"
44+
continue
45+
;;
46+
"")
47+
# Preserve blank lines
48+
printf '\n' >> "$tmp_file"
49+
continue
50+
;;
51+
esac
52+
53+
if [ $in_code_block -eq 1 ]; then
54+
printf '%s\n' "$line" >> "$tmp_file"
55+
else
56+
wrap_line "$line"
57+
fi
58+
done < "$COMMIT_MSG_FILE"
59+
60+
mv "$tmp_file" "$COMMIT_MSG_FILE"
61+
exit 0
62+

0 commit comments

Comments
 (0)