Skip to content

Commit 98b3994

Browse files
JordanCoinclaude
andauthored
Validate staged Go blobs in pre-commit gofmt check and include renames (#56)
* Fix pre-commit gofmt check to validate staged blobs * fix: address review comments on pre-commit hook - Use portable mktemp with explicit template (macOS compat) - Pipe staged files instead of here-doc (no leading space bug) - Use temp file + cat instead of printf %b (no backslash escapes) - Clean up temp result file on exit Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent e9ed7c1 commit 98b3994

1 file changed

Lines changed: 34 additions & 7 deletions

File tree

.githooks/pre-commit

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,45 @@
11
#!/bin/sh
2-
# Pre-commit hook: run gofmt on staged Go files
2+
# Pre-commit hook: run gofmt on staged Go file blobs (not working tree).
33

4-
STAGED_GO=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')
4+
STAGED_GO=$(git diff --cached --name-only --diff-filter=ACMR -- '*.go')
55

66
if [ -z "$STAGED_GO" ]; then
77
exit 0
88
fi
99

10-
UNFORMATTED=$(echo "$STAGED_GO" | xargs gofmt -l 2>/dev/null)
10+
UNFORMATTED=""
1111

12-
if [ -n "$UNFORMATTED" ]; then
13-
echo "gofmt required on:"
14-
echo "$UNFORMATTED"
12+
echo "$STAGED_GO" | while IFS= read -r file; do
13+
[ -z "$file" ] && continue
14+
15+
orig=$(mktemp "${TMPDIR:-/tmp}/gofmt.orig.XXXXXX") || continue
16+
formatted=$(mktemp "${TMPDIR:-/tmp}/gofmt.fmt.XXXXXX") || { rm -f "$orig"; continue; }
17+
18+
if ! git show ":$file" >"$orig" 2>/dev/null; then
19+
rm -f "$orig" "$formatted"
20+
continue
21+
fi
22+
23+
cp "$orig" "$formatted"
24+
if ! gofmt -w "$formatted" >/dev/null 2>&1; then
25+
rm -f "$orig" "$formatted"
26+
continue
27+
fi
28+
29+
if ! cmp -s "$orig" "$formatted"; then
30+
echo "$file" >> "${TMPDIR:-/tmp}/gofmt-unformatted.$$"
31+
fi
32+
33+
rm -f "$orig" "$formatted"
34+
done
35+
36+
RESULT_FILE="${TMPDIR:-/tmp}/gofmt-unformatted.$$"
37+
if [ -f "$RESULT_FILE" ]; then
38+
echo "gofmt required on staged content:"
39+
cat "$RESULT_FILE"
1540
echo ""
16-
echo "Run: gofmt -w $UNFORMATTED"
41+
echo "Run: gofmt -w <files> && git add <files>"
42+
rm -f "$RESULT_FILE"
1743
exit 1
1844
fi
45+
rm -f "$RESULT_FILE"

0 commit comments

Comments
 (0)