Application auto build versioning

后端 未结 6 831
情话喂你
情话喂你 2020-11-28 00:25

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 auto

6条回答
  •  执笔经年
    2020-11-28 00:34

    I had trouble using the -ldflags parameter when building my mixed command-line app and library project, so I ended up using a Makefile target to generate a Go source file containing my app's version and the build date:

    BUILD_DATE := `date +%Y-%m-%d\ %H:%M`
    VERSIONFILE := cmd/myapp/version.go
    
    gensrc:
        rm -f $(VERSIONFILE)
        @echo "package main" > $(VERSIONFILE)
        @echo "const (" >> $(VERSIONFILE)
        @echo "  VERSION = \"1.0\"" >> $(VERSIONFILE)
        @echo "  BUILD_DATE = \"$(BUILD_DATE)\"" >> $(VERSIONFILE)
        @echo ")" >> $(VERSIONFILE)
    

    In my init() method, I do this:

    flag.Usage = func() {
        fmt.Fprintf(os.Stderr, "%s version %s\n", os.Args[0], VERSION)
        fmt.Fprintf(os.Stderr, "built %s\n", BUILD_DATE)
        fmt.Fprintln(os.Stderr, "usage:")
        flag.PrintDefaults()
    }
    

    If you wanted an atomically-increasing build number instead of a build date, however, you would probably need to create a local file that contained the last build number. Your Makefile would read the file contents into a variable, increment it, insert it in the version.go file instead of the date, and write the new build number back to the file.

提交回复
热议问题