main: --version includes git commit

Include the commit of the build (if available in the build environment),
also include the version of `images` in the build; if available.

Signed-off-by: Simon de Vlieger <supakeen@redhat.com>
This commit is contained in:
Simon de Vlieger 2025-06-23 08:36:41 +02:00
parent f52041ab67
commit 3021afb9f7
3 changed files with 71 additions and 5 deletions

View file

@ -28,9 +28,8 @@ import (
)
var (
osStdout io.Writer = os.Stdout
osStderr io.Writer = os.Stderr
BuildVersion = "DEVEL"
osStdout io.Writer = os.Stdout
osStderr io.Writer = os.Stderr
)
// basenameFor returns the basename for directory and filenames
@ -423,11 +422,13 @@ image-type and blueprint.
Image-builder builds operating system images for a range of predefined
operating systems like Fedora, CentOS and RHEL with easy customizations support.`,
SilenceErrors: true,
Version: BuildVersion,
Version: prettyVersion(),
CompletionOptions: cobra.CompletionOptions{
HiddenDefaultCmd: true,
},
}
rootCmd.SetVersionTemplate(prettyVersion())
rootCmd.PersistentFlags().String("data-dir", "", `Override the default data directory for e.g. custom repositories/*.json data`)
rootCmd.PersistentFlags().StringArray("extra-repo", nil, `Add an extra repository during build (will *not* be gpg checked and not be part of the final image)`)
rootCmd.PersistentFlags().StringArray("force-repo", nil, `Override the base repositories during build (these will not be part of the final image)`)

View file

@ -0,0 +1,65 @@
package main
import (
"runtime/debug"
"strings"
"gopkg.in/yaml.v3"
)
// Usually set by whatever is building the binary with a `-x main.version=22`, for example
// in `make build`.
var version = "unknown"
type versionDescription struct {
ImageBuilder struct {
Version string `yaml:"version"`
Commit string `yaml:"commit"`
Dependencies struct {
Images string `yaml:"images"`
} `yaml:"dependencies"`
} `yaml:"image-builder"`
}
func readVersionFromBinary() *versionDescription {
// We'll be getting these values from the build info if they're available, otherwise
// they will always be set to unknown. Note that `version` is set globally so it can
// be defined by whatever is building this project.
commit := "unknown"
images := "unknown"
if bi, ok := debug.ReadBuildInfo(); ok {
for _, bs := range bi.Settings {
switch bs.Key {
case "vcs.revision":
commit = bs.Value
}
}
for _, dep := range bi.Deps {
if dep.Path == "github.com/osbuild/images" {
images = dep.Version
}
}
}
vd := &versionDescription{}
vd.ImageBuilder.Version = version
vd.ImageBuilder.Commit = commit
vd.ImageBuilder.Dependencies.Images = images
return vd
}
func prettyVersion() string {
var b strings.Builder
enc := yaml.NewEncoder(&b)
enc.SetIndent(2)
enc.Encode(readVersionFromBinary())
return b.String()
}