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]
Here is the answer:
Note:
go list -deps
produces one row for each package. So modules from which multiple packages are imported are listed mutiple times.sort -u
sorts and removes duplicates.It can be compared with:
Here is a version with more details that lists each package referenced from each module (also using
jq
: