Skip to content

Commit

Permalink
main: use VERSION file as fallback for version reporting (#614)
Browse files Browse the repository at this point in the history
Currently, if Alloy was built without setting build information, it
reports its version as "v0.0.0".

This commit adds using the VERSION file as fallback, so if the version
information wasn't present (such as when ussing `go run .`), the
reported version is taken from the VERSION file at the root of the
repository.

The version reported is then appended with `-devel` to indicate that it
is not the final release.

For example, as the VERSION file currently contains `v1.1.0`, then the
fallback reported version will be `v1.1.0-devel`.
  • Loading branch information
rfratto authored Apr 22, 2024
1 parent cf30906 commit 2509c15
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
38 changes: 38 additions & 0 deletions fallback_version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"bufio"
"bytes"
_ "embed"
"strings"

"github.com/grafana/alloy/internal/build"
)

//go:embed VERSION
var fallbackVersionText []byte

// fallbackVersion returns a version string to use for when the version isn't
// explicitly set at build time. The version string will always have -devel
// appended to it.
func fallbackVersion() string {
return fallbackVersionFromText(fallbackVersionText)
}

func fallbackVersionFromText(text []byte) string {
// Find the first line in fallbackVersionText which isn't a blank line or a
// line starting with #.
scanner := bufio.NewScanner(bytes.NewReader(text))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if len(line) == 0 || strings.HasPrefix(line, "#") {
continue
}

return line + "-devel"
}

// We shouldn't hit this case since we always control the contents of the
// VERSION file, but just in case we'll return the existing version.
return build.Version
}
20 changes: 20 additions & 0 deletions fallback_version_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package main

import (
"testing"

"github.com/stretchr/testify/require"
)

func Test_fallbackVersionFromText(t *testing.T) {
in := `# This is a comment
# This is another comment
v1.2.3
This line is ignored!`
expect := "v1.2.3-devel"

actual := fallbackVersionFromText([]byte(in))
require.Equal(t, expect, actual)
}
6 changes: 6 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ import (
)

func init() {
// If the build version wasn't set by the build process, we'll set it based
// on the version string in VERSION.
if build.Version == "" || build.Version == "v0.0.0" {
build.Version = fallbackVersion()
}

prometheus.MustRegister(build.NewCollector("alloy"))
}

Expand Down

0 comments on commit 2509c15

Please sign in to comment.