github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/roachpb/version.go (about) 1 // Copyright 2017 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package roachpb 12 13 import ( 14 "fmt" 15 "strconv" 16 "strings" 17 18 "github.com/cockroachdb/errors" 19 ) 20 21 // Less compares two Versions. 22 func (v Version) Less(otherV Version) bool { 23 if v.Major < otherV.Major { 24 return true 25 } else if v.Major > otherV.Major { 26 return false 27 } 28 if v.Minor < otherV.Minor { 29 return true 30 } else if v.Minor > otherV.Minor { 31 return false 32 } 33 if v.Patch < otherV.Patch { 34 return true 35 } else if v.Patch > otherV.Patch { 36 return false 37 } 38 if v.Unstable < otherV.Unstable { 39 return true 40 } else if v.Unstable > otherV.Unstable { 41 return false 42 } 43 return false 44 } 45 46 func (v Version) String() string { 47 if v.Unstable == 0 { 48 return fmt.Sprintf("%d.%d", v.Major, v.Minor) 49 } 50 return fmt.Sprintf("%d.%d-%d", v.Major, v.Minor, v.Unstable) 51 } 52 53 // ParseVersion parses a Version from a string of the form 54 // "<major>.<minor>-<unstable>" where the "-<unstable>" is optional. We don't 55 // use the Patch component, so it is always zero. 56 func ParseVersion(s string) (Version, error) { 57 var c Version 58 dotParts := strings.Split(s, ".") 59 60 if len(dotParts) != 2 { 61 return Version{}, errors.Errorf("invalid version %s", s) 62 } 63 64 parts := append(dotParts[:1], strings.Split(dotParts[1], "-")...) 65 if len(parts) == 2 { 66 parts = append(parts, "0") 67 } 68 69 if len(parts) != 3 { 70 return c, errors.Errorf("invalid version %s", s) 71 } 72 73 ints := make([]int64, len(parts)) 74 for i := range parts { 75 var err error 76 if ints[i], err = strconv.ParseInt(parts[i], 10, 32); err != nil { 77 return c, errors.Errorf("invalid version %s: %s", s, err) 78 } 79 } 80 81 c.Major = int32(ints[0]) 82 c.Minor = int32(ints[1]) 83 c.Unstable = int32(ints[2]) 84 85 return c, nil 86 } 87 88 // MustParseVersion calls ParseVersion and panics on error. 89 func MustParseVersion(s string) Version { 90 v, err := ParseVersion(s) 91 if err != nil { 92 panic(err) 93 } 94 return v 95 }