使用 govendor 管理你的 go 項目包版本

govendorgo 的一個比較好用包版本管理工具。主要用來保證 go 項目在協同開發或發版部署時,保證部署安裝的依賴包版本對當前項目是穩定可用的。

爲什麼要使用包版本管理工具

javamavenphpcomposernodejsnpmpythonrequirement.txtgolanggovendor

例1:你的項目依賴一個github.com/foo 1.0.0的包,如果不使用包版本管理工具,他人在本地部署安裝你的項目時,安裝的包版本可能是最新的github.com/foo 2.0.0,如果兩個版本存在兼容問題,就會出現crashed
例2:使用 go get 安裝的項目依賴包的存放位置爲 $GOPATH/src,即與你的項目路徑同級,我們使用 git 時就沒辦法管理這些依賴包,不能也不應該將它們也提交到git倉庫,如果提供一個包版本說明說,將說明書提交倉庫,他人則根據此說明書安裝依賴包。

爲解決此問題,govendor出現了,govendor會將項目依賴的包版本記錄到your_proj/vendor/vendor.json中,後期將此文件提交至 git 倉庫,則其他人 pull or clone 你的項目到本地後,即可使用 govendor 安裝穩定的包依賴。

govendor 工作流

首先要部署好你的 go 環境,並將 $GOPATH/bin 路徑加載到系統PATH中。我們將體驗一遍如何使用govendor管理你的項目包版本,及如何安裝他人的govendor管理的go項目(這點纔是精華,很多博文都不提及,爲什麼版本管理,不就是爲了能讓程序在其他地方也能穩定運行嘛)。

安裝govendor

go get -u -v github.com/kardianos/govendor
#運行 govendor 檢測安裝結果
govendor

如果能看到幫助提示信息,說明安裝ok。

項目初始化

使用 govendor 初始化你的項目,將會在工程目錄下自動創建 vendor 目錄及 vendor/vendor.json 文件。如果是已有項目,也沒關係,govendor允許你在項目開發的任何階段去使用它,它總能將你的項目包版本管理起來。

mkdir go_proj && cd go_proj
# init proj
govendor init
#查看目錄結構
tree
.
└── vendor
    └── vendor.json

1 directory, 1 file

安裝&管理包

govendor get

我們仍然可以通過 go get安裝包到 $GOPATH/src下,但使用govendor get可以在安裝包的同時將包納入版本管理,而且會將包安裝在$GOPATH/src/your_proj/vendor,更符合我們的要求。

#安裝在 $GOPATH/src 下
go get github.com/go-sql-driver/mysql

#安裝在$GOPATH/src/your_proj/vendor下
govendor get github.com/go-sql-driver/mysql

govendor list & govendor add

govendor list可以幫助我們查看項目中引入的包的狀態,即哪些是沒有納入版本管理的外部包,哪些是納入版本管理的包,哪些是標準包,哪些是本地包等。

govendor list

Status Types

        +local    (l) packages in your project 你自己在項目中定義的包
        +external (e) referenced packages in GOPATH but not in current project 使用 go get 安裝的項目外部包
        +vendor   (v) packages in the vendor folder 使用 govendor get 安裝的納入版本管理的包
        +std      (s) packages in the standard library 標準包 fmt/time/runtime 等
        
        +excluded (x) external packages explicitly excluded from vendoring 排除的外部包
        +unused   (u) packages in the vendor folder, but unused 安裝但沒引用的包
        +missing  (m) referenced packages but not found 引用但沒安裝的包 缺失了

        +program  (p) package is a main package 你的項目主包,它總會同 l 一起出現 pl 這個很好理解吧

        +outside  +external +missing
        +all      +all packages

govendor add則是方便我們在任何時間將項目包納入版本管理。比如我們前期一直使用或現在偶然使用go get安裝了一個項目的依賴包,此包是不會被記錄在vendor/vendor.json中的,即沒有納入版本管理,那該如何將其納入呢?

go add +external

執行上方命令即可,這樣項目依賴的包都納入了版本管理。

提交git倉庫

在提交源碼至git倉庫時,我們沒有必要將依賴包源文件也一併提交至倉庫,所以 .gitignore 的編排要加上如下規則:

# vi .gitignore
vendor/*
!vendor/vendor.json

即排除vendor下的除vendor/vendor.json外的所有文件(這些文件其實就是依賴包),將vendor/vendor.json提交至git倉庫即可。

安裝/部署 govendor 項目

當我們從git倉庫下載好govendor管理的golang項目時,需要安裝好項目的包依賴,纔可以正常的運行程序,類似 composer install的作用,這裏則是使用govendor sync

這裏使用我的一個 govendor 管理的基於GinMVC簡易框架給大家演示一下:

cd $GOPATH/src && git clone [email protected]:sqrtcat/easy-gin.git && cd easy-gin

govendor sync

運行程序即可,簡單!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章