livebud / bud

The Full-Stack Web Framework for Go
MIT License
5.53k stars 181 forks source link

feature idea: detect git short version hash during build and embed into binary #332

Open sneak opened 1 year ago

sneak commented 1 year ago

In my apps I usually do something like:

var Version   string

func main() {
    os.Exit(httpserver.Run(Version))
}

Then at build time (in my Makefile) I do this:

VERSION := $(shell git describe --always --dirty=-dirty)
GOLDFLAGS += -X main.Version=$(VERSION)
GOFLAGS := -ldflags "$(GOLDFLAGS)"

This embeds the version string into the app so that I can access it, which is useful for me because then in production I can access this value and put it in my footers and error messages so that I know precisely which commit is running.

It would be cool if bud build could detect if it's building out of a git repo, and embed the git shorthash into the built binary in this way. It seems that you could skip the ldflags part and simply "hardcode" the git shorthash into the main.go via the main.gotext template at build filesystem generation time.

Anyway, just an idea, and I'm happy to take a crack at making a patch for this when I have some time, I just wanted to write it down while it's in my head.

matthewmueller commented 1 year ago

Thanks for raising this feature request @sneak. I think it's a good idea. Two potential solutions:

  1. Add a package to one of the bud packages that's could be accessed at runtime. Perhaps github.com/livebud/bud/package/version, then the builder automatically adds the -ldflags to target that package. As a user, you could import that runtime package in your controller and use it.
  2. Support passing Go flags into bud build, so you could do bud build -- -ldflags="...". We may want to improve this API, but at the very least you could pass raw Go flags in. Then you're responsible for creating your own hash package that you'd target with the ldflags.

I'm leaning towards 1. since it's more automatic for the developer. I think 2. would need to be possible too though, at least passing in raw flags into Go.

syke99 commented 1 year ago

Hey @matthewmueller I wouldn't mind knocking this out. 1 should be more than simple enough. However, do you have any input for tackling 2? It's been a minute since I've looked at the bud codebase, so I gave it a cursory glance and noticed internal/cli/build/build.go directory. Gave that a quick look and noticed Command has the field Flag of *framework.Flag type. Would this be the appropriate jumping off point or do you have any pointers of where I should look if this isn't the right spot?