From 1c9530a18801585cf855c6acce84a3cc4ab5493e Mon Sep 17 00:00:00 2001 From: James Bowes Date: Sat, 11 Sep 2021 07:29:58 -0300 Subject: [PATCH] Add a prerelease method to version This method returns the joined components of the prerelease field. It's intended use is really to see if there is a prerelease or not, so a bool could also work, possibly. --- version.go | 13 +++++++++++++ version_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/version.go b/version.go index 46aa291..9fe7442 100644 --- a/version.go +++ b/version.go @@ -144,3 +144,16 @@ func (v *buildlessVersion) comparePre(other *Version) int { // build is not used for semver comparison. } + +// Prerelease returns the prerelease portion of a Version. If the version had +// no prerelease or is nil, the empty string is returned. +// +// Note: This method is considered experimental, and may be removed or changed +// before v1.0.0 +func (v *Version) Prerelease() string { + if v == nil { + return "" + } + + return strings.Join(v.pre, ".") +} diff --git a/version_test.go b/version_test.go index 2a674de..db44af7 100644 --- a/version_test.go +++ b/version_test.go @@ -181,3 +181,29 @@ func TestCompare_nil(t *testing.T) { t.Errorf("two nil versions are not equal") } } + +func TestVersion_Prerelease(t *testing.T) { + mustParse := func(s string) *semver.Version { + v, _ := semver.Parse(s) + return v + } + + tcs := map[string]struct { + in *semver.Version + out string + }{ + "no prerelease": {mustParse("1.0.0"), ""}, + "prerelease": {mustParse("1.0.0-alpha"), "alpha"}, + "multi-part prerelease": {mustParse("1.0.0-rc.0"), "rc.0"}, + "nil version": {nil, ""}, + } + + for name, tc := range tcs { + t.Run(name, func(t *testing.T) { + out := tc.in.Prerelease() + if out != tc.out { + t.Error("bad prerelease. got:", out, "wanted:", tc.out) + } + }) + } +}