genversioninfo
genversioninfo is a Go module designed to be used with go generate to automatically gather build metadata (Git tags, hashes, Go version, etc.) and generate version information for your application.
Features
- Generates Go files with version constants (no runtime parsing)
- Supports Cobra CLI integration (
cmd/version.go)
- Supports plain Go version file (
version/version.go)
- Supports internal package version file (
internal/version/version.go)
- Secure git command execution with
safeexec
- HMAC-SHA256 build hash for unique build identification
Installation
go get github.com/inovacc/genversioninfo
Usage
Simple API
//go:build ignore
package main
import "github.com/inovacc/genversioninfo"
func main() {
// Generate Cobra-integrated cmd/version.go
genversioninfo.GenWithCobraCLI()
// Generate plain version/version.go
genversioninfo.GenWithRawVersion()
// Generate internal/version/version.go
genversioninfo.GenWithInternalVersion()
}
1. Create a generator script
Create scripts/genversion.go in your project:
//go:build ignore
package main
import "github.com/inovacc/genversioninfo"
func main() {
if err := genversioninfo.GenWithCobraCLI(); err != nil {
panic(err)
}
}
2. Add go:generate directive
Add to your main.go:
//go:generate go run scripts/genversion.go
3. Run the generator
go generate ./...
Generated Files
| Function |
File Generated |
GenWithCobraCLI() |
cmd/version.go (Cobra) |
GenWithRawVersion() |
version/version.go (plain) |
GenWithInternalVersion() |
internal/version/version.go (plain) |
Generated Command
With GenWithCobraCLI(), use the version command:
yourapp version
Output:
Version: v1.0.0
Git Hash: a1b2c3d4e5f6...
Build Time: 2023-10-27T10:00:00Z
Build Hash: 8e1c858269c4...
Go Version: go1.21.3
OS/Arch: linux/amd64
JSON output:
yourapp version --json
How it works
- Version: Reads from git tag (
git describe --tags) or falls back to dev
- Git Hash: From
git rev-parse HEAD
- Build Hash: HMAC-SHA256 hash of all metadata for unique build identification
- Constants: All version info is generated as Go constants at generation time
Examples
See the example/ directory:
example/cobra/ - Cobra CLI integration (cmd/version.go)
example/raw/ - Plain version file (version/version.go)
example/internal/ - Internal package version (internal/version/version.go)
Roadmap
- Add support for custom output paths
- Add support for custom package names in generated files
- Add
ldflags injection support as alternative to embed
- Add support for monorepo (multiple VERSION files)
- Add pre-commit hook integration
- Add GitHub Actions workflow template
License
MIT License - see LICENSE