LoginSignup
2
3

More than 5 years have passed since last update.

gitのpre-commitを使ってbuildに失敗するコミットを防ぐ

Posted at

問題だったこと

私はgoでコード書いていてしばしばコミットした後にbuildしてエラー。
修正してコミットみたいな生産性の低いことをやっていました。

これをどうにかするためにgitのpre-commitを使ってみることとしました。

手順

$ vi .git/hooks/pre-commit
pre-commit
#!/bin/sh

# build project
build_result=$(make)
build_rc=$?
if [ $build_rc -ne 0 ] ; then
    echo "git pre-commit check failed: build failed."
    exit 1
fi
$ chmod +x .git/hooks/pre-commit

これでcommit時にmakeコマンド(build命令していると思ってください)が走って
失敗した場合はcommitが作られないようになります

サンプル

$ vi main.go
main.go
package main

func main() {
    a := 1
}
$ git add .
$ git commit -m "init"
github.com/smith-30/sample-git
# github.com/smith-30/sample-git
./main.go:4:2: a declared and not used
make: *** [build] Error 2
git pre-commit check failed: build failed.

修正

main.go
package main

import "fmt"

func main() {
    a := 1
    fmt.Println(a)
}
$ git add .
$ git commit -m "init"
[master d34bde1] init
 1 file changed, 8 insertions(+)
 create mode 100644 main.go

# yatta

参考

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3