質問
The article describes a script to apply `go vet` which is a static analysis and `goimports` (go fmt) in git's pre-commit hook. When we use the script, we can prevent committing unexpected code.
Update: 

When team members wrote Golang code, they would commit corrupted formatting or with code mixed in that was deemed undesirable by static analysis.

So we should use a script to apply go vet which is static analysis and goimports (go fmt) in git pre-commit hook.

A script for git pre-commit hook

Edit .git/hooks/pre-commit in your Golang project as following:

#!/bin/sh

gopackages=$(git diff --cached --name-only --diff-filter=ACM | grep '.go$'| xargs -n1 dirname| sort -u| sed 's/^/.\//' )

[ -z "$gopackages" ] && exit 0

echo "Info: git diff (go packages)"
echo $gopackages
echo "Info: Runnning go vet"
linterr="$(go vet $gopackages 2>&1 )"
if [ -n "$linterr" ] ; then
    echo "fatal:"
    echo $linterr
    exit 1
fi

echo "Info: go vet -> OK"

unformatted=$(goimports -l $gopackages 2>&1 )
if [ -n "$unformatted" ] ; then
    echo "Info: unformatted file: $unformatted"
    echo "Info: Running goimports"
    for fn in $unformatted; do
        goimports -w $fn
        echo >&2 "goimports -w $fn"
        git add $fn
    done
fi

echo "Info: goinports -> OK"

exit 0

After you completed to edit, grant execute permission to .git/hooks/pre-commit.

chmod +x .git/hooks/pre-commit
Write a comment

Reference

Write a comment
この記事が気に入ったら応援お願いします🙏
31
ツイート
LINE
Engineer
morizyun
Full stack developer. Be able to build an optimal architecture with Next.js / Firebase / TypeScript / JavaScript Ruby / Golang / Kotlin / Java.