Specifically, for our next software release, I want to make sure to catch a bug fix that was released in go 1.5.2; is there a way to make the build fail if our build server tries to build my code using Go 1.5.1 or earlier?
I know about Build Constraints, and I can see how I can add a build constraint of "go1.5" to make sure the "1.5 or greater" compiler is used, but "go1.5.2" doesn't work (it appears that build tags go1.5.1 and go1.5.2 are not defined.)
On a related note, I also can't find a way to dump out the build tags that apply for a build, and yet this seems to be a pretty useful thing to do.
You can use the -ldflags
to pass the configured min golang build and check at init() time if the runtime matches the specified version.
package main
import "runtime"
// go run -ldflags "-X main.minGoVersion=go1.5.1" main.go
// from http://stackoverflow.com/questions/18409373/how-to-compare-two-version-number-strings-in-golang
func VersionOrdinal(version string) string {
// ISO/IEC 14651:2011
const maxByte = 1<<8 - 1
vo := make([]byte, 0, len(version)+8)
j := -1
for i := 0; i < len(version); i++ {
b := version[i]
if '0' > b || b > '9' {
vo = append(vo, b)
j = -1
continue
}
if j == -1 {
vo = append(vo, 0x00)
j = len(vo) - 1
}
if vo[j] == 1 && vo[j+1] == '0' {
vo[j+1] = b
continue
}
if vo[j]+1 > maxByte {
panic("VersionOrdinal: invalid version")
}
vo = append(vo, b)
vo[j]++
}
return string(vo)
}
var minGoVersion string
func init() {
if minGoVersion == "" {
panic("please pass -ldflags \"-X main.minGoVersion=<version string> flag\"")
}
current := VersionOrdinal(runtime.Version())
desired := VersionOrdinal(minGoVersion)
if current < desired {
panic("unsupported golang runtime " + current + " < " + desired)
}
}
func main() {
}