Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 43 additions & 4 deletions internal/cli/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,54 @@ import (
"fmt"
"io"
"runtime"
"runtime/debug"
)

// Set via -ldflags "-X github.com/plinth-dev/cli/internal/cli.Version=..." at build.
// Set via -ldflags "-X github.com/plinth-dev/cli/internal/cli.Version=..." at
// build (see Makefile). When unset — e.g. when the user installs via
// `go install ...@v0.1.0` — runtime/debug.ReadBuildInfo provides the module
// version and VCS revision Go's toolchain stamped into the binary.
var (
Version = "dev"
Commit = "none"
Version = ""
Commit = ""
)

func runVersion(stdout io.Writer) int {
fmt.Fprintf(stdout, "plinth %s (commit %s, %s)\n", Version, Commit, runtime.Version())
v, c := resolveVersion(Version, Commit)
fmt.Fprintf(stdout, "plinth %s (commit %s, %s)\n", v, c, runtime.Version())
return 0
}

func resolveVersion(version, commit string) (string, string) {
if version != "" && commit != "" {
return version, commit
}
info, ok := debug.ReadBuildInfo()
if !ok {
return fallback(version, "dev"), fallback(commit, "none")
}
if version == "" {
if v := info.Main.Version; v != "" && v != "(devel)" {
version = v
}
}
if commit == "" {
for _, s := range info.Settings {
if s.Key == "vcs.revision" && s.Value != "" {
commit = s.Value
if len(commit) > 12 {
commit = commit[:12]
}
break
}
}
}
return fallback(version, "dev"), fallback(commit, "none")
}

func fallback(s, def string) string {
if s == "" {
return def
}
return s
}
19 changes: 19 additions & 0 deletions internal/cli/version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,22 @@ func TestVersionPrints(t *testing.T) {
t.Errorf("missing commit: %s", got)
}
}

func TestResolveVersionPrefersExplicit(t *testing.T) {
v, c := resolveVersion("0.2.0", "deadbeef")
if v != "0.2.0" || c != "deadbeef" {
t.Errorf("explicit args lost: v=%q c=%q", v, c)
}
}

func TestResolveVersionFallback(t *testing.T) {
// In `go test` runs, debug.ReadBuildInfo reports Main.Version="(devel)"
// and no vcs.revision setting, so both should land on the dev/none defaults.
v, c := resolveVersion("", "")
if v != "dev" {
t.Errorf("unset version did not fall back to dev: %q", v)
}
if c == "" {
t.Errorf("commit must not be empty after fallback")
}
}
Loading