github.com/sl1pm4t/terraform@v0.6.4-0.20170725213156-870617d22df3/plugin/discovery/version_set.go (about) 1 package discovery 2 3 import ( 4 "sort" 5 6 version "github.com/hashicorp/go-version" 7 ) 8 9 // A ConstraintStr is a string containing a possibly-invalid representation 10 // of a version constraint provided in configuration. Call Parse on it to 11 // obtain a real Constraint object, or discover that it is invalid. 12 type ConstraintStr string 13 14 // Parse transforms a ConstraintStr into a Constraints if it is 15 // syntactically valid. If it isn't then an error is returned instead. 16 func (s ConstraintStr) Parse() (Constraints, error) { 17 raw, err := version.NewConstraint(string(s)) 18 if err != nil { 19 return Constraints{}, err 20 } 21 return Constraints{raw}, nil 22 } 23 24 // MustParse is like Parse but it panics if the constraint string is invalid. 25 func (s ConstraintStr) MustParse() Constraints { 26 ret, err := s.Parse() 27 if err != nil { 28 panic(err) 29 } 30 return ret 31 } 32 33 // Constraints represents a set of versions which any given Version is either 34 // a member of or not. 35 type Constraints struct { 36 raw version.Constraints 37 } 38 39 // AllVersions is a Constraints containing all versions 40 var AllVersions Constraints 41 42 func init() { 43 AllVersions = Constraints{ 44 raw: make(version.Constraints, 0), 45 } 46 } 47 48 // Allows returns true if the given version permitted by the receiving 49 // constraints set. 50 func (s Constraints) Allows(v Version) bool { 51 return s.raw.Check(v.raw) 52 } 53 54 // Append combines the receiving set with the given other set to produce 55 // a set that is the intersection of both sets, which is to say that resulting 56 // constraints contain only the versions that are members of both. 57 func (s Constraints) Append(other Constraints) Constraints { 58 raw := make(version.Constraints, 0, len(s.raw)+len(other.raw)) 59 60 // Since "raw" is a list of constraints that remove versions from the set, 61 // "Intersection" is implemented by concatenating together those lists, 62 // thus leaving behind only the versions not removed by either list. 63 raw = append(raw, s.raw...) 64 raw = append(raw, other.raw...) 65 66 // while the set is unordered, we sort these lexically for consistent output 67 sort.Slice(raw, func(i, j int) bool { 68 return raw[i].String() < raw[j].String() 69 }) 70 71 return Constraints{raw} 72 } 73 74 // String returns a string representation of the set members as a set 75 // of range constraints. 76 func (s Constraints) String() string { 77 return s.raw.String() 78 } 79 80 // Unconstrained returns true if and only if the receiver is an empty 81 // constraint set. 82 func (s Constraints) Unconstrained() bool { 83 return len(s.raw) == 0 84 }