From 99a8875d3e4e6800621331973012ded332674e27 Mon Sep 17 00:00:00 2001 From: Timothy Messier Date: Thu, 2 Feb 2023 16:32:19 +0000 Subject: [PATCH] feat(version): Determine binary version during initalization This ensures that checks for features should work, and bails early if that is not the case, since if this fails the binary is essentially broken. This also simplifies code that performs these checks, ie instead of: binaryVersion, err := version.GetReleaseVersion() if err != nil { // handle error? panic? } if version.SupportsFeature(binaryVersion, version.FeatureA) { // code for FeatureA } else { // without FeatureA } Implementations can do: if version.SupportsFeature(version.Binary, version.FeatureA) { // code for FeatureA } else { // without FeatureA } --- version/feature_manager.go | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/version/feature_manager.go b/version/feature_manager.go index 32f48a1589..8995c73dcc 100644 --- a/version/feature_manager.go +++ b/version/feature_manager.go @@ -27,16 +27,29 @@ const ( var featureMap map[Feature]MetadataConstraint +// Binary is the version of the running binary. +// This can be used for feature checks. +var Binary *gvers.Version + func init() { + // Do this early to ensure version is valid, if this panics something is + // very broken with the version and any version checks based on the binary's + // version info will not work correctly. Also do this once since the version + // can't change while running. + var err error + Binary, err = GetReleaseVersion() + if err != nil { + panic(err) + } + if featureMap == nil { featureMap = make(map[Feature]MetadataConstraint) } /* Add constraints here following this format after adding a Feature to the Feature iota: - featureConstraint, err := gvers.NewConstraint(">= 0.1.0") // This feature exists at 0.1.0 and above featureMap[FEATURE] = MetadataConstraint{ MetaInfo: []Metadata{OSS, HCP}, - Constraints: featureConstraint, + Constraints: mustNewConstraints(">= 0.1.0"), // This feature exists at 0.1.0 and above } */ } @@ -49,6 +62,14 @@ func metadataStringToMetadata(m string) Metadata { return OSS } +func mustNewConstraints(v string) gvers.Constraints { + c, err := gvers.NewConstraint(v) + if err != nil { + panic(err) + } + return c +} + // Check returns a bool indicating if a version meets the metadata constraint // for a feature. Check returns false if version is nil. func (m MetadataConstraint) Check(version *gvers.Version) bool {