6 version "github.com/hashicorp/go-version"
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
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))
19 return Constraints{}, err
21 return Constraints{raw}, nil
24 // MustParse is like Parse but it panics if the constraint string is invalid.
25 func (s ConstraintStr) MustParse() Constraints {
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
39 // NewConstraints creates a Constraints based on a version.Constraints.
40 func NewConstraints(c version.Constraints) Constraints {
44 // AllVersions is a Constraints containing all versions
45 var AllVersions Constraints
48 AllVersions = Constraints{
49 raw: make(version.Constraints, 0),
53 // Allows returns true if the given version permitted by the receiving
55 func (s Constraints) Allows(v Version) bool {
56 return s.raw.Check(v.raw)
59 // Append combines the receiving set with the given other set to produce
60 // a set that is the intersection of both sets, which is to say that resulting
61 // constraints contain only the versions that are members of both.
62 func (s Constraints) Append(other Constraints) Constraints {
63 raw := make(version.Constraints, 0, len(s.raw)+len(other.raw))
65 // Since "raw" is a list of constraints that remove versions from the set,
66 // "Intersection" is implemented by concatenating together those lists,
67 // thus leaving behind only the versions not removed by either list.
68 raw = append(raw, s.raw...)
69 raw = append(raw, other.raw...)
71 // while the set is unordered, we sort these lexically for consistent output
72 sort.Slice(raw, func(i, j int) bool {
73 return raw[i].String() < raw[j].String()
76 return Constraints{raw}
79 // String returns a string representation of the set members as a set
80 // of range constraints.
81 func (s Constraints) String() string {
85 // Unconstrained returns true if and only if the receiver is an empty
87 func (s Constraints) Unconstrained() bool {
88 return len(s.raw) == 0