extract VCS branch name used during build

246 views
Skip to first unread message

quin...@gmail.com

unread,
Feb 6, 2023, 10:48:43 AM2/6/23
to golang-nuts

Hi,

I would like to be able to extract the VCS branch name used during build.
Currently I append "-X main.BranchName=${BRANCH}" to the build line which works, but I was hoping there might be a cunning way to extract this from runtime/debug?

Thanks,

-Steve

Chris Burkert

unread,
Feb 6, 2023, 12:33:53 PM2/6/23
to quin...@gmail.com, golang-nuts
You can use go:generate and go:embed to achieve this. In our CI/CD pipeline we generate a json file with a lot of information like vcs, branch, tag, date and time, hash and a lot more. Then we embed this json into the binary.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/6f0a10e1-f818-4b98-8384-3fe925ec69dcn%40googlegroups.com.

Duncan Harris

unread,
Feb 6, 2023, 7:23:12 PM2/6/23
to golang-nuts
Do you really need the branch? You get the commit hash for free since Go 1.18 : https://tip.golang.org/doc/go1.18#go-version
You can see the embedded version information with: go version -m <executable_file>

Tobias Klausmann

unread,
Feb 7, 2023, 11:37:16 AM2/7/23
to golan...@googlegroups.com
Hi!
Indeed there is. On top of the already mentioned approaches using go
generate, the runtime/debug package:

```
import "runtime/debug"

var Commit = func() string {
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" {
return setting.Value
}
}
}
return ""
}()
```

(shamelessly stolen from
https://icinga.com/blog/2022/05/25/embedding-git-commit-information-in-go-binaries/)

HTH,
Tobias

quin...@gmail.com

unread,
Feb 8, 2023, 5:35:07 AM2/8/23
to golang-nuts

Thanks for the ideas all, I think go embed is the best path for me.

runtime/debug will give me the revision but sadly it can't give me the branch.

I want the branch as we run a microservice architecture and seeing that all the microservices are running
the release branch and not master (or main) is a useful cross check for our QA dept; we have had cases of
them spending time checking development code which is - well, imperfect.

-Steve
Reply all
Reply to author
Forward
0 new messages