Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/distlib/version.py: 24%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

414 statements  

1# -*- coding: utf-8 -*- 

2# 

3# Copyright (C) 2012-2023 The Python Software Foundation. 

4# See LICENSE.txt and CONTRIBUTORS.txt. 

5# 

6""" 

7Implementation of a flexible versioning scheme providing support for PEP-440, 

8setuptools-compatible and semantic versioning. 

9""" 

10 

11import logging 

12import re 

13 

14from .compat import string_types 

15from .util import parse_requirement 

16 

17__all__ = ['NormalizedVersion', 'NormalizedMatcher', 

18 'LegacyVersion', 'LegacyMatcher', 

19 'SemanticVersion', 'SemanticMatcher', 

20 'UnsupportedVersionError', 'get_scheme'] 

21 

22logger = logging.getLogger(__name__) 

23 

24 

25class UnsupportedVersionError(ValueError): 

26 """This is an unsupported version.""" 

27 pass 

28 

29 

30class Version(object): 

31 def __init__(self, s): 

32 self._string = s = s.strip() 

33 self._parts = parts = self.parse(s) 

34 assert isinstance(parts, tuple) 

35 assert len(parts) > 0 

36 

37 def parse(self, s): 

38 raise NotImplementedError('please implement in a subclass') 

39 

40 def _check_compatible(self, other): 

41 if type(self) != type(other): 

42 raise TypeError('cannot compare %r and %r' % (self, other)) 

43 

44 def __eq__(self, other): 

45 self._check_compatible(other) 

46 return self._parts == other._parts 

47 

48 def __ne__(self, other): 

49 return not self.__eq__(other) 

50 

51 def __lt__(self, other): 

52 self._check_compatible(other) 

53 return self._parts < other._parts 

54 

55 def __gt__(self, other): 

56 return not (self.__lt__(other) or self.__eq__(other)) 

57 

58 def __le__(self, other): 

59 return self.__lt__(other) or self.__eq__(other) 

60 

61 def __ge__(self, other): 

62 return self.__gt__(other) or self.__eq__(other) 

63 

64 # See http://docs.python.org/reference/datamodel#object.__hash__ 

65 def __hash__(self): 

66 return hash(self._parts) 

67 

68 def __repr__(self): 

69 return "%s('%s')" % (self.__class__.__name__, self._string) 

70 

71 def __str__(self): 

72 return self._string 

73 

74 @property 

75 def is_prerelease(self): 

76 raise NotImplementedError('Please implement in subclasses.') 

77 

78 

79class Matcher(object): 

80 version_class = None 

81 

82 # value is either a callable or the name of a method 

83 _operators = { 

84 '<': lambda v, c, p: v < c, 

85 '>': lambda v, c, p: v > c, 

86 '<=': lambda v, c, p: v == c or v < c, 

87 '>=': lambda v, c, p: v == c or v > c, 

88 '==': lambda v, c, p: v == c, 

89 '===': lambda v, c, p: v == c, 

90 # by default, compatible => >=. 

91 '~=': lambda v, c, p: v == c or v > c, 

92 '!=': lambda v, c, p: v != c, 

93 } 

94 

95 # this is a method only to support alternative implementations 

96 # via overriding 

97 def parse_requirement(self, s): 

98 return parse_requirement(s) 

99 

100 def __init__(self, s): 

101 if self.version_class is None: 

102 raise ValueError('Please specify a version class') 

103 self._string = s = s.strip() 

104 r = self.parse_requirement(s) 

105 if not r: 

106 raise ValueError('Not valid: %r' % s) 

107 self.name = r.name 

108 self.key = self.name.lower() # for case-insensitive comparisons 

109 clist = [] 

110 if r.constraints: 

111 # import pdb; pdb.set_trace() 

112 for op, s in r.constraints: 

113 if s.endswith('.*'): 

114 if op not in ('==', '!='): 

115 raise ValueError('\'.*\' not allowed for ' 

116 '%r constraints' % op) 

117 # Could be a partial version (e.g. for '2.*') which 

118 # won't parse as a version, so keep it as a string 

119 vn, prefix = s[:-2], True 

120 # Just to check that vn is a valid version 

121 self.version_class(vn) 

122 else: 

123 # Should parse as a version, so we can create an 

124 # instance for the comparison 

125 vn, prefix = self.version_class(s), False 

126 clist.append((op, vn, prefix)) 

127 self._parts = tuple(clist) 

128 

129 def match(self, version): 

130 """ 

131 Check if the provided version matches the constraints. 

132 

133 :param version: The version to match against this instance. 

134 :type version: String or :class:`Version` instance. 

135 """ 

136 if isinstance(version, string_types): 

137 version = self.version_class(version) 

138 for operator, constraint, prefix in self._parts: 

139 f = self._operators.get(operator) 

140 if isinstance(f, string_types): 

141 f = getattr(self, f) 

142 if not f: 

143 msg = ('%r not implemented ' 

144 'for %s' % (operator, self.__class__.__name__)) 

145 raise NotImplementedError(msg) 

146 if not f(version, constraint, prefix): 

147 return False 

148 return True 

149 

150 @property 

151 def exact_version(self): 

152 result = None 

153 if len(self._parts) == 1 and self._parts[0][0] in ('==', '==='): 

154 result = self._parts[0][1] 

155 return result 

156 

157 def _check_compatible(self, other): 

158 if type(self) != type(other) or self.name != other.name: 

159 raise TypeError('cannot compare %s and %s' % (self, other)) 

160 

161 def __eq__(self, other): 

162 self._check_compatible(other) 

163 return self.key == other.key and self._parts == other._parts 

164 

165 def __ne__(self, other): 

166 return not self.__eq__(other) 

167 

168 # See http://docs.python.org/reference/datamodel#object.__hash__ 

169 def __hash__(self): 

170 return hash(self.key) + hash(self._parts) 

171 

172 def __repr__(self): 

173 return "%s(%r)" % (self.__class__.__name__, self._string) 

174 

175 def __str__(self): 

176 return self._string 

177 

178 

179PEP440_VERSION_RE = re.compile(r'^v?([0-9]+!)?([0-9]+(\.[0-9]+)*)((a|alpha|b|beta|c|rc|pre|preview)([0-9]+)?)?' 

180 r'(\.(post|r|rev)([0-9]+)?)?([._-]?(dev)([0-9]+)?)?' 

181 r'(\+([a-zA-Z0-9]+([._-][a-zA-Z0-9]+)*))?$', re.I | getattr(re, 'ASCII', 0)) 

182 

183_PRE_RELEASE_TAGS = {'alpha': 'a', 'beta': 'b', 'c': 'rc', 'pre': 'rc', 'preview': 'rc'} 

184 

185 

186def _pep_440_key(s, match=None, release=None): 

187 """Return the comparison key, optionally reusing the parsed release tuple and regex match.""" 

188 s = s.strip() 

189 m = match if match is not None else PEP440_VERSION_RE.match(s) 

190 if m is None: 

191 raise UnsupportedVersionError('Not a valid version: %s' % s) 

192 groups = m.groups() 

193 nums = release if release is not None else tuple(map(int, groups[1].split('.'))) 

194 # Strip trailing-zero release segments (keeping at least one component) in a 

195 # single pass. Slicing one element off at a time rebuilt the whole tuple on 

196 # every iteration, which is O(n^2) for a version with many trailing zeros and 

197 # lets a crafted version string from package metadata stall the parser (CWE-407). 

198 end = len(nums) 

199 while end > 1 and nums[end - 1] == 0: 

200 end -= 1 

201 nums = nums[:end] 

202 

203 if not groups[0]: 

204 epoch = 0 

205 else: 

206 epoch = int(groups[0][:-1]) 

207 pre = groups[4:6] 

208 post = groups[7:9] 

209 dev = groups[10:12] 

210 local = groups[13] 

211 if pre == (None, None): 

212 pre = () 

213 else: 

214 letter = pre[0].lower() 

215 letter = _PRE_RELEASE_TAGS.get(letter, letter) 

216 if pre[1] is None: 

217 pre = letter, 0 

218 else: 

219 pre = letter, int(pre[1]) 

220 if post == (None, None): 

221 post = () 

222 else: 

223 if post[1] is None: 

224 post = 'post', 0 

225 else: 

226 post = 'post', int(post[1]) 

227 if dev == (None, None): 

228 dev = () 

229 else: 

230 if dev[1] is None: 

231 dev = 'dev', 0 

232 else: 

233 dev = 'dev', int(dev[1]) 

234 if local is None: 

235 local = () 

236 else: 

237 parts = [] 

238 for part in local.lower().replace('_', '.').replace('-', '.').split('.'): 

239 # to ensure that numeric compares as > lexicographic, avoid 

240 # comparing them directly, but encode a tuple which ensures 

241 # correct sorting 

242 if part.isdigit(): 

243 part = (1, int(part)) 

244 else: 

245 part = (0, part) 

246 parts.append(part) 

247 local = tuple(parts) 

248 if not pre: 

249 # either before pre-release, or final release and after 

250 if not post and dev: 

251 # before pre-release 

252 pre = ('a', -1) # to sort before a0 

253 else: 

254 pre = ('z',) # to sort after all pre-releases 

255 # now look at the state of post and dev. 

256 if not post: 

257 post = ('_',) # sort before 'a' 

258 if not dev: 

259 dev = ('final',) 

260 

261 return epoch, nums, pre, post, dev, local 

262 

263 

264_normalized_key = _pep_440_key 

265 

266 

267class NormalizedVersion(Version): 

268 """A rational version. 

269 

270 Good: 

271 1.2 # equivalent to "1.2.0" 

272 1.2.0 

273 1.2a1 

274 1.2.3a2 

275 1.2.3b1 

276 1.2.3c1 

277 1.2.3.4 

278 TODO: fill this out 

279 

280 Bad: 

281 1 # minimum two numbers 

282 1.2a # release level must have a release serial 

283 1.2.3b 

284 """ 

285 def parse(self, s): 

286 m = PEP440_VERSION_RE.match(s) 

287 if not m: 

288 raise UnsupportedVersionError('Not a valid version: %s' % s) 

289 release = tuple(map(int, m.groups()[1].split('.'))) 

290 result = _normalized_key(s, match=m, release=release) 

291 # _normalized_key loses trailing zeroes in the release 

292 # clause, since that's needed to ensure that X.Y == X.Y.0 == X.Y.0.0 

293 # However, PEP 440 prefix matching needs it: for example, 

294 # (~= 1.4.5.0) matches differently to (~= 1.4.5.0.0). 

295 self._release_clause = release 

296 return result 

297 

298 PREREL_TAGS = set(['a', 'b', 'c', 'rc', 'dev']) 

299 

300 @property 

301 def is_prerelease(self): 

302 return self._parts[2][0] in self.PREREL_TAGS or self._parts[4][0] == 'dev' 

303 

304 

305def _match_prefix(x, y): 

306 x = str(x) 

307 y = str(y) 

308 if x == y: 

309 return True 

310 if not x.startswith(y): 

311 return False 

312 n = len(y) 

313 return x[n] == '.' 

314 

315 

316class NormalizedMatcher(Matcher): 

317 version_class = NormalizedVersion 

318 

319 # value is either a callable or the name of a method 

320 _operators = { 

321 '~=': '_match_compatible', 

322 '<': '_match_lt', 

323 '>': '_match_gt', 

324 '<=': '_match_le', 

325 '>=': '_match_ge', 

326 '==': '_match_eq', 

327 '===': '_match_arbitrary', 

328 '!=': '_match_ne', 

329 } 

330 

331 def _adjust_local(self, version, constraint, prefix): 

332 if prefix: 

333 strip_local = '+' not in constraint and version._parts[-1] 

334 else: 

335 # both constraint and version are 

336 # NormalizedVersion instances. 

337 # If constraint does not have a local component, 

338 # ensure the version doesn't, either. 

339 strip_local = not constraint._parts[-1] and version._parts[-1] 

340 if strip_local: 

341 s = version._string.split('+', 1)[0] 

342 version = self.version_class(s) 

343 return version, constraint 

344 

345 def _match_lt(self, version, constraint, prefix): 

346 version, constraint = self._adjust_local(version, constraint, prefix) 

347 if version >= constraint: 

348 return False 

349 release_clause = constraint._release_clause 

350 pfx = '.'.join([str(i) for i in release_clause]) 

351 return not _match_prefix(version, pfx) 

352 

353 def _match_gt(self, version, constraint, prefix): 

354 version, constraint = self._adjust_local(version, constraint, prefix) 

355 if version <= constraint: 

356 return False 

357 release_clause = constraint._release_clause 

358 pfx = '.'.join([str(i) for i in release_clause]) 

359 return not _match_prefix(version, pfx) 

360 

361 def _match_le(self, version, constraint, prefix): 

362 version, constraint = self._adjust_local(version, constraint, prefix) 

363 return version <= constraint 

364 

365 def _match_ge(self, version, constraint, prefix): 

366 version, constraint = self._adjust_local(version, constraint, prefix) 

367 return version >= constraint 

368 

369 def _match_eq(self, version, constraint, prefix): 

370 version, constraint = self._adjust_local(version, constraint, prefix) 

371 if not prefix: 

372 result = (version == constraint) 

373 else: 

374 result = _match_prefix(version, constraint) 

375 return result 

376 

377 def _match_arbitrary(self, version, constraint, prefix): 

378 return str(version) == str(constraint) 

379 

380 def _match_ne(self, version, constraint, prefix): 

381 version, constraint = self._adjust_local(version, constraint, prefix) 

382 if not prefix: 

383 result = (version != constraint) 

384 else: 

385 result = not _match_prefix(version, constraint) 

386 return result 

387 

388 def _match_compatible(self, version, constraint, prefix): 

389 version, constraint = self._adjust_local(version, constraint, prefix) 

390 if version == constraint: 

391 return True 

392 if version < constraint: 

393 return False 

394# if not prefix: 

395# return True 

396 release_clause = constraint._release_clause 

397 if len(release_clause) > 1: 

398 release_clause = release_clause[:-1] 

399 pfx = '.'.join([str(i) for i in release_clause]) 

400 return _match_prefix(version, pfx) 

401 

402 

403_REPLACEMENTS = ( 

404 (re.compile('[.+-]$'), ''), # remove trailing puncts 

405 (re.compile(r'^[.](\d)'), r'0.\1'), # .N -> 0.N at start 

406 (re.compile('^[.-]'), ''), # remove leading puncts 

407 (re.compile(r'^\((.*)\)$'), r'\1'), # remove parentheses 

408 (re.compile(r'^v(ersion)?\s*(\d+)'), r'\2'), # remove leading v(ersion) 

409 (re.compile(r'^r(ev)?\s*(\d+)'), r'\2'), # remove leading v(ersion) 

410 (re.compile('[.]{2,}'), '.'), # multiple runs of '.' 

411 (re.compile(r'\b(alfa|apha)\b'), 'alpha'), # misspelt alpha 

412 (re.compile(r'\b(pre-alpha|prealpha)\b'), 

413 'pre.alpha'), # standardise 

414 (re.compile(r'\(beta\)$'), 'beta'), # remove parentheses 

415) 

416 

417_SUFFIX_REPLACEMENTS = ( 

418 (re.compile('^[:~._+-]+'), ''), # remove leading puncts 

419 (re.compile('[,*")([\\]]'), ''), # remove unwanted chars 

420 (re.compile('[~:+_ -]'), '.'), # replace illegal chars 

421 (re.compile('[.]{2,}'), '.'), # multiple runs of '.' 

422 (re.compile(r'\.$'), ''), # trailing '.' 

423) 

424 

425_NUMERIC_PREFIX = re.compile(r'(\d+(\.\d+)*)') 

426 

427 

428def _suggest_semantic_version(s): 

429 """ 

430 Try to suggest a semantic form for a version for which 

431 _suggest_normalized_version couldn't come up with anything. 

432 """ 

433 result = s.strip().lower() 

434 for pat, repl in _REPLACEMENTS: 

435 result = pat.sub(repl, result) 

436 if not result: 

437 result = '0.0.0' 

438 

439 # Now look for numeric prefix, and separate it out from 

440 # the rest. 

441 # import pdb; pdb.set_trace() 

442 m = _NUMERIC_PREFIX.match(result) 

443 if not m: 

444 prefix = '0.0.0' 

445 suffix = result 

446 else: 

447 prefix = m.groups()[0].split('.') 

448 prefix = [int(i) for i in prefix] 

449 while len(prefix) < 3: 

450 prefix.append(0) 

451 if len(prefix) == 3: 

452 suffix = result[m.end():] 

453 else: 

454 suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():] 

455 prefix = prefix[:3] 

456 prefix = '.'.join([str(i) for i in prefix]) 

457 suffix = suffix.strip() 

458 if suffix: 

459 # import pdb; pdb.set_trace() 

460 # massage the suffix. 

461 for pat, repl in _SUFFIX_REPLACEMENTS: 

462 suffix = pat.sub(repl, suffix) 

463 

464 if not suffix: 

465 result = prefix 

466 else: 

467 sep = '-' if 'dev' in suffix else '+' 

468 result = prefix + sep + suffix 

469 if not is_semver(result): 

470 result = None 

471 return result 

472 

473 

474def _suggest_normalized_version(s): 

475 """Suggest a normalized version close to the given version string. 

476 

477 If you have a version string that isn't rational (i.e. NormalizedVersion 

478 doesn't like it) then you might be able to get an equivalent (or close) 

479 rational version from this function. 

480 

481 This does a number of simple normalizations to the given string, based 

482 on observation of versions currently in use on PyPI. Given a dump of 

483 those version during PyCon 2009, 4287 of them: 

484 - 2312 (53.93%) match NormalizedVersion without change 

485 with the automatic suggestion 

486 - 3474 (81.04%) match when using this suggestion method 

487 

488 @param s {str} An irrational version string. 

489 @returns A rational version string, or None, if couldn't determine one. 

490 """ 

491 try: 

492 _normalized_key(s) 

493 return s # already rational 

494 except UnsupportedVersionError: 

495 pass 

496 

497 rs = s.lower() 

498 

499 # part of this could use maketrans 

500 for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'), 

501 ('beta', 'b'), ('rc', 'c'), ('-final', ''), 

502 ('-pre', 'c'), 

503 ('-release', ''), ('.release', ''), ('-stable', ''), 

504 ('+', '.'), ('_', '.'), (' ', ''), ('.final', ''), 

505 ('final', '')): 

506 rs = rs.replace(orig, repl) 

507 

508 # if something ends with dev or pre, we add a 0 

509 rs = re.sub(r"pre$", r"pre0", rs) 

510 rs = re.sub(r"dev$", r"dev0", rs) 

511 

512 # if we have something like "b-2" or "a.2" at the end of the 

513 # version, that is probably beta, alpha, etc 

514 # let's remove the dash or dot 

515 rs = re.sub(r"([abc]|rc)[\-\.](\d+)$", r"\1\2", rs) 

516 

517 # 1.0-dev-r371 -> 1.0.dev371 

518 # 0.1-dev-r79 -> 0.1.dev79 

519 rs = re.sub(r"[\-\.](dev)[\-\.]?r?(\d+)$", r".\1\2", rs) 

520 

521 # Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1 

522 rs = re.sub(r"[.~]?([abc])\.?", r"\1", rs) 

523 

524 # Clean: v0.3, v1.0 

525 if rs.startswith('v'): 

526 rs = rs[1:] 

527 

528 # Clean leading '0's on numbers. 

529 # TODO: unintended side-effect on, e.g., "2003.05.09" 

530 # PyPI stats: 77 (~2%) better 

531 rs = re.sub(r"\b0+(\d+)(?!\d)", r"\1", rs) 

532 

533 # Clean a/b/c with no version. E.g. "1.0a" -> "1.0a0". Setuptools infers 

534 # zero. 

535 # PyPI stats: 245 (7.56%) better 

536 rs = re.sub(r"(\d+[abc])$", r"\g<1>0", rs) 

537 

538 # the 'dev-rNNN' tag is a dev tag 

539 rs = re.sub(r"\.?(dev-r|dev\.r)\.?(\d+)$", r".dev\2", rs) 

540 

541 # clean the - when used as a pre delimiter 

542 rs = re.sub(r"-(a|b|c)(\d+)$", r"\1\2", rs) 

543 

544 # a terminal "dev" or "devel" can be changed into ".dev0" 

545 rs = re.sub(r"[\.\-](dev|devel)$", r".dev0", rs) 

546 

547 # a terminal "dev" can be changed into ".dev0" 

548 rs = re.sub(r"(?![\.\-])dev$", r".dev0", rs) 

549 

550 # a terminal "final" or "stable" can be removed 

551 rs = re.sub(r"(final|stable)$", "", rs) 

552 

553 # The 'r' and the '-' tags are post release tags 

554 # 0.4a1.r10 -> 0.4a1.post10 

555 # 0.9.33-17222 -> 0.9.33.post17222 

556 # 0.9.33-r17222 -> 0.9.33.post17222 

557 rs = re.sub(r"\.?(r|-|-r)\.?(\d+)$", r".post\2", rs) 

558 

559 # Clean 'r' instead of 'dev' usage: 

560 # 0.9.33+r17222 -> 0.9.33.dev17222 

561 # 1.0dev123 -> 1.0.dev123 

562 # 1.0.git123 -> 1.0.dev123 

563 # 1.0.bzr123 -> 1.0.dev123 

564 # 0.1a0dev.123 -> 0.1a0.dev123 

565 # PyPI stats: ~150 (~4%) better 

566 rs = re.sub(r"\.?(dev|git|bzr)\.?(\d+)$", r".dev\2", rs) 

567 

568 # Clean '.pre' (normalized from '-pre' above) instead of 'c' usage: 

569 # 0.2.pre1 -> 0.2c1 

570 # 0.2-c1 -> 0.2c1 

571 # 1.0preview123 -> 1.0c123 

572 # PyPI stats: ~21 (0.62%) better 

573 rs = re.sub(r"\.?(pre|preview|-c)(\d+)$", r"c\g<2>", rs) 

574 

575 # Tcl/Tk uses "px" for their post release markers 

576 rs = re.sub(r"p(\d+)$", r".post\1", rs) 

577 

578 try: 

579 _normalized_key(rs) 

580 except UnsupportedVersionError: 

581 rs = None 

582 return rs 

583 

584# 

585# Legacy version processing (distribute-compatible) 

586# 

587 

588 

589_VERSION_PART = re.compile(r'([a-z]+|\d+|[\.-])', re.I) 

590_VERSION_REPLACE = { 

591 'pre': 'c', 

592 'preview': 'c', 

593 '-': 'final-', 

594 'rc': 'c', 

595 'dev': '@', 

596 '': None, 

597 '.': None, 

598} 

599 

600 

601def _legacy_key(s): 

602 def get_parts(s): 

603 result = [] 

604 for p in _VERSION_PART.split(s.lower()): 

605 p = _VERSION_REPLACE.get(p, p) 

606 if p: 

607 if '0' <= p[:1] <= '9': 

608 p = p.zfill(8) 

609 else: 

610 p = '*' + p 

611 result.append(p) 

612 result.append('*final') 

613 return result 

614 

615 result = [] 

616 for p in get_parts(s): 

617 if p.startswith('*'): 

618 if p < '*final': 

619 while result and result[-1] == '*final-': 

620 result.pop() 

621 while result and result[-1] == '00000000': 

622 result.pop() 

623 result.append(p) 

624 return tuple(result) 

625 

626 

627class LegacyVersion(Version): 

628 def parse(self, s): 

629 return _legacy_key(s) 

630 

631 @property 

632 def is_prerelease(self): 

633 result = False 

634 for x in self._parts: 

635 if (isinstance(x, string_types) and x.startswith('*') and x < '*final'): 

636 result = True 

637 break 

638 return result 

639 

640 

641class LegacyMatcher(Matcher): 

642 version_class = LegacyVersion 

643 

644 _operators = dict(Matcher._operators) 

645 _operators['~='] = '_match_compatible' 

646 

647 numeric_re = re.compile(r'^(\d+(\.\d+)*)') 

648 

649 def _match_compatible(self, version, constraint, prefix): 

650 if version < constraint: 

651 return False 

652 m = self.numeric_re.match(str(constraint)) 

653 if not m: 

654 logger.warning('Cannot compute compatible match for version %s ' 

655 ' and constraint %s', version, constraint) 

656 return True 

657 s = m.groups()[0] 

658 if '.' in s: 

659 s = s.rsplit('.', 1)[0] 

660 return _match_prefix(version, s) 

661 

662# 

663# Semantic versioning 

664# 

665 

666 

667_SEMVER_RE = re.compile(r'^(\d+)\.(\d+)\.(\d+)' 

668 r'(-[a-z0-9]+(\.[a-z0-9-]+)*)?' 

669 r'(\+[a-z0-9]+(\.[a-z0-9-]+)*)?$', re.I) 

670 

671 

672def is_semver(s): 

673 return _SEMVER_RE.match(s) 

674 

675 

676def _semantic_key(s): 

677 def make_tuple(s, absent): 

678 if s is None: 

679 result = (absent,) 

680 else: 

681 parts = s[1:].split('.') 

682 # We can't compare ints and strings on Python 3, so fudge it 

683 # by zero-filling numeric values so simulate a numeric comparison 

684 result = tuple([p.zfill(8) if p.isdigit() else p for p in parts]) 

685 return result 

686 

687 m = is_semver(s) 

688 if not m: 

689 raise UnsupportedVersionError(s) 

690 groups = m.groups() 

691 major, minor, patch = [int(i) for i in groups[:3]] 

692 # Numeric prerelease identifiers compare numerically, below nonnumeric ones. 

693 # An absent prerelease sorts above either kind of identifier. 

694 if groups[3] is None: 

695 pre = ((2,),) 

696 else: 

697 pre = tuple((0, int(p)) if p.isdigit() else (1, p) 

698 for p in groups[3][1:].split('.')) 

699 build = make_tuple(groups[5], '*') 

700 return (major, minor, patch), pre, build 

701 

702 

703class SemanticVersion(Version): 

704 def parse(self, s): 

705 return _semantic_key(s) 

706 

707 @property 

708 def is_prerelease(self): 

709 return self._parts[1][0] != (2,) 

710 

711 

712class SemanticMatcher(Matcher): 

713 version_class = SemanticVersion 

714 

715 

716class VersionScheme(object): 

717 def __init__(self, key, matcher, suggester=None): 

718 self.key = key 

719 self.matcher = matcher 

720 self.suggester = suggester 

721 

722 def is_valid_version(self, s): 

723 try: 

724 self.matcher.version_class(s) 

725 result = True 

726 except UnsupportedVersionError: 

727 result = False 

728 return result 

729 

730 def is_valid_matcher(self, s): 

731 try: 

732 self.matcher(s) 

733 result = True 

734 except UnsupportedVersionError: 

735 result = False 

736 return result 

737 

738 def is_valid_constraint_list(self, s): 

739 """ 

740 Used for processing some metadata fields 

741 """ 

742 # See issue #140. Be tolerant of a single trailing comma. 

743 if s.endswith(','): 

744 s = s[:-1] 

745 return self.is_valid_matcher('dummy_name (%s)' % s) 

746 

747 def suggest(self, s): 

748 if self.suggester is None: 

749 result = None 

750 else: 

751 result = self.suggester(s) 

752 return result 

753 

754 

755_SCHEMES = { 

756 'normalized': VersionScheme(_normalized_key, NormalizedMatcher, 

757 _suggest_normalized_version), 

758 'legacy': VersionScheme(_legacy_key, LegacyMatcher, lambda s: s), 

759 'semantic': VersionScheme(_semantic_key, SemanticMatcher, 

760 _suggest_semantic_version), 

761} 

762 

763_SCHEMES['default'] = _SCHEMES['normalized'] 

764 

765 

766def get_scheme(name): 

767 if name not in _SCHEMES: 

768 raise ValueError('unknown scheme name: %r' % name) 

769 return _SCHEMES[name]