2 Copyright 2018 The Kubernetes Authors.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
28 // Bigger the version type number, higher priority it is
29 versionTypeAlpha versionType = iota
34 var kubeVersionRegex = regexp.MustCompile("^v([\\d]+)(?:(alpha|beta)([\\d]+))?$")
36 func parseKubeVersion(v string) (majorVersion int, vType versionType, minorVersion int, ok bool) {
38 submatches := kubeVersionRegex.FindStringSubmatch(v)
39 if len(submatches) != 4 {
42 switch submatches[2] {
44 vType = versionTypeAlpha
46 vType = versionTypeBeta
52 if majorVersion, err = strconv.Atoi(submatches[1]); err != nil {
55 if vType != versionTypeGA {
56 if minorVersion, err = strconv.Atoi(submatches[3]); err != nil {
60 return majorVersion, vType, minorVersion, true
63 // CompareKubeAwareVersionStrings compares two kube-like version strings.
64 // Kube-like version strings are starting with a v, followed by a major version, optional "alpha" or "beta" strings
65 // followed by a minor version (e.g. v1, v2beta1). Versions will be sorted based on GA/alpha/beta first and then major
66 // and minor versions. e.g. v2, v1, v1beta2, v1beta1, v1alpha1.
67 func CompareKubeAwareVersionStrings(v1, v2 string) int {
71 v1major, v1type, v1minor, ok1 := parseKubeVersion(v1)
72 v2major, v2type, v2minor, ok2 := parseKubeVersion(v2)
75 return strings.Compare(v2, v1)
82 return int(v1type) - int(v2type)
84 if v1major != v2major {
85 return v1major - v2major
87 return v1minor - v2minor