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.
This commit is contained in:
Conner Fromknecht 2020-04-09 17:04:11 -07:00
parent 640aadb61a
commit b68764f86c
No known key found for this signature in database
GPG Key ID: E7D737B67FA592C7

@ -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()
}