Debian Codegraph @

lib/ansible/module_utils/compat/version.py

raw
1 # Vendored copy of distutils/version.py from CPython 3.9.5
2 #
3 # Implements multiple version numbering conventions for the
4 # Python Module Distribution Utilities.
5 #
6 # PSF License (see licenses/PSF-license.txt or https://opensource.org/licenses/Python-2.0)
7 #
8
9 """Provides classes to represent module version numbers (one class for
10 each style of version numbering). There are currently two such classes
11 implemented: StrictVersion and LooseVersion.
12
13 Every version number class implements the following interface:
14 * the 'parse' method takes a string and parses it to some internal
15 representation; if the string is an invalid version number,
16 'parse' raises a ValueError exception
17 * the class constructor takes an optional string argument which,
18 if supplied, is passed to 'parse'
19 * __str__ reconstructs the string that was passed to 'parse' (or
20 an equivalent string -- ie. one that will generate an equivalent
21 version number instance)
22 * __repr__ generates Python code to recreate the version number instance
23 * _cmp compares the current instance with either another instance
24 of the same class or a string (which will be parsed to an instance
25 of the same class, thus must follow the same rules)
26 """
27
28 from __future__ import annotations
29
30 import re
31
32 try:
33 RE_FLAGS = re.VERBOSE | re.ASCII # type: ignore[attr-defined]
34 except AttributeError:
35 RE_FLAGS = re.VERBOSE
36
37
38 class Version:
39 """Abstract base class for version numbering classes. Just provides
40 constructor (__init__) and reproducer (__repr__), because those
41 seem to be the same for all version numbering classes; and route
42 rich comparisons to _cmp.
43 """
44
45 def __init__(self, vstring=None):
46 if vstring:
47 self.parse(vstring)
48
49 def __repr__(self):
50 return "%s ('%s')" % (self.__class__.__name__, str(self))
51
52 def __eq__(self, other):
53 c = self._cmp(other)
54 if c is NotImplemented:
55 return c
56 return c == 0
57
58 def __lt__(self, other):
59 c = self._cmp(other)
60 if c is NotImplemented:
61 return c
62 return c < 0
63
64 def __le__(self, other):
65 c = self._cmp(other)
66 if c is NotImplemented:
67 return c
68 return c <= 0
69
70 def __gt__(self, other):
71 c = self._cmp(other)
72 if c is NotImplemented:
73 return c
74 return c > 0
75
76 def __ge__(self, other):
77 c = self._cmp(other)
78 if c is NotImplemented:
79 return c
80 return c >= 0
81
82
83 # Interface for version-number classes -- must be implemented
84 # by the following classes (the concrete ones -- Version should
85 # be treated as an abstract class).
86 # __init__ (string) - create and take same action as 'parse'
87 # (string parameter is optional)
88 # parse (string) - convert a string representation to whatever
89 # internal representation is appropriate for
90 # this style of version numbering
91 # __str__ (self) - convert back to a string; should be very similar
92 # (if not identical to) the string supplied to parse
93 # __repr__ (self) - generate Python code to recreate
94 # the instance
95 # _cmp (self, other) - compare two version numbers ('other' may
96 # be an unparsed version string, or another
97 # instance of your version class)
98
99
100 class StrictVersion(Version):
101 """Version numbering for anal retentives and software idealists.
102 Implements the standard interface for version number classes as
103 described above. A version number consists of two or three
104 dot-separated numeric components, with an optional "pre-release" tag
105 on the end. The pre-release tag consists of the letter 'a' or 'b'
106 followed by a number. If the numeric components of two version
107 numbers are equal, then one with a pre-release tag will always
108 be deemed earlier (lesser) than one without.
109
110 The following are valid version numbers (shown in the order that
111 would be obtained by sorting according to the supplied cmp function):
112
113 0.4 0.4.0 (these two are equivalent)
114 0.4.1
115 0.5a1
116 0.5b3
117 0.5
118 0.9.6
119 1.0
120 1.0.4a3
121 1.0.4b1
122 1.0.4
123
124 The following are examples of invalid version numbers:
125
126 1
127 2.7.2.2
128 1.3.a4
129 1.3pl1
130 1.3c4
131
132 The rationale for this version numbering system will be explained
133 in the distutils documentation.
134 """
135
136 version_re = re.compile(r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$',
137 RE_FLAGS)
138
139 def parse(self, vstring):
140 match = self.version_re.match(vstring)
141 if not match:
142 raise ValueError("invalid version number '%s'" % vstring)
143
144 (major, minor, patch, prerelease, prerelease_num) = \
145 match.group(1, 2, 4, 5, 6)
146
147 if patch:
148 self.version = tuple(map(int, [major, minor, patch]))
149 else:
150 self.version = tuple(map(int, [major, minor])) + (0,)
151
152 if prerelease:
153 self.prerelease = (prerelease[0], int(prerelease_num))
154 else:
155 self.prerelease = None
156
157 def __str__(self):
158 if self.version[2] == 0:
159 vstring = '.'.join(map(str, self.version[0:2]))
160 else:
161 vstring = '.'.join(map(str, self.version))
162
163 if self.prerelease:
164 vstring = vstring + self.prerelease[0] + str(self.prerelease[1])
165
166 return vstring
167
168 def _cmp(self, other):
169 if isinstance(other, str):
170 other = StrictVersion(other)
171 elif not isinstance(other, StrictVersion):
172 return NotImplemented
173
174 if self.version != other.version:
175 # numeric versions don't match
176 # prerelease stuff doesn't matter
177 if self.version < other.version:
178 return -1
179 else:
180 return 1
181
182 # have to compare prerelease
183 # case 1: neither has prerelease; they're equal
184 # case 2: self has prerelease, other doesn't; other is greater
185 # case 3: self doesn't have prerelease, other does: self is greater
186 # case 4: both have prerelease: must compare them!
187
188 if (not self.prerelease and not other.prerelease):
189 return 0
190 elif (self.prerelease and not other.prerelease):
191 return -1
192 elif (not self.prerelease and other.prerelease):
193 return 1
194 elif (self.prerelease and other.prerelease):
195 if self.prerelease == other.prerelease:
196 return 0
197 elif self.prerelease < other.prerelease:
198 return -1
199 else:
200 return 1
201 else:
202 raise AssertionError("never get here")
203
204 # end class StrictVersion
205
206 # The rules according to Greg Stein:
207 # 1) a version number has 1 or more numbers separated by a period or by
208 # sequences of letters. If only periods, then these are compared
209 # left-to-right to determine an ordering.
210 # 2) sequences of letters are part of the tuple for comparison and are
211 # compared lexicographically
212 # 3) recognize the numeric components may have leading zeroes
213 #
214 # The LooseVersion class below implements these rules: a version number
215 # string is split up into a tuple of integer and string components, and
216 # comparison is a simple tuple comparison. This means that version
217 # numbers behave in a predictable and obvious way, but a way that might
218 # not necessarily be how people *want* version numbers to behave. There
219 # wouldn't be a problem if people could stick to purely numeric version
220 # numbers: just split on period and compare the numbers as tuples.
221 # However, people insist on putting letters into their version numbers;
222 # the most common purpose seems to be:
223 # - indicating a "pre-release" version
224 # ('alpha', 'beta', 'a', 'b', 'pre', 'p')
225 # - indicating a post-release patch ('p', 'pl', 'patch')
226 # but of course this can't cover all version number schemes, and there's
227 # no way to know what a programmer means without asking them.
228 #
229 # The problem is what to do with letters (and other non-numeric
230 # characters) in a version number. The current implementation does the
231 # obvious and predictable thing: keep them as strings and compare
232 # lexically within a tuple comparison. This has the desired effect if
233 # an appended letter sequence implies something "post-release":
234 # eg. "0.99" < "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002".
235 #
236 # However, if letters in a version number imply a pre-release version,
237 # the "obvious" thing isn't correct. Eg. you would expect that
238 # "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison
239 # implemented here, this just isn't so.
240 #
241 # Two possible solutions come to mind. The first is to tie the
242 # comparison algorithm to a particular set of semantic rules, as has
243 # been done in the StrictVersion class above. This works great as long
244 # as everyone can go along with bondage and discipline. Hopefully a
245 # (large) subset of Python module programmers will agree that the
246 # particular flavour of bondage and discipline provided by StrictVersion
247 # provides enough benefit to be worth using, and will submit their
248 # version numbering scheme to its domination. The free-thinking
249 # anarchists in the lot will never give in, though, and something needs
250 # to be done to accommodate them.
251 #
252 # Perhaps a "moderately strict" version class could be implemented that
253 # lets almost anything slide (syntactically), and makes some heuristic
254 # assumptions about non-digits in version number strings. This could
255 # sink into special-case-hell, though; if I was as talented and
256 # idiosyncratic as Larry Wall, I'd go ahead and implement a class that
257 # somehow knows that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is
258 # just as happy dealing with things like "2g6" and "1.13++". I don't
259 # think I'm smart enough to do it right though.
260 #
261 # In any case, I've coded the test suite for this module (see
262 # ../test/test_version.py) specifically to fail on things like comparing
263 # "1.2a2" and "1.2". That's not because the *code* is doing anything
264 # wrong, it's because the simple, obvious design doesn't match my
265 # complicated, hairy expectations for real-world version numbers. It
266 # would be a snap to fix the test suite to say, "Yep, LooseVersion does
267 # the Right Thing" (ie. the code matches the conception). But I'd rather
268 # have a conception that matches common notions about version numbers.
269
270
271 class LooseVersion(Version):
272 """Version numbering for anarchists and software realists.
273 Implements the standard interface for version number classes as
274 described above. A version number consists of a series of numbers,
275 separated by either periods or strings of letters. When comparing
276 version numbers, the numeric components will be compared
277 numerically, and the alphabetic components lexically. The following
278 are all valid version numbers, in no particular order:
279
280 1.5.1
281 1.5.2b2
282 161
283 3.10a
284 8.02
285 3.4j
286 1996.07.12
287 3.2.pl0
288 3.1.1.6
289 2g6
290 11g
291 0.960923
292 2.2beta29
293 1.13++
294 5.5.kw
295 2.0b1pl0
296
297 In fact, there is no such thing as an invalid version number under
298 this scheme; the rules for comparison are simple and predictable,
299 but may not always give the results you want (for some definition
300 of "want").
301 """
302
303 component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE)
304
305 def __init__(self, vstring=None):
306 if vstring:
307 self.parse(vstring)
308
309 def parse(self, vstring):
310 # I've given up on thinking I can reconstruct the version string
311 # from the parsed tuple -- so I just store the string here for
312 # use by __str__
313 self.vstring = vstring
314 components = [x for x in self.component_re.split(vstring) if x and x != '.']
315 for i, obj in enumerate(components):
316 try:
317 components[i] = int(obj)
318 except ValueError:
319 pass
320
321 self.version = components
322
323 def __str__(self):
324 return self.vstring
325
326 def __repr__(self):
327 return "LooseVersion ('%s')" % str(self)
328
329 def _cmp(self, other):
330 if isinstance(other, str):
331 other = LooseVersion(other)
332 elif not isinstance(other, LooseVersion):
333 return NotImplemented
334
335 if self.version == other.version:
336 return 0
337 if self.version < other.version:
338 return -1
339 if self.version > other.version:
340 return 1
341
342 # end class LooseVersion