github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/plugin/discovery/version.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package discovery 5 6 import ( 7 "fmt" 8 "sort" 9 10 version "github.com/hashicorp/go-version" 11 ) 12 13 const VersionZero = "0.0.0" 14 15 // A VersionStr is a string containing a possibly-invalid representation 16 // of a semver version number. Call Parse on it to obtain a real Version 17 // object, or discover that it is invalid. 18 type VersionStr string 19 20 // Parse transforms a VersionStr into a Version if it is 21 // syntactically valid. If it isn't then an error is returned instead. 22 func (s VersionStr) Parse() (Version, error) { 23 raw, err := version.NewVersion(string(s)) 24 if err != nil { 25 return Version{}, err 26 } 27 return Version{raw}, nil 28 } 29 30 // MustParse transforms a VersionStr into a Version if it is 31 // syntactically valid. If it isn't then it panics. 32 func (s VersionStr) MustParse() Version { 33 ret, err := s.Parse() 34 if err != nil { 35 panic(err) 36 } 37 return ret 38 } 39 40 // Version represents a version number that has been parsed from 41 // a semver string and known to be valid. 42 type Version struct { 43 // We wrap this here just because it avoids a proliferation of 44 // direct go-version imports all over the place, and keeps the 45 // version-processing details within this package. 46 raw *version.Version 47 } 48 49 func (v Version) String() string { 50 return v.raw.String() 51 } 52 53 func (v Version) NewerThan(other Version) bool { 54 return v.raw.GreaterThan(other.raw) 55 } 56 57 func (v Version) Equal(other Version) bool { 58 return v.raw.Equal(other.raw) 59 } 60 61 // IsPrerelease determines if version is a prerelease 62 func (v Version) IsPrerelease() bool { 63 return v.raw.Prerelease() != "" 64 } 65 66 // MinorUpgradeConstraintStr returns a ConstraintStr that would permit 67 // minor upgrades relative to the receiving version. 68 func (v Version) MinorUpgradeConstraintStr() ConstraintStr { 69 segments := v.raw.Segments() 70 return ConstraintStr(fmt.Sprintf("~> %d.%d", segments[0], segments[1])) 71 } 72 73 type Versions []Version 74 75 // Sort sorts version from newest to oldest. 76 func (v Versions) Sort() { 77 sort.Slice(v, func(i, j int) bool { 78 return v[i].NewerThan(v[j]) 79 }) 80 }