How To Upgrade To A Major Version In Go
In this article we are going to see how you can upgrade a package to a major version in Go and some of the common pitfalls when doing so.
invalid version: module contains a go.mod file, so major version must be compatible: should be v0 or v1, not v2
Have ever tried upgrading to a major version in Go (Golang)? Well if you did you may have seen this error. Let’s say that you have a version v1 of github.com/awesomerepo/pkg
package and you want to upgrade to its major version
$ go get github.com/awesomerepo/pkg@v2.0.0
invalid version: module contains a go.mod file, so major version must be compatible: should be v0 or v1, not v2
This is due to the fact that sementic versioning in Go requires us to change the Go package path when releasing or requiring modules with a version greater or equal to v2. As seen in the offical Go FAQ, the issue with versioning is described as follows:
Packages intended for public use should try to maintain backward compatibility as they evolve. The Go 1 compatibility guidelines are a good reference here: don’t remove exported names, encourage tagged composite literals, and so on. If different functionality is required, add a new name instead of changing an old one. If a complete break is required, create a new package with a new import path.
So when using Go modules we must follow semantic versioning rules in Go, namely:
- If you are using a version that is v2 or higher you must include the version number into the import path of your package, for example
github.com/awesomerepo/pkg/v2
. You will need to use the version in the import path for both go.mod imports (require github.com/awesomerepo/pkg/v2 v2.0.0
), when importing the package through command line (go get github.com/awesomerepo/pkg/v2@v2.0.0
) and when importing your package in your source files (import "github.com/awesomerepo/pkg/v2 v2.0.0"
) - If the module version is v0 or v1 do not include it in the import path of your package
So following the above mentioned rules we can now attempt upgrading our Go package to a major version
go clean -modcache // clean modcache
go get github.com/awesomerepo/pkg/v2@v2.0.0 // use v2 in the import path
More info on semantic versioning in Go https://github.com/golang/go/wiki/Modules#semantic-import-versioning
More info on Go Get versioning (Go FAQ) https://golang.org/doc/faq#get_version
Module compatibility and semantic versioning https://golang.org/cmd/go/#hdr-Module_compatibility_and_semantic_versioning