Search code examples
go

Application auto build versioning


Is it possible to increment a minor version number automatically each time a Go app is compiled?

I would like to set a version number inside my program, with an autoincrementing section:

$ myapp -version
MyApp version 0.5.132

Being 0.5 the version number I set, and 132 a value that increments automatically each time the binary is compiled.

Is this possible in Go?


Solution

  • The Go linker (go tool link) has an option to set the value of an uninitialised string variable:

    -X importpath.name=value
      Set the value of the string variable in importpath named name to
    

    value. Note that before Go 1.5 this option took two separate arguments. Now it takes one argument split on the first = sign.

    As part of your build process, you could set a version string variable using this. You can pass this through the go tool using -ldflags. For example, given the following source file:

    package main
    
    import "fmt"
    
    var xyz string
    
    func main() {
        fmt.Println(xyz)
    }
    

    Then:

    $ go run -ldflags "-X main.xyz=abc" main.go
    abc
    

    In order to set main.minversion to the build date and time when building:

    go build -ldflags "-X main.minversion=`date -u +.%Y%m%d.%H%M%S`" service.go
    

    If you compile without initializing main.minversion in this way, it will contain the empty string.