github.com/grafana/synthetic-monitoring-agent@v0.64.2/internal/version/version.go (about) 1 // Copyright (C) 2025 Grafana Labs. 2 // SPDX-License-Identifier: AGPL-3.0-only 3 4 package version 5 6 import ( 7 "fmt" 8 "path/filepath" 9 "runtime" 10 "runtime/debug" 11 "slices" 12 "strings" 13 "sync" 14 ) 15 16 const ( 17 revisionKey = "vcs.revision" 18 timeKey = "vcs.time" 19 smHomepage = "https://github.com/grafana/synthetic-monitoring-agent" 20 ) 21 22 func Short() string { 23 bi := getBuildInfo() 24 25 return bi.Main.Version 26 } 27 28 func Commit() string { 29 return getBuildInfoByKey(revisionKey) 30 } 31 32 func Buildstamp() string { 33 return getBuildInfoByKey(timeKey) 34 } 35 36 func UserAgent() string { 37 return userAgentStr() 38 } 39 40 func getBuildInfoByKey(key string) string { 41 bi := getBuildInfo() 42 if bi == nil { 43 return "invalid" 44 } 45 46 idx, found := slices.BinarySearchFunc(bi.Settings, key, isKey) 47 if found { 48 return bi.Settings[idx].Value 49 } 50 51 return "unknown" 52 } 53 54 //nolint:gochecknoglobals // This variable is only accessed in this package. 55 var getBuildInfo = sync.OnceValue(func() *debug.BuildInfo { 56 bi, ok := debug.ReadBuildInfo() 57 if !ok { 58 return nil 59 } 60 61 slices.SortFunc(bi.Settings, cmpBuildSettings) 62 63 return bi 64 }) 65 66 var userAgentStr = sync.OnceValue(func() string { 67 bi := getBuildInfo() 68 69 program := filepath.Base(bi.Path) 70 71 return fmt.Sprintf("%s/%s (%s %s; %s; %s; +%s)", program, Short(), runtime.GOOS, runtime.GOARCH, Commit(), Buildstamp(), smHomepage) 72 }) 73 74 func cmpBuildSettings(a, b debug.BuildSetting) int { 75 if v := strings.Compare(a.Key, b.Key); v != 0 { 76 return v 77 } 78 79 return strings.Compare(a.Value, b.Value) 80 } 81 82 func isKey(a debug.BuildSetting, key string) int { 83 return strings.Compare(a.Key, key) 84 }