Skip to content

Instantly share code, notes, and snippets.

@peshala-prabhapoorna
Last active June 28, 2025 14:18
Show Gist options
  • Select an option

  • Save peshala-prabhapoorna/ffc25413adeb17d86d5875ce0174b34c to your computer and use it in GitHub Desktop.

Select an option

Save peshala-prabhapoorna/ffc25413adeb17d86d5875ce0174b34c to your computer and use it in GitHub Desktop.
Gofmt pre-commit hook

Gofmt Pre-commit Hook

A shell script to check and format only the staged .go files before committing. If any staged Go files are not properly formatted, it automatically formats them using gofmt, lists the affected files, and prevents the commit so you can stage the changes and try again.

Save this script as .git/hooks/pre-commit and give it execute permission.

#!/usr/bin/sh
# Check and format staged Go files using gofmt
echo "================="
echo "Checking staged Go files..."
# Get staged files
staged_files=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')
if [ -z "$staged_files" ]; then
echo "No staged Go files to check."
echo "================="
exit 0
fi
# Check formatting
unformatted=""
for file in $staged_files; do
if [ -f "$file" ]; then
if [ -n "$(gofmt -l "$file")" ]; then
unformatted="$unformatted $file"
fi
fi
done
if [ -n "$unformatted" ]; then
echo "The following staged Go files are not formatted:"
for file in $unformatted; do
echo "$file"
gofmt -w "$file"
done
echo "Files have been formatted. Please stage the changes and commit again."
echo "================="
exit 1
else
echo "All staged Go files are properly formatted."
echo "================="
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment