PageRenderTime 47ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/distutils/version.py

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