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