Debian Codegraph @

internal/semver/semver.go

raw
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package semver provides functions related to semanic version.
15 // This package is based on "golang.org/x/mod/semver"
16 package semver
17
18 import (
19 "fmt"
20 "regexp"
21
22 "golang.org/x/mod/semver"
23 )
24
25 // semVerRegEx is taken from https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
26 var semVerRegEx = regexp.MustCompile(`^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$`)
27
28 // IsValid returns true if version is a valid semantic version
29 func IsValid(version string) bool {
30 return semVerRegEx.MatchString(version)
31 }
32
33 // ComparePluginVersion validates and compares two plugin semantic versions.
34 //
35 // The result will be 0 if v == w, -1 if v < w, or +1 if v > w.
36 func ComparePluginVersion(v, w string) (int, error) {
37 // sanity check
38 if !IsValid(v) {
39 return 0, fmt.Errorf("%s is not a valid semantic version", v)
40 }
41 if !IsValid(w) {
42 return 0, fmt.Errorf("%s is not a valid semantic version", w)
43 }
44
45 // golang.org/x/mod/semver requires semantic version strings must begin
46 // with a leading "v". Adding prefix "v" to the inputs.
47 // Reference: https://pkg.go.dev/golang.org/x/mod/semver#pkg-overview
48 return semver.Compare("v"+v, "v"+w), nil
49 }