diff --git a/util.go b/util.go index e5717c631..47f814850 100644 --- a/util.go +++ b/util.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "os" + "runtime/debug" "strings" "time" @@ -66,6 +67,13 @@ func defaultRelease() (release string) { } } + if info, ok := debug.ReadBuildInfo(); ok { + buildInfoVcsRevision := revisionFromBuildInfo(info) + if len(buildInfoVcsRevision) > 0 { + return buildInfoVcsRevision + } + } + // Derive a version string from Git. Example outputs: // v1.0.1-0-g9de4 // v2.0-8-g77df-dirty @@ -89,3 +97,14 @@ func defaultRelease() (release string) { Logger.Printf("Using release from Git: %s", release) return release } + +func revisionFromBuildInfo(info *debug.BuildInfo) string { + for _, setting := range info.Settings { + if setting.Key == "vcs.revision" && setting.Value != "" { + Logger.Printf("Using release from debug info: %s", setting.Value) + return setting.Value + } + } + + return "" +} diff --git a/util_test.go b/util_test.go index 409e91f4e..e6a5568fb 100644 --- a/util_test.go +++ b/util_test.go @@ -1,6 +1,7 @@ package sentry import ( + "runtime/debug" "testing" ) @@ -27,3 +28,66 @@ func TestFileExistsReturnsFalseForNonExistingFiles(t *testing.T) { assertEqual(t, fileExists(("util_nope.go")), false) assertEqual(t, fileExists(("util_nope_test.go")), false) } + +func TestDefaultReleaseSentryReleaseEnvvar(t *testing.T) { + releaseVersion := "1.2.3" + t.Setenv("SENTRY_RELEASE", releaseVersion) + + assertEqual(t, defaultRelease(), releaseVersion) +} + +func TestDefaultReleaseSentryReleaseEnvvarPrecedence(t *testing.T) { + releaseVersion := "1.2.3" + t.Setenv("SOURCE_VERSION", "3.2.1") + t.Setenv("SENTRY_RELEASE", releaseVersion) + + assertEqual(t, defaultRelease(), releaseVersion) +} + +func TestRevisionFromBuildInfo(t *testing.T) { + releaseVersion := "deadbeef" + + info := &debug.BuildInfo{ + Main: debug.Module{ + Path: "my/module", + Version: "(devel)", + }, + Deps: []*debug.Module{ + { + Path: "github.com/getsentry/sentry-go", + Version: "v0.23.1", + Replace: &debug.Module{ + Path: "pkg/sentry", + }, + }, + }, + Settings: []debug.BuildSetting{ + { + Key: "vcs.revision", + Value: releaseVersion, + }, + }, + } + + assertEqual(t, revisionFromBuildInfo(info), releaseVersion) +} + +func TestRevisionFromBuildInfoNoVcsInformation(t *testing.T) { + info := &debug.BuildInfo{ + Main: debug.Module{ + Path: "my/module", + Version: "(devel)", + }, + Deps: []*debug.Module{ + { + Path: "github.com/getsentry/sentry-go", + Version: "v0.23.1", + Replace: &debug.Module{ + Path: "pkg/sentry", + }, + }, + }, + } + + assertEqual(t, revisionFromBuildInfo(info), "") +}