From c728e031df92115cea14099b1c672c07f4d14ff3 Mon Sep 17 00:00:00 2001 From: Ayke van Laethem Date: Sun, 3 Nov 2024 10:03:56 +0100 Subject: [PATCH] goenv: read git hash embedded in the binary The git hash that's part of `tinygo version` is now read from the binary itself instead of embedding it with a `-ldflags` flag. This means it is also present when building TinyGo using `go build` or `go install`. --- GNUmakefile | 2 +- goenv/version.go | 24 ++++++++++++++++-------- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/GNUmakefile b/GNUmakefile index 155f5c5d5..e66b6af29 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -291,7 +291,7 @@ endif tinygo: ## Build the TinyGo compiler @if [ ! -f "$(LLVM_BUILDDIR)/bin/llvm-config" ]; then echo "Fetch and build LLVM first by running:"; echo " $(MAKE) llvm-source"; echo " $(MAKE) $(LLVM_BUILDDIR)"; exit 1; fi - CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GOENVFLAGS) $(GO) build -buildmode exe -o build/tinygo$(EXE) -tags "byollvm osusergo" -ldflags="-X github.com/tinygo-org/tinygo/goenv.GitSha1=`git rev-parse --short HEAD`" . + CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GOENVFLAGS) $(GO) build -buildmode exe -o build/tinygo$(EXE) -tags "byollvm osusergo" . test: wasi-libc check-nodejs-version CGO_CPPFLAGS="$(CGO_CPPFLAGS)" CGO_CXXFLAGS="$(CGO_CXXFLAGS)" CGO_LDFLAGS="$(CGO_LDFLAGS)" $(GO) test $(GOTESTFLAGS) -timeout=1h -buildmode exe -tags "byollvm osusergo" $(GOTESTPKGS) diff --git a/goenv/version.go b/goenv/version.go index 5b71820f2..158c3caf2 100644 --- a/goenv/version.go +++ b/goenv/version.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "io" + "runtime/debug" "strings" ) @@ -11,22 +12,29 @@ import ( // Update this value before release of new version of software. const version = "0.35.0-dev" -var ( - // This variable is set at build time using -ldflags parameters. - // See: https://stackoverflow.com/a/11355611 - GitSha1 string -) - // Return TinyGo version, either in the form 0.30.0 or as a development version // (like 0.30.0-dev-abcd012). func Version() string { v := version - if strings.HasSuffix(version, "-dev") && GitSha1 != "" { - v += "-" + GitSha1 + if strings.HasSuffix(version, "-dev") { + if hash := readGitHash(); hash != "" { + v += "-" + hash + } } return v } +func readGitHash() string { + if info, ok := debug.ReadBuildInfo(); ok { + for _, setting := range info.Settings { + if setting.Key == "vcs.revision" { + return setting.Value[:8] + } + } + } + return "" +} + // GetGorootVersion returns the major and minor version for a given GOROOT path. // If the goroot cannot be determined, (0, 0) is returned. func GetGorootVersion() (major, minor int, err error) {