version.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* Copyright 2018 The Bazel Authors. All rights reserved.
  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. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. */
  12. package version
  13. import (
  14. "fmt"
  15. "strconv"
  16. "strings"
  17. )
  18. // Version is a tuple of non-negative integers that represents the version of
  19. // a software package.
  20. type Version []int
  21. func (v Version) String() string {
  22. cstrs := make([]string, len(v))
  23. for i, cn := range v {
  24. cstrs[i] = strconv.Itoa(cn)
  25. }
  26. return strings.Join(cstrs, ".")
  27. }
  28. // Compare returns an integer comparing two versions lexicographically.
  29. func (x Version) Compare(y Version) int {
  30. n := len(x)
  31. if len(y) < n {
  32. n = len(y)
  33. }
  34. for i := 0; i < n; i++ {
  35. cmp := x[i] - y[i]
  36. if cmp != 0 {
  37. return cmp
  38. }
  39. }
  40. return len(x) - len(y)
  41. }
  42. // ParseVersion parses a version of the form "12.34.56-abcd". Non-negative
  43. // integer components are separated by dots. An arbitrary suffix may appear
  44. // after '-', which is ignored.
  45. func ParseVersion(vs string) (Version, error) {
  46. i := strings.IndexByte(vs, '-')
  47. if i >= 0 {
  48. vs = vs[:i]
  49. }
  50. cstrs := strings.Split(vs, ".")
  51. v := make(Version, len(cstrs))
  52. for i, cstr := range cstrs {
  53. cn, err := strconv.Atoi(cstr)
  54. if err != nil {
  55. return nil, fmt.Errorf("could not parse version string: %q is not an integer", cstr)
  56. }
  57. if cn < 0 {
  58. return nil, fmt.Errorf("could not parse version string: %q is negative", cstr)
  59. }
  60. v[i] = cn
  61. }
  62. return v, nil
  63. }