简体   繁体   中英

How to build Go Module with a semantic version?

Here are the bash steps to setup a new minimal Go module project with a git repo, commit it, and tag it with annotated semantic version tag:

mkdir gotest
cd gotest

git init

go mod init test.org/simple

cat <<EOT >> app.go
package main

import (
    "fmt"
    "runtime/debug"
)

func main() {
    fmt.Println("hello world")

    if bi, ok := debug.ReadBuildInfo(); ok {
        fmt.Printf("version=%v. sum=%v\n", bi.Main.Version, bi.Main.Sum)
    } else {
        fmt.Println("Failed to get build info")
    }
}
EOT

echo "simple" >> .gitignore

git add go.mod app.go .gitignore
git commit -am "initial commit"
git tag -am "initial semantic version" v0.1.0

Quickly verify that it's tagged correctly:

git tag -n
git describe --dirty

Build and run:

go build
./simple

That produces:

hello world
version=(devel). sum=

I was hoping to see the semantic version I tagged the repository with. Instead I got the dummy placeholder version. What is wrong?

The go command does not query version control to determine whether your repository is a pristine checkout of a semantic version (that's https://golang.org/issue/29228 ).

If you build the binary with some other module as the main module, then the go command should know which version of your module is in use and embed that in the resulting binary:

go.mod :

module example.com/other

require test.org/simple v0.1.0

go build test.org/simple && ./simple

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM