適用於 Go 專案的 Makefile 指南
適用於 Go 專案的 Makefile 指南
大家好,我叫謝偉,是一名使用 Go 語言的後端開發者。
本文章的主題是: 編寫適用於 Go 專案的 Makefile 指南。
1. 前提:
- 會使用 Makefile
- 會使用 Go 編寫專案
編寫專案的過程中,經常需要對檔案進行編譯和執行,檢視功能開發或者修復的 Bug 是否正確。你當然可以直接執行go build
命令用來編譯,執行go run
命令來執行。
在編寫 Go 專案其實還會經常執行些諸如 測試、格式檢查、庫下載安裝等命令。
當然你也可以編寫 shell 指令碼來執行這些命令,進一步進行了簡化。
其實有更好的選擇,即 Makefile。 在諸多的開源專案中經常能看到 Makefile 的身影。當你的專案中檔案發生變化,都可以使用 Makefile 執行命令來自動構建
2. Makefile 語法
PROJECT="example" default: echo ${PROJECT} install: @govendor sync -v test: install @go test ./... .PHONY: default install test
上文是一個非常簡單的 Makefile 檔案,通過這些命令的編寫,直接執行make
,make install
,make test
等就能完成對應的命令。
格式介紹:
<target> : <prerequisites> [tab]<commands>
#
3. Go 專案
Go 中支援內建的go
命令,可以用來執行:測試、編譯、執行、語法檢查等命令
一個完善的 Go 專案經常會執行哪些命令?
- go vet 靜態檢查
- go test 執行單元測試
- go fmt 格式化
- go build 編譯
-
go run 執行
...
所以一個適用於 Go 專案的 Makefile 也應該支援這些命令。
- make default : 編譯
- make fmt: 格式化
- make vet: 靜態檢查
- make test: 執行測試
- make install: 下載依賴庫
- make clean: 移除編譯的二進位制檔案
所以整體可以如下安排:
BINARY="example" VERSION=1.0.0 BUILD=`date +%FT%T%z` PACKAGES=`go list ./... | grep -v /vendor/` VETPACKAGES=`go list ./... | grep -v /vendor/ | grep -v /examples/` GOFILES=`find . -name "*.go" -type f -not -path "./vendor/*"` default: @go build -o ${BINARY} -tags=jsoniter list: @echo ${PACKAGES} @echo ${VETPACKAGES} @echo ${GOFILES} fmt: @gofmt -s -w ${GOFILES} fmt-check: @diff=$$(gofmt -s -d $(GOFILES)); \ if [ -n "$$diff" ]; then \ echo "Please run 'make fmt' and commit the result:"; \ echo "$${diff}"; \ exit 1; \ fi; install: @govendor sync -v test: @go test -cpu=1,2,4 -v -tags integration ./... vet: @go vet $(VETPACKAGES) docker: @docker build -t wuxiaoxiaoshen/example:latest . clean: @if [ -f ${BINARY} ] ; then rm ${BINARY} ; fi .PHONY: default fmt fmt-check install test vet docker clean
4. 補充
Makefile 構建工具,大大的簡化了構建專案的難度。
真實的生產環境下,需要使用到CI/CD(持續整合和持續部署), 所以 Makefile 也通常用來和 CI 工具配合使用。
比如新合併的程式碼,先觸發單元測試,靜態檢查等,在執行 CI 指令碼,成功之後,再構建映象,推送映象到伺服器上,完成持續整合和持續部署一整套流程。
Makefile 通常配合 travis 使用。
比如:
language: go go: - "1.11" - "1.11.x" env: - GO111MODULE=on notifications: email: recipients: - [email protected] on_success: change # default: change on_failure: always # default: always before_install: - go test -cpu=1,2,4 -v -tags integration ./... - go vet $(go list ./... | grep -v /vendor/) script: - make fmt - make fmt-check - make vet - make list - go test -race./... -coverprofile=coverage.txt -covermode=atomic
希望對大家有所啟發。
<完>
參考: