英文:
Installing All Go Mod Dependency Binaries
问题
我正在使用go1.16.3版本,并使用以下工具文件 consolide 依赖项:
// +build tools
package main
import (
	_ "github.com/swaggo/swag/cmd/swag"
	_ "honnef.co/go/tools/cmd/staticcheck"
)
在项目目录中运行 go get 会将包下载并安装到 $GOPATH/pkg/mod,但不会将它们的二进制文件安装到 $GOPATH/bin。逐个为每个模块运行 go get(例如 go get github.com/swaggo/swag/cmd/swag)会安装包和二进制文件。
是否有一种方法可以使用单个命令安装所有模块的二进制文件?
如果没有,有没有一种自动安装所有依赖项的包和二进制文件的正确方法?
英文:
I'm using go1.16.3 with this tools file to consolidate dependencies:
// +build tools
package main
import (
	_ "github.com/swaggo/swag/cmd/swag"
	_ "honnef.co/go/tools/cmd/staticcheck"
)
Running go get in the project dir downloads and installs the packages to $GOPATH/pkg/mod but doesn't install their binaries to $GOPATH/bin. Running go get individually for each mod (i.e. go get github.com/swaggo/swag/cmd/swag) does install both packages and binaries.
Is there a way I can install the binaries for all mods with a single command?
If not, what's the right way to automatically install all packages and binaries for all dependencies?
答案1
得分: 4
这个问题没有一个简单的单行命令可以完成。你最好的选择可能是编写一个脚本,将go list命令链式连接到go install命令中,以列出tools.go文件中的所有导入项:
tools=$(go list -f '{{range .Imports}}{{.}} {{end}}' tools.go)
go install $tools
解释一下上面的代码,go list用于查询包和模块。默认情况下,它只打印包名,但可以使用-f或-json来控制输出。go help list展示了go list可以打印的所有内容。-f的语法与text/template相同。
所以,在这里,go list tools.go查询一个包,该包是一个.go文件的列表,这里只有tools.go。.Imports是该包中导入项的排序去重列表。我们可以直接使用模板{{.Imports}},但它会在开头和结尾打印方括号。
$ go list -f '{{.Imports}}' tools.go
[github.com/swaggo/swag/cmd/swag honnef.co/go/tools/cmd/staticcheck]
因此,我们使用{{range .Imports}}遍历.Imports,在循环内部打印每个导入项({{.}})后跟一个空格。
英文:
There's not really a good way to do this in a single command. Your best bet might be a script that chains a go list command to list all the imports from tools.go into a go install command:
tools=$(go list -f '{{range .Imports}}{{.}} {{end}}' tools.go)
go install $tools
To explain the above, go list queries packages and modules. By default, it just prints package names, but its output can be controlled with -f or -json. go help list shows everything go list can print. The syntax for -f is the same as text/template.
So here, go list tools.go queries a package which is a list of .go files, in this case, just tools.go. .Imports is a sorted, deduplicated list of imports from that package. We could just use the template {{.Imports}}, but it prints brackets at the beginning and end.
$ go list -f '{{.Imports}}' tools.go
[github.com/swaggo/swag/cmd/swag honnef.co/go/tools/cmd/staticcheck]
So instead, we range over .Imports, and inside the range, we print each import ({{.}}) followed by a space.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论