golang vendor是为了解决golang依赖的问题的, 因为golang的依赖都是以源码的形式存在的, 所以如果别的项目变更了API, 这个时候很有可能会让你的代码无法通过编译. 在vendor出来之前, 一般都是用godep来解决的, godep是把这些依赖的源代码复制到当前的Godeps目录, 然后go build 变成 godep go build
godep算是一个妥协的产物, 但它毕竟更改了go build的原义, 所以这个方案还是不够满意, 所以vendor来了. go1.5需要通过GO15VENDOREXPERIMENT=1
环境变量开启, go1.6默认开启
golang文档是这样说的:
Go 1.6 includes support for using local copies of external dependencies to satisfy imports of those dependencies, often referred to as vendoring.
Code below a directory named “vendor” is importable only by code in the directory tree rooted at the parent of “vendor”, and only using an import path that omits the prefix up to and including the vendor element.
Here’s the example from the previous section, but with the “internal” directory renamed to “vendor” and a new foo/vendor/crash/bang directory added:
|
|
The same visibility rules apply as for internal, but the code in z.go is imported as “baz”, not as “foo/vendor/baz”.
Code in vendor directories deeper in the source tree shadows code in higher directories. Within the subtree rooted at foo, an import of “crash/bang” resolves to “foo/vendor/crash/bang”, not the top-level “crash/bang”.
Code in vendor directories is not subject to import path checking (see ‘go help importpath’).
When ‘go get’ checks out or updates a git repository, it now also updates submodules.
Vendor directories do not affect the placement of new repositories being checked out for the first time by ‘go get’: those are always placed in the main GOPATH, never in a vendor subtree.
In Go 1.5, as an experiment, setting the environment variable GO15VENDOREXPERIMENT=1 enabled these features. As of Go 1.6 they are on by default. To turn them off, set GO15VENDOREXPERIMENT=0. In Go 1.7, the environment variable will stop having any effect.
See https://golang.org/s/go15vendor for details.
举个例子
假设有如下的目录:
|
|
main.go 内容如下:
|
|
vendor/a/a.go 如下:
|
|
vendor/b/b.go looks like:
|
|
vendor/c/c.go looks like:
|
|
最后 vendor/c/vendor/a/a.go looks like:
|
|
如果不带上vendor特性, 运行main.go, 你会得到:
但是如果开启vendor:
总结一下就是, b和main都会使用vendor/a
包, 而c本身会使用它自己的vendor, vendor/c/vendor/a
那怎么保存我的依赖到vendor目录呢?
官方并没有提供这种工具, 显然是要我们自己来处理了, 我们可以用这个工具https://github.com/kardianos/govendor就可以啦
govendor Quick Start
|
|