From afc0c0f02177d56d1c6f47fad6b5ffdead79e8fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miloslav=20Trma=C4=8D?= Date: Thu, 13 Feb 2025 00:55:44 +0100 Subject: [PATCH] Rely on Go-maintained commit value instead of handling that ourselves MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Should not change behavior Signed-off-by: Miloslav Trmač --- Makefile | 4 +--- cmd/skopeo/main.go | 25 +++++++++++++++++++------ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/Makefile b/Makefile index ebfd2e7a..4fd12949 100644 --- a/Makefile +++ b/Makefile @@ -81,10 +81,8 @@ endif CONTAINER_GOSRC = /src/github.com/containers/skopeo CONTAINER_RUN ?= $(CONTAINER_CMD) --security-opt label=disable -v $(CURDIR):$(CONTAINER_GOSRC) -w $(CONTAINER_GOSRC) $(SKOPEO_CIDEV_CONTAINER_FQIN) -GIT_COMMIT := $(shell GIT_CEILING_DIRECTORIES=$$(cd ..; pwd) git rev-parse HEAD 2> /dev/null || true) - EXTRA_LDFLAGS ?= -SKOPEO_LDFLAGS := -ldflags '-X main.gitCommit=${GIT_COMMIT} $(EXTRA_LDFLAGS)' +SKOPEO_LDFLAGS := -ldflags '$(EXTRA_LDFLAGS)' MANPAGES_MD = $(wildcard docs/*.md) MANPAGES ?= $(MANPAGES_MD:%.md=%) diff --git a/cmd/skopeo/main.go b/cmd/skopeo/main.go index 13670687..36bdecb8 100644 --- a/cmd/skopeo/main.go +++ b/cmd/skopeo/main.go @@ -3,6 +3,7 @@ package main import ( "context" "fmt" + "runtime/debug" "strings" "time" @@ -15,10 +16,6 @@ import ( "go.podman.io/storage/pkg/reexec" ) -// gitCommit will be the hash that the binary was built from -// and will be populated by the Makefile -var gitCommit = "" - var defaultUserAgent = "skopeo/" + version.Version type globalOptions struct { @@ -70,8 +67,10 @@ func createApp() (*cobra.Command, *globalOptions) { // (skopeo --tls-verify inspect) (causes a warning) and (skopeo inspect --tls-verify) (no warning). TraverseChildren: true, } - if gitCommit != "" { - rootCommand.Version = fmt.Sprintf("%s commit: %s", version.Version, gitCommit) + // We don’t use debug.ReadBuildInfo to automate version.Version, because that would not work well for builds from + // a released tarball (e.g. RPM builds). + if commit := gitCommit(); commit != "" { + rootCommand.Version = fmt.Sprintf("%s commit: %s", version.Version, commit) } else { rootCommand.Version = version.Version } @@ -112,6 +111,20 @@ func createApp() (*cobra.Command, *globalOptions) { return rootCommand, &opts } +// gitCommit returns the git commit for this codebase, if we are built from a git repo; "" otherwise. +func gitCommit() string { + bi, ok := debug.ReadBuildInfo() + if !ok { + logrus.Fatal("runtime.ReadBuildInfo failed") + } + for _, e := range bi.Settings { + if e.Key == "vcs.revision" { + return e.Value + } + } + return "" +} + // before is run by the cli package for any command, before running the command-specific handler. func (opts *globalOptions) before(cmd *cobra.Command, args []string) error { if opts.debug {