在Go專案利用pre-commit搭配golangci-lint做git commit前的linting檢查。
pre-commit除了本身pre-commit-hooks
的hooks檢查外也可加入外部的hooks檢查,通常會搭配linter提供的hook做程式碼linting。支援的外部hooks可參考Supported hooks。
參考「使用pre-commit做commit前檢查」及「Go golangci-lint安裝及使用」了解並安裝好pre-commit及golangci-lint。
範例
pre-commit加入golangci-lint的hooks如下,在pre-commit配置檔.pre-commit-config.yaml
加入golangci-lint hook的repo及id即可,repo為golangci-lint的github位址https://github.com/golangci/golangci-lint
,rev為Tags的版本。
.pre-commit-config.yaml
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/golangci/golangci-lint # golangci-lint hook repo
rev: v1.42.0 # golangci-lint hook repo revision
hooks:
- id: golangci-lint # hook id
設定好配置檔後在Go專案根目錄輸入pre-commit install
載入剛加入的golangci-lint hook到專案的.git/hooks
。
~/.../go-demo$ pre-commit install
pre-commit installed at .git/hooks/pre-commit
到此便完成pre-commit加入golangci-lint hook設定,之後提交的go程式就會多了golangci-lint的檢查。
例如在main.go
加一未使用的package變數g
。
main.go
package main
import "fmt"
var g = 123
func main() {
fmt.Println("Hello World")
}
git commit此異動時會做pre-commit檢查,其中包括了golangci-lint
~/.../go-demo$ git commit -m "test"
[INFO] Initializing environment for https://github.com/golangci/golangci-lint.
[INFO] Installing environment for https://github.com/golangci/golangci-lint.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
Check Yaml...........................................(no files to check)Skipped
Fix End of Files.........................................................Passed
Trim Trailing Whitespace.................................................Passed
golangci-lint............................................................Failed
- hook id: golangci-lint
- exit code: 1
main.go:5:5: `g` is unused (deadcode)
var g = 123
^
參考github。
但通常除了golangci-lint hook還會加入其他外部hooks,有許多已整合多個外部hooks的repo可使用,例如github.com/dnephin/pre-commit-golang
及整合了golangci-lint hook。
沒有留言:
張貼留言