18

We are working with Go modules. I want in a CLI to get the specific version of a module. Is it possible?

If you are curious, the reason is that I want to add the following generate command:

//go:generate go run github.com/golang/mock/mockgen -source="$GOPATH/pkg/mod/mymodules.com/mymodule@${VERSION}/module.go" -destination=module_mock.go

So I need to somehow get the version

ElyashivLavi
  • 1,681
  • 3
  • 22
  • 33
  • 2
    Why not just parsing the `go.mod` file? – leaf bebop Dec 05 '19 at 14:00
  • It's possible, but it's quite difficult to do it as part of the go:generate. If I will hard-code it, every time I will update the module, the command will break, so I prefer to get the version dynamically – ElyashivLavi Dec 05 '19 at 14:01
  • 1
    I don't understand - you can dynamically parse `go.mod` right? – leaf bebop Dec 05 '19 at 14:08
  • 1
    `go list -m -u all` piped to `grep` would do it, but I'd try to avoid generating mocks of a third-party package. Rather, write an interface for it in your own project, and mock that. – Adrian Dec 05 '19 at 15:05
  • 1
    This might not get you what you want, but if you run `go mod vendor`, then all module packages will be available in the local directory without versions. That will make `-source="vendor/mymodules.com/mymodule/module.go"` work. – Bubbles Dec 05 '19 at 18:16

3 Answers3

20

Basics:

go list -m all — View final versions that will be used in a build for all direct and indirect dependencies

go list -u -m all — View available minor and patch upgrades for all direct and indirect dependencies

Example:

To get the version of a specific module, let's say golang.org/x/text

go list -m all | grep golang.org/x/text | awk '{print $2}'

or

go list -u -m all | grep golang.org/x/text | awk '{print $2}'

So, the general way:

go list -u -m all | grep <module-name> | awk '{print $2}'
shmsr
  • 3,802
  • 2
  • 18
  • 29
15

Late but worth to mention, if you want to check the all available versions of a specific module:

go list -m -versions <module_name>

Like:

go list -m -versions github.com/user/module-name

Zubair Hassan
  • 776
  • 6
  • 14
-2

This command will get the version of go that's used in a project.

[$]> grep -m 1 go go.mod | cut -d\ -f2

That'll output a version like 1.18.

Andrew
  • 3,733
  • 1
  • 35
  • 36