golang : コミット時に gofmt を実行する(pre-commit hook)
misc/git/pre-commit - The Go Programming Language を参考に作成しました。
オリジナルではフォーマットされていないコードがある場合にコミットを中断していますが、以下のスクリプトでは gofmt を実行して git add するところまでやっています。
#!/bin/sh gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '.go$') [ -z "$gofiles" ] && exit 0 unformatted=$(gofmt -l $gofiles) [ -z "$unformatted" ] && exit 0 echo >&2 "Info: Running gofmt as some Go files are not formatted with gofmt." for fn in $unformatted; do gofmt.exe -s -w $fn echo >&2 "gofmt -s -w $fn" git add $fn done exit 0
リンク先は、gofmt に加えて、gocyclo によるCyclomatic complexity のチェック(見るだけ)と goimports の実行も合わせたものになります。