git » gofer » commit 08c2d29

debug: Get build info from Go's runtime/debug package

author Alberto Bertogli
2022-12-28 03:36:56 UTC
committer Alberto Bertogli
2023-01-22 21:56:59 UTC
parent 3aff609677230f8a191be446363845fb0fd6126a

debug: Get build info from Go's runtime/debug package

Since Go 1.18, build-time VCS information is available via the
runtime/debug package.

This patch makes use of it to simplify the build, so we get more useful
version strings by default.

Makefile +4 -8
debug/debug.go +44 -6
go.mod +1 -1

diff --git a/Makefile b/Makefile
index 9de8e1c..023c5a5 100644
--- a/Makefile
+++ b/Makefile
@@ -1,14 +1,10 @@
 
-ifndef VERSION
-    VERSION = `git describe --always --long --dirty`
-endif
+default: gofer
 
+# Pass version and source date info if available on the $VERSION and
+# $SOURCE_DATE_EPOCH environment variables; we will get them from Go's build
+# info infrastructure otherwise.
 # https://wiki.debian.org/ReproducibleBuilds/TimestampsProposal
-ifndef SOURCE_DATE_EPOCH
-    SOURCE_DATE_EPOCH = `git log -1 --format=%ct`
-endif
-
-default: gofer
 
 gofer:
 	go build -ldflags="\
diff --git a/debug/debug.go b/debug/debug.go
index 26cddab..6c072b1 100644
--- a/debug/debug.go
+++ b/debug/debug.go
@@ -1,10 +1,12 @@
 package debug
 
 import (
+	"fmt"
 	"html/template"
 	"net/http"
 	"os"
 	"runtime"
+	"runtime/debug"
 	"strconv"
 	"time"
 
@@ -19,8 +21,8 @@ import (
 // Build information, overridden at build time using
 // -ldflags="-X blitiri.com.ar/go/gofer/debug.Version=blah".
 var (
-	Version      = "undefined"
-	SourceDateTs = "0"
+	Version      = ""
+	SourceDateTs = ""
 
 	// Derived from SourceDateTs.
 	SourceDate    = time.Time{}
@@ -28,13 +30,49 @@ var (
 )
 
 func init() {
-	sdts, err := strconv.ParseInt(SourceDateTs, 10, 0)
-	if err != nil {
-		panic(err)
+	bi, ok := debug.ReadBuildInfo()
+	if !ok {
+		panic("unable to read build info")
 	}
 
-	SourceDate = time.Unix(sdts, 0)
+	dirty := false
+	gitRev := ""
+	gitTime := ""
+	for _, s := range bi.Settings {
+		switch s.Key {
+		case "vcs.modified":
+			if s.Value == "true" {
+				dirty = true
+			}
+		case "vcs.time":
+			gitTime = s.Value
+		case "vcs.revision":
+			gitRev = s.Value
+		}
+	}
+
+	if SourceDateTs != "" {
+		sdts, err := strconv.ParseInt(SourceDateTs, 10, 0)
+		if err != nil {
+			panic(err)
+		}
+
+		SourceDate = time.Unix(sdts, 0)
+	} else {
+		SourceDate, _ = time.Parse(time.RFC3339, gitTime)
+	}
 	SourceDateStr = SourceDate.Format("2006-01-02 15:04:05 -0700")
+
+	if Version == "" {
+		Version = SourceDate.Format("20060102")
+
+		if gitRev != "" {
+			Version += fmt.Sprintf("-%.9s", gitRev)
+		}
+		if dirty {
+			Version += "-dirty"
+		}
+	}
 }
 
 func ServeDebugging(addr string, conf *config.Config) error {
diff --git a/go.mod b/go.mod
index b82f90b..a2779e3 100644
--- a/go.mod
+++ b/go.mod
@@ -1,6 +1,6 @@
 module blitiri.com.ar/go/gofer
 
-go 1.17
+go 1.18
 
 require (
 	blitiri.com.ar/go/log v1.1.0