I want to list the modules (and their versions) that are compiled in the final executable (and not other dependencies).
I can do that with:
$ go build -o a.out
$ go version -m a.out
But how can I do that with go list
(which has a convenient JSON output)?
I tried this:
$ go list -m -f '{{define "M"}}{{.Path}}@{{.Version}}{{end}}{{if not .Main}}{{if .Replace}}{{template "M" .Replace}}{{else}}{{template "M" .}}{{end}}{{end}}' all
But it lists many transitive dependencies which are only used in test suites for example. I don't see how I could filter out those dependencies.
Here is a sample project to see the problem (available on The 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/[email protected]
golang.org/x/[email protected]
Module
field of the package as documented. – Gilbertogilbertson{{if not .Indirect}}{{.}}{{end}}
only includes direct dependencies. – Countertype.Indirect
do not excludes modules which are used in tests. In my example,github.com/google/[email protected]
is listed ingo list
but is not used in the binary. – Untowardgo list -deps -f '{{with .Module}}{{.Path}} {{.Version}}{{end}}'
– Countertype