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