20

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

5
  • 2
    Why not just parsing the go.mod file?
    – leaf bebop
    Dec 5, 2019 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 Dec 5, 2019 at 14:01
  • 1
    I don't understand - you can dynamically parse go.mod right?
    – leaf bebop
    Dec 5, 2019 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 5, 2019 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 5, 2019 at 18:16

3 Answers 3

23

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}'
1
  • 12
    You can omit the grep and awk like such: go list -m -f '{{ .Version }}' moduleImport Oct 4, 2020 at 16:21
20

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

1
  • 1
    tried it and got a go: can't determine available versions using the vendor directory
    – Ghilteras
    Aug 7, 2023 at 17:17
-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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.