github.com/google/osv-scalibr@v0.4.1/semantic/version-hackage.go (about) 1 // Copyright 2025 Google LLC 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 package semantic 16 17 import ( 18 "fmt" 19 "strings" 20 ) 21 22 type hackageVersion struct { 23 semverLikeVersion 24 } 25 26 func (v hackageVersion) compare(w hackageVersion) int { 27 if diff := v.Components.Cmp(w.Components); diff != 0 { 28 return diff 29 } 30 31 return compareBuildComponents(strings.ToLower(v.Build), strings.ToLower(w.Build)) 32 } 33 34 func (v hackageVersion) CompareStr(str string) (int, error) { 35 w, err := parseHackageVersion(str) 36 37 if err != nil { 38 return 0, err 39 } 40 41 if diff := v.compare(w); diff != 0 { 42 return diff, nil 43 } 44 45 if len(v.Components) > len(w.Components) { 46 return +1, nil 47 } 48 if len(v.Components) < len(w.Components) { 49 return -1, nil 50 } 51 52 return 0, nil 53 } 54 55 func parseHackageVersion(str string) (hackageVersion, error) { 56 v := hackageVersion{parseSemverLikeVersion(str, -1)} 57 58 // this is technically possible since we're using the "semver-like" parser 59 if v.Build != "" { 60 return hackageVersion{}, fmt.Errorf("%w: Hackage versions cannot contain a build version", ErrInvalidVersion) 61 } 62 63 return v, nil 64 }