internal/buildinfo/buildinfo.go

v1.27.0
gitbay/internal/buildinfo/buildinfo.go history · blame · raw

56 lines · 1506 bytes

 1// Package buildinfo reports which commit a binary was built from, so a
 2// deployed artifact can state its provenance instead of needing a rebuild and
 3// a hash comparison to infer it.
 4package buildinfo
 5
 6import (
 7	"runtime/debug"
 8	"strings"
 9)
10
11// Commit is stamped at link time by the Makefile:
12//
13//	-X gitbay.org/gitbay/internal/buildinfo.Commit=<sha>
14//
15// It carries a -dirty suffix when the tree was not clean, which only happens
16// under ALLOW_DIRTY=1 since preflight otherwise refuses to build.
17var Commit string
18
19// String returns the build's commit. A binary built by hand rather than by the
20// Makefile has no stamp, so fall back to the revision the toolchain embeds;
21// that one is absent too when the build ran outside a checkout.
22func String() string {
23	if Commit != "" {
24		return Commit
25	}
26	info, ok := debug.ReadBuildInfo()
27	if !ok {
28		return "unknown"
29	}
30	var rev, modified string
31	for _, s := range info.Settings {
32		switch s.Key {
33		case "vcs.revision":
34			rev = s.Value
35		case "vcs.modified":
36			if s.Value == "true" {
37				modified = "-dirty"
38			}
39		}
40	}
41	if rev == "" {
42		return "unknown"
43	}
44	if len(rev) > 12 {
45		rev = rev[:12]
46	}
47	return rev + modified
48}
49
50// Identified reports whether this build can be traced back to a commit that
51// exists in history. A dirty or missing stamp means it cannot: the tree it was
52// built from was never committed, so nothing can say what is running.
53func Identified() bool {
54	s := String()
55	return s != "unknown" && !strings.HasSuffix(s, "-dirty")
56}