• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""Module for parsing and testing package version predicate strings.
2"""
3import re
4import distutils.version
5import operator
6
7
8re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)",
9    re.ASCII)
10# (package) (rest)
11
12re_paren = re.compile(r"^\s*\((.*)\)\s*$") # (list) inside of parentheses
13re_splitComparison = re.compile(r"^\s*(<=|>=|<|>|!=|==)\s*([^\s,]+)\s*$")
14# (comp) (version)
15
16
17def splitUp(pred):
18    """Parse a single version comparison.
19
20    Return (comparison string, StrictVersion)
21    """
22    res = re_splitComparison.match(pred)
23    if not res:
24        raise ValueError("bad package restriction syntax: %r" % pred)
25    comp, verStr = res.groups()
26    return (comp, distutils.version.StrictVersion(verStr))
27
28compmap = {"<": operator.lt, "<=": operator.le, "==": operator.eq,
29           ">": operator.gt, ">=": operator.ge, "!=": operator.ne}
30
31class VersionPredicate:
32    """Parse and test package version predicates.
33
34    >>> v = VersionPredicate('pyepat.abc (>1.0, <3333.3a1, !=1555.1b3)')
35
36    The `name` attribute provides the full dotted name that is given::
37
38    >>> v.name
39    'pyepat.abc'
40
41    The str() of a `VersionPredicate` provides a normalized
42    human-readable version of the expression::
43
44    >>> print(v)
45    pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3)
46
47    The `satisfied_by()` method can be used to determine with a given
48    version number is included in the set described by the version
49    restrictions::
50
51    >>> v.satisfied_by('1.1')
52    True
53    >>> v.satisfied_by('1.4')
54    True
55    >>> v.satisfied_by('1.0')
56    False
57    >>> v.satisfied_by('4444.4')
58    False
59    >>> v.satisfied_by('1555.1b3')
60    False
61
62    `VersionPredicate` is flexible in accepting extra whitespace::
63
64    >>> v = VersionPredicate(' pat( ==  0.1  )  ')
65    >>> v.name
66    'pat'
67    >>> v.satisfied_by('0.1')
68    True
69    >>> v.satisfied_by('0.2')
70    False
71
72    If any version numbers passed in do not conform to the
73    restrictions of `StrictVersion`, a `ValueError` is raised::
74
75    >>> v = VersionPredicate('p1.p2.p3.p4(>=1.0, <=1.3a1, !=1.2zb3)')
76    Traceback (most recent call last):
77      ...
78    ValueError: invalid version number '1.2zb3'
79
80    It the module or package name given does not conform to what's
81    allowed as a legal module or package name, `ValueError` is
82    raised::
83
84    >>> v = VersionPredicate('foo-bar')
85    Traceback (most recent call last):
86      ...
87    ValueError: expected parenthesized list: '-bar'
88
89    >>> v = VersionPredicate('foo bar (12.21)')
90    Traceback (most recent call last):
91      ...
92    ValueError: expected parenthesized list: 'bar (12.21)'
93
94    """
95
96    def __init__(self, versionPredicateStr):
97        """Parse a version predicate string.
98        """
99        # Fields:
100        #    name:  package name
101        #    pred:  list of (comparison string, StrictVersion)
102
103        versionPredicateStr = versionPredicateStr.strip()
104        if not versionPredicateStr:
105            raise ValueError("empty package restriction")
106        match = re_validPackage.match(versionPredicateStr)
107        if not match:
108            raise ValueError("bad package name in %r" % versionPredicateStr)
109        self.name, paren = match.groups()
110        paren = paren.strip()
111        if paren:
112            match = re_paren.match(paren)
113            if not match:
114                raise ValueError("expected parenthesized list: %r" % paren)
115            str = match.groups()[0]
116            self.pred = [splitUp(aPred) for aPred in str.split(",")]
117            if not self.pred:
118                raise ValueError("empty parenthesized list in %r"
119                                 % versionPredicateStr)
120        else:
121            self.pred = []
122
123    def __str__(self):
124        if self.pred:
125            seq = [cond + " " + str(ver) for cond, ver in self.pred]
126            return self.name + " (" + ", ".join(seq) + ")"
127        else:
128            return self.name
129
130    def satisfied_by(self, version):
131        """True if version is compatible with all the predicates in self.
132        The parameter version must be acceptable to the StrictVersion
133        constructor.  It may be either a string or StrictVersion.
134        """
135        for cond, ver in self.pred:
136            if not compmap[cond](version, ver):
137                return False
138        return True
139
140
141_provision_rx = None
142
143def split_provision(value):
144    """Return the name and optional version number of a provision.
145
146    The version number, if given, will be returned as a `StrictVersion`
147    instance, otherwise it will be `None`.
148
149    >>> split_provision('mypkg')
150    ('mypkg', None)
151    >>> split_provision(' mypkg( 1.2 ) ')
152    ('mypkg', StrictVersion ('1.2'))
153    """
154    global _provision_rx
155    if _provision_rx is None:
156        _provision_rx = re.compile(
157            r"([a-zA-Z_]\w*(?:\.[a-zA-Z_]\w*)*)(?:\s*\(\s*([^)\s]+)\s*\))?$",
158            re.ASCII)
159    value = value.strip()
160    m = _provision_rx.match(value)
161    if not m:
162        raise ValueError("illegal provides specification: %r" % value)
163    ver = m.group(2) or None
164    if ver:
165        ver = distutils.version.StrictVersion(ver)
166    return m.group(1), ver
167