Skip to content

Commit 4171fb7

Browse files
committed
add Go 包管理工具 govendor 使用指南.md
1 parent 81e62f6 commit 4171fb7

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# Go 包管理工具 govendor 使用指南
2+
3+
govendor 是 go 语言依赖管理工具。
4+
5+
## 安装及初始化
6+
安装:
7+
```
8+
go get -u -v github.com/kardianos/govendor
9+
```
10+
初始化:
11+
```
12+
# Setup your project.
13+
cd "my project in GOPATH"
14+
govendor init
15+
16+
# Add existing GOPATH files to vendor.
17+
govendor add +external
18+
```
19+
20+
## 下载依赖包
21+
下面介绍三个命令:
22+
23+
- `govendor fetch`:不但可以下载自身的包,还可以下载依赖。
24+
- `govendor get`:如官网所述 Like "go get" but copies dependencies into a "vendor" folder,实际上只复制了依赖包进到 vendor 目录而已。
25+
- `govendor add`:Add packages from $GOPATH,意思是从本地加载依赖包。
26+
27+
综上,如果是下载依赖包,一定是用 `govendor fetch`
28+
29+
```
30+
govendor fetch github.com/gin-gonic/[email protected] # 只拷贝 gin/ 目录的内容,而不包含其子目录
31+
govendor fetch github.com/gin-gonic/gin/[email protected] # 可以得到 gin/ 目录,及其所有子目录
32+
```
33+
`@v1.2` 表示使用 v1.2 版本,其实就是 git tag 为 v1.2 的 revision,这个功能很实用。
34+
35+
再说一个可能会碰到的问题,有时候我们使用第三方依赖包,而且还有 bug,修复之后,期望使用自己仓库的时候,可以这样做:
36+
37+
```
38+
govendor get 'github.com/go-sql-driver/mysql::github.com/yongxinz/go-mysql'
39+
```
40+
原仓库的 `github.com/go-sql-driver/mysql` 存在一个小问题,此时期望使用自己修复过的 `github.com/yongxinz/go-mysql`
41+
42+
## 版本管理
43+
不要将整个 `vendor/` 目录的内容都提到 git 仓库,只提交 `vendor/vendor.json` 文件就可以了。
44+
45+
当我们拉代码之后,需要安装依赖包时,只需要执行下面这条命令就可以了。
46+
47+
```
48+
govendor sync
49+
```
50+
51+
`.gitignore` 文件,重点在最后两行:
52+
53+
```
54+
# Created by https://www.gitignore.io/api/go
55+
### Go ###
56+
# Binaries for programs and plugins
57+
*.exe
58+
*.exe~
59+
*.dll
60+
*.so
61+
*.dylib
62+
# Test binary, build with `go test -c`
63+
*.test
64+
# Output of the go coverage tool, specifically when used with LiteIDE
65+
*.out
66+
67+
### Go Patch ###
68+
/vendor/
69+
!/vendor/vendor.json
70+
```
71+
所以,一般的开发流程可以这样来做:如果是新建项目,先安装 govendor 并初始化,然后通过 govendor 来安装依赖包;如果是已有项目,先从版本库拉下来,然后安装 govendor,再执行同步命令即可。
72+
73+
## 其他命令
74+
75+
`govendor status`: 查看当前包状态
76+
77+
`govendor list +e`: 查看当前项目的依赖但是未被添加到 `vendor` 中的包
78+
79+
`govendor add +e`: 添加依赖的包。如果 `vendor.json` 中存在,但是 `vendor` 目录下不存在(即 `govendor status` 显示缺失)的包也会被重新添加
80+
81+
`govendor remove +u`: 删除在 `vendor` 下但是未依赖的包
82+
83+
在实际过程中,有部分包是团队的公共包。 这部分包通常有自己的单独项目,并且已经被我们添加到 `$GOPATH` 下,可能就不需要添加到当前项目的 `vendor` 下。
84+
85+
这时候可以结合 `list``add` 来使用, 先用 `list -no-status +e` 列出依赖包,然后使用 `grep` 过滤,再调用 `add` 命令添加:
86+
87+
```
88+
govendor list -no-status +e | grep -v 'myteam/common' | xargs govendor add
89+
```
90+
91+
92+
<br>相关文档:<br>
93+
https://github.com/kardianos/govendor<br>
94+
https://www.orztu.com/post/using-govendor/<br>
95+
https://linkscue.com/2018/08/09/2018-08-09-govendor-tips/

0 commit comments

Comments
 (0)