我可以帮您列出最终可执行文件中编译的模块(及其版本),而不包括其他依赖项。以下是代码示例:
$ go build -o a.out
$ go version -m a.out
但是我该如何使用 go list
(它具有方便的JSON输出)来实现呢?
我尝试了这个方法:
$ go list -m -f '{{define "M"}}{{.Path}}@{{.Version}}{{end}}{{if not .Main}}{{if .Replace}}{{template "M" .Replace}}{{else}}{{template "M" .}}{{end}}{{end}}' all
但是它列出了许多传递依赖项,这些依赖项仅在测试套件中使用。
我不知道如何过滤掉这些依赖项。
以下是一个示例项目以查看问题(可在Go Playground上获取):
main.go
:
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
main_test.go
:
package main
import (
"github.com/google/go-cmp/cmp"
"testing"
)
func TestHelloWorld(t *testing.T) {
if !cmp.Equal(1, 1) {
t.Fatal("FAIL")
}
}
go.mod
:
module play.ground
go 1.15
require github.com/google/go-cmp v0.5.2
$ go build -o hello ; go version -m hello
hello: go1.15
path play.ground
mod play.ground (devel)
$ go list -m -f '{{define "M"}}{{.Path}}@{{.Version}}{{end}}{{if not .Main}}{{if .Replace}}{{template "M" .Replace}}{{else}}{{template "M" .}}{{end}}{{end}}' all
github.com/google/go-cmp@v0.5.2
golang.org/x/xerrors@v0.0.0-20191204190536-9bdfabe68543
Module
字段,如文档所述。 - Jonathan Hall{{if not .Indirect}}{{.}}{{end}}
仅包括直接依赖项。 - iczaIndirect
不会排除在测试中使用的模块。在我的例子中,github.com/google/go-cmp@v0.5.2
在go list
中被列出,但并未在二进制文件中使用。 - dolmengo list -deps -f '{{with .Module}}{{.Path}} {{.Version}}{{end}}'
- icza