helpers.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package version
  14. import (
  15. "regexp"
  16. "strconv"
  17. "strings"
  18. )
  19. type versionType int
  20. const (
  21. // Bigger the version type number, higher priority it is
  22. versionTypeAlpha versionType = iota
  23. versionTypeBeta
  24. versionTypeGA
  25. )
  26. var kubeVersionRegex = regexp.MustCompile("^v([\\d]+)(?:(alpha|beta)([\\d]+))?$")
  27. func parseKubeVersion(v string) (majorVersion int, vType versionType, minorVersion int, ok bool) {
  28. var err error
  29. submatches := kubeVersionRegex.FindStringSubmatch(v)
  30. if len(submatches) != 4 {
  31. return 0, 0, 0, false
  32. }
  33. switch submatches[2] {
  34. case "alpha":
  35. vType = versionTypeAlpha
  36. case "beta":
  37. vType = versionTypeBeta
  38. case "":
  39. vType = versionTypeGA
  40. default:
  41. return 0, 0, 0, false
  42. }
  43. if majorVersion, err = strconv.Atoi(submatches[1]); err != nil {
  44. return 0, 0, 0, false
  45. }
  46. if vType != versionTypeGA {
  47. if minorVersion, err = strconv.Atoi(submatches[3]); err != nil {
  48. return 0, 0, 0, false
  49. }
  50. }
  51. return majorVersion, vType, minorVersion, true
  52. }
  53. // CompareKubeAwareVersionStrings compares two kube-like version strings.
  54. // Kube-like version strings are starting with a v, followed by a major version, optional "alpha" or "beta" strings
  55. // followed by a minor version (e.g. v1, v2beta1). Versions will be sorted based on GA/alpha/beta first and then major
  56. // and minor versions. e.g. v2, v1, v1beta2, v1beta1, v1alpha1.
  57. func CompareKubeAwareVersionStrings(v1, v2 string) int {
  58. if v1 == v2 {
  59. return 0
  60. }
  61. v1major, v1type, v1minor, ok1 := parseKubeVersion(v1)
  62. v2major, v2type, v2minor, ok2 := parseKubeVersion(v2)
  63. switch {
  64. case !ok1 && !ok2:
  65. return strings.Compare(v2, v1)
  66. case !ok1 && ok2:
  67. return -1
  68. case ok1 && !ok2:
  69. return 1
  70. }
  71. if v1type != v2type {
  72. return int(v1type) - int(v2type)
  73. }
  74. if v1major != v2major {
  75. return v1major - v2major
  76. }
  77. return v1minor - v2minor
  78. }