From b68764f86c4c14056e2e8aa3763d32307e88cff3 Mon Sep 17 00:00:00 2001 From: Conner Fromknecht Date: Thu, 9 Apr 2020 17:04:11 -0700 Subject: [PATCH] build/version: check AppPreRelease semantics in init() We'll do the validation during construction of the runtime so that we can safely use the AppPreRelease field externally without needing to normalize it. --- build/version.go | 40 ++++++++++++++++++---------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/build/version.go b/build/version.go index 855d9127c..4985ed6cc 100644 --- a/build/version.go +++ b/build/version.go @@ -6,7 +6,6 @@ package build import ( - "bytes" "fmt" "strings" ) @@ -36,19 +35,30 @@ const ( AppPreRelease = "beta" ) +func init() { + // Assert that AppPreRelease is valid according to the semantic + // versioning guidelines for pre-release version and build metadata + // strings. In particular it MUST only contain characters in + // semanticAlphabet. + for _, r := range AppPreRelease { + if !strings.ContainsRune(semanticAlphabet, r) { + panic(fmt.Errorf("rune: %v is not in the semantic "+ + "alphabet", r)) + } + } +} + // Version returns the application version as a properly formed string per the // semantic versioning 2.0.0 spec (http://semver.org/). func Version() string { // Start with the major, minor, and patch versions. version := fmt.Sprintf("%d.%d.%d", AppMajor, AppMinor, AppPatch) - // Append pre-release version if there is one. The hyphen called for - // by the semantic versioning spec is automatically appended and should - // not be contained in the pre-release string. The pre-release version - // is not appended if it contains invalid characters. - preRelease := normalizeVerString(AppPreRelease) - if preRelease != "" { - version = fmt.Sprintf("%s-%s", version, preRelease) + // Append pre-release version if there is one. The hyphen called for by + // the semantic versioning spec is automatically appended and should not + // be contained in the pre-release string. + if AppPreRelease != "" { + version = fmt.Sprintf("%s-%s", version, AppPreRelease) } // Append commit hash of current build to version. @@ -56,17 +66,3 @@ func Version() string { return version } - -// normalizeVerString returns the passed string stripped of all characters which -// are not valid according to the semantic versioning guidelines for pre-release -// version and build metadata strings. In particular they MUST only contain -// characters in semanticAlphabet. -func normalizeVerString(str string) string { - var result bytes.Buffer - for _, r := range str { - if strings.ContainsRune(semanticAlphabet, r) { - result.WriteRune(r) - } - } - return result.String() -}