aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/hashicorp/terraform/plugin/discovery/version_set.go
blob: 0aefd759fd4f353713ace4f34ed9b54600b7713d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package discovery

import (
	"sort"

	version "github.com/hashicorp/go-version"
)

// A ConstraintStr is a string containing a possibly-invalid representation
// of a version constraint provided in configuration. Call Parse on it to
// obtain a real Constraint object, or discover that it is invalid.
type ConstraintStr string

// Parse transforms a ConstraintStr into a Constraints if it is
// syntactically valid. If it isn't then an error is returned instead.
func (s ConstraintStr) Parse() (Constraints, error) {
	raw, err := version.NewConstraint(string(s))
	if err != nil {
		return Constraints{}, err
	}
	return Constraints{raw}, nil
}

// MustParse is like Parse but it panics if the constraint string is invalid.
func (s ConstraintStr) MustParse() Constraints {
	ret, err := s.Parse()
	if err != nil {
		panic(err)
	}
	return ret
}

// Constraints represents a set of versions which any given Version is either
// a member of or not.
type Constraints struct {
	raw version.Constraints
}

// AllVersions is a Constraints containing all versions
var AllVersions Constraints

func init() {
	AllVersions = Constraints{
		raw: make(version.Constraints, 0),
	}
}

// Allows returns true if the given version permitted by the receiving
// constraints set.
func (s Constraints) Allows(v Version) bool {
	return s.raw.Check(v.raw)
}

// Append combines the receiving set with the given other set to produce
// a set that is the intersection of both sets, which is to say that resulting
// constraints contain only the versions that are members of both.
func (s Constraints) Append(other Constraints) Constraints {
	raw := make(version.Constraints, 0, len(s.raw)+len(other.raw))

	// Since "raw" is a list of constraints that remove versions from the set,
	// "Intersection" is implemented by concatenating together those lists,
	// thus leaving behind only the versions not removed by either list.
	raw = append(raw, s.raw...)
	raw = append(raw, other.raw...)

	// while the set is unordered, we sort these lexically for consistent output
	sort.Slice(raw, func(i, j int) bool {
		return raw[i].String() < raw[j].String()
	})

	return Constraints{raw}
}

// String returns a string representation of the set members as a set
// of range constraints.
func (s Constraints) String() string {
	return s.raw.String()
}

// Unconstrained returns true if and only if the receiver is an empty
// constraint set.
func (s Constraints) Unconstrained() bool {
	return len(s.raw) == 0
}