dep是一個golang依賴管理工具,需要在Go 1.7及更高的版本中使用。
1. 安裝
安裝dep工具的方式有很多種,如果是mac電腦的話,只需要如下命令:
brew install dep
對於Linux和類Unix系統而言,我們還可以使用如下方式安裝dep:
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
或者直接使用源碼安裝。
而對於windows電腦,可以使用命令行:
go get -u github.com/golang/dep/cmd/dep
會自動下載到go_path/bin/目錄下,你需要將go_path/bin 加入到環境變量中。
如果這種方式下載不下來,你也可以手動下載:點擊這裏,挑選適合你的版本,然後修改文件名爲dep.exe放入go_path/bin/目錄下。
2. 使用
安裝完畢再命令行下敲入dep命令:
$ dep
Dep is a tool for managing dependencies for Go projects
Usage: "dep [command]"
Commands:
init Set up a new Go project, or migrate an existing one
status Report the status of the project's dependencies
ensure Ensure a dependency is safely vendored in the project
prune Pruning is now performed automatically by dep ensure.
version Show the dep version information
Examples:
dep init set up a new project
dep ensure install the project's dependencies
dep ensure -update update the locked versions of all dependencies
dep ensure -add github.com/pkg/errors add a dependency to the project
Use "dep help [command]" for more information about a command.
如上:
init命令用來初始化項目;
status命令用來查看當前項目的依賴狀態;
ensure命令用來同步依賴包
3. 初始化
切換到你的工程目錄下:
cd $GOPATH/src/goProject
假設項目現在是空的,什麼也沒有,進行初始化:
dep init -v
注意:因爲牆的原因,,,不一定我們能成功的拉下來依賴,使用dep init 儘量帶上-v:
-v enable verbose logging (default: false)
如果半分鐘沒響應就ctrl+c中斷,就可以看到fail的原因,dep遇到一些錯誤不會立馬報錯(特別是網絡原因) 。
執行成功之後會生成兩個文件 Gopkg.lock、Gopkg.toml和一個文件夾vendor
Gopkg.toml文件記錄着current project依賴項project的約束。
Gopkg.toml參數解釋:
[[constraint]]: 這個約束主要體現在到底要採用目標project的某個tag的版本(version),還是某個branch,或者是某個revision,這三個對於一個constraint只能選一個。
[[override]]:有時項目依賴比較複雜,經常會遇到依賴衝突導致 dep ensure 命令無法執行成功,這個時候使用 override 消除單個依賴關係上多個不可調和的constraint聲明之間的分歧
[[required]]:列出了必須包含在Gopkg.lock中的一組包
[[ignored]]:列出dep靜態分析源代碼時忽略的一組包
[[prune]]:prune爲依賴關係定義全局和每個項目的prune選項。 這些選項決定寫入vendor/時丟棄哪些文件
- unused-packages:修剪掉來自於目錄中,但是沒有出現在包導入圖中的文件
- non-go:修剪掉非.go文件
- go-tests:修剪掉Go的測試文件
Gopkg.lock文件是工具生成的,你不用手工編輯
vendor文件裏面存放current project的遠程依賴的源代碼
當需要指定目標project使用哪一個version時,可以在Gopkg.toml中添加。如,需要指定alice版本爲0.8.4,在Gopkg.toml中添加:
[[constraint]]
name = "github.com/golang/dep"
version = "=0.8.4"
然後執行
dep ensure -update "github.com/golang/dep
在指定version的時候,如果指定semantic version,可選的符號有
- =: 只選擇對應version
- >或<: 大於(或小於)對應版本號
- >=或<=: 大於等於(或小於等於)對應版本號
- ~: ~1.2.3表示 >=1.2.3,<1.3.0
- ^: ^1.2.3表示 >1.2.3,<2.0.0
不指定符號的話,默認爲^符號。
有了包管理工具之後,好處還是挺多:
- 幫你鎖住依賴版本,防止第三方包升級導致代碼不兼容;
- 將項目的依賴都放在vendor下,就不用依賴gopath下的公共包了;
4. 添加依賴
依賴管理幫助
`dep help ensure`
添加一條依賴
`dep ensure -add github.com``/bitly/go-simplejson`
一次性添加多條依賴
`dep ensure -add github.com``/pkg/errors` `github.com``/bitly/go-simplejson`
添加依賴指定依賴版本
`dep ensure -add github.com``/bitly/go-simplejson``@=0.4.3`
添加後記住執行dep ensure確保同步
`dep ensure -``v`
如果執行dep ensure出錯,看下Gopkg.toml文件中是否同時配置了version,branch和revision。