Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/packaging/version.py: 27%

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

167 statements  

1# This file is dual licensed under the terms of the Apache License, Version 

2# 2.0, and the BSD License. See the LICENSE file in the root of this repository 

3# for complete details. 

4""" 

5.. testsetup:: 

6 

7 from packaging.version import parse, Version 

8""" 

9 

10from __future__ import annotations 

11 

12import itertools 

13import re 

14from typing import Any, Callable, NamedTuple, SupportsInt, Tuple, Union 

15 

16from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType 

17 

18__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"] 

19 

20LocalType = Tuple[Union[int, str], ...] 

21 

22CmpPrePostDevType = Union[InfinityType, NegativeInfinityType, Tuple[str, int]] 

23CmpLocalType = Union[ 

24 NegativeInfinityType, 

25 Tuple[Union[Tuple[int, str], Tuple[NegativeInfinityType, Union[int, str]]], ...], 

26] 

27CmpKey = Tuple[ 

28 int, 

29 Tuple[int, ...], 

30 CmpPrePostDevType, 

31 CmpPrePostDevType, 

32 CmpPrePostDevType, 

33 CmpLocalType, 

34] 

35VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool] 

36 

37 

38class _Version(NamedTuple): 

39 epoch: int 

40 release: tuple[int, ...] 

41 dev: tuple[str, int] | None 

42 pre: tuple[str, int] | None 

43 post: tuple[str, int] | None 

44 local: LocalType | None 

45 

46 

47def parse(version: str) -> Version: 

48 """Parse the given version string. 

49 

50 >>> parse('1.0.dev1') 

51 <Version('1.0.dev1')> 

52 

53 :param version: The version string to parse. 

54 :raises InvalidVersion: When the version string is not a valid version. 

55 """ 

56 return Version(version) 

57 

58 

59class InvalidVersion(ValueError): 

60 """Raised when a version string is not a valid version. 

61 

62 >>> Version("invalid") 

63 Traceback (most recent call last): 

64 ... 

65 packaging.version.InvalidVersion: Invalid version: 'invalid' 

66 """ 

67 

68 

69class _BaseVersion: 

70 _key: tuple[Any, ...] 

71 

72 def __hash__(self) -> int: 

73 return hash(self._key) 

74 

75 # Please keep the duplicated `isinstance` check 

76 # in the six comparisons hereunder 

77 # unless you find a way to avoid adding overhead function calls. 

78 def __lt__(self, other: _BaseVersion) -> bool: 

79 if not isinstance(other, _BaseVersion): 

80 return NotImplemented 

81 

82 return self._key < other._key 

83 

84 def __le__(self, other: _BaseVersion) -> bool: 

85 if not isinstance(other, _BaseVersion): 

86 return NotImplemented 

87 

88 return self._key <= other._key 

89 

90 def __eq__(self, other: object) -> bool: 

91 if not isinstance(other, _BaseVersion): 

92 return NotImplemented 

93 

94 return self._key == other._key 

95 

96 def __ge__(self, other: _BaseVersion) -> bool: 

97 if not isinstance(other, _BaseVersion): 

98 return NotImplemented 

99 

100 return self._key >= other._key 

101 

102 def __gt__(self, other: _BaseVersion) -> bool: 

103 if not isinstance(other, _BaseVersion): 

104 return NotImplemented 

105 

106 return self._key > other._key 

107 

108 def __ne__(self, other: object) -> bool: 

109 if not isinstance(other, _BaseVersion): 

110 return NotImplemented 

111 

112 return self._key != other._key 

113 

114 

115# Deliberately not anchored to the start and end of the string, to make it 

116# easier for 3rd party code to reuse 

117_VERSION_PATTERN = r""" 

118 v? 

119 (?: 

120 (?:(?P<epoch>[0-9]+)!)? # epoch 

121 (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment 

122 (?P<pre> # pre-release 

123 [-_\.]? 

124 (?P<pre_l>alpha|a|beta|b|preview|pre|c|rc) 

125 [-_\.]? 

126 (?P<pre_n>[0-9]+)? 

127 )? 

128 (?P<post> # post release 

129 (?:-(?P<post_n1>[0-9]+)) 

130 | 

131 (?: 

132 [-_\.]? 

133 (?P<post_l>post|rev|r) 

134 [-_\.]? 

135 (?P<post_n2>[0-9]+)? 

136 ) 

137 )? 

138 (?P<dev> # dev release 

139 [-_\.]? 

140 (?P<dev_l>dev) 

141 [-_\.]? 

142 (?P<dev_n>[0-9]+)? 

143 )? 

144 ) 

145 (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version 

146""" 

147 

148VERSION_PATTERN = _VERSION_PATTERN 

149""" 

150A string containing the regular expression used to match a valid version. 

151 

152The pattern is not anchored at either end, and is intended for embedding in larger 

153expressions (for example, matching a version number as part of a file name). The 

154regular expression should be compiled with the ``re.VERBOSE`` and ``re.IGNORECASE`` 

155flags set. 

156 

157:meta hide-value: 

158""" 

159 

160 

161class Version(_BaseVersion): 

162 """This class abstracts handling of a project's versions. 

163 

164 A :class:`Version` instance is comparison aware and can be compared and 

165 sorted using the standard Python interfaces. 

166 

167 >>> v1 = Version("1.0a5") 

168 >>> v2 = Version("1.0") 

169 >>> v1 

170 <Version('1.0a5')> 

171 >>> v2 

172 <Version('1.0')> 

173 >>> v1 < v2 

174 True 

175 >>> v1 == v2 

176 False 

177 >>> v1 > v2 

178 False 

179 >>> v1 >= v2 

180 False 

181 >>> v1 <= v2 

182 True 

183 """ 

184 

185 _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE) 

186 _version: _Version 

187 _key: CmpKey 

188 

189 def __init__(self, version: str) -> None: 

190 """Initialize a Version object. 

191 

192 :param version: 

193 The string representation of a version which will be parsed and normalized 

194 before use. 

195 :raises InvalidVersion: 

196 If the ``version`` does not conform to PEP 440 in any way then this 

197 exception will be raised. 

198 """ 

199 

200 # Validate the version and parse it into pieces 

201 match = self._regex.search(version) 

202 if not match: 

203 raise InvalidVersion(f"Invalid version: {version!r}") 

204 

205 # Store the parsed out pieces of the version 

206 self._version = _Version( 

207 epoch=int(match.group("epoch")) if match.group("epoch") else 0, 

208 release=tuple(int(i) for i in match.group("release").split(".")), 

209 pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")), 

210 post=_parse_letter_version( 

211 match.group("post_l"), match.group("post_n1") or match.group("post_n2") 

212 ), 

213 dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")), 

214 local=_parse_local_version(match.group("local")), 

215 ) 

216 

217 # Generate a key which will be used for sorting 

218 self._key = _cmpkey( 

219 self._version.epoch, 

220 self._version.release, 

221 self._version.pre, 

222 self._version.post, 

223 self._version.dev, 

224 self._version.local, 

225 ) 

226 

227 def __repr__(self) -> str: 

228 """A representation of the Version that shows all internal state. 

229 

230 >>> Version('1.0.0') 

231 <Version('1.0.0')> 

232 """ 

233 return f"<Version('{self}')>" 

234 

235 def __str__(self) -> str: 

236 """A string representation of the version that can be round-tripped. 

237 

238 >>> str(Version("1.0a5")) 

239 '1.0a5' 

240 """ 

241 parts = [self.base_version] 

242 

243 # Pre-release 

244 if self.pre is not None: 

245 parts.append("".join(str(x) for x in self.pre)) 

246 

247 # Post-release 

248 if self.post is not None: 

249 parts.append(f".post{self.post}") 

250 

251 # Development release 

252 if self.dev is not None: 

253 parts.append(f".dev{self.dev}") 

254 

255 # Local version segment 

256 if self.local is not None: 

257 parts.append(f"+{self.local}") 

258 

259 return "".join(parts) 

260 

261 @property 

262 def epoch(self) -> int: 

263 """The epoch of the version. 

264 

265 >>> Version("2.0.0").epoch 

266 0 

267 >>> Version("1!2.0.0").epoch 

268 1 

269 """ 

270 return self._version.epoch 

271 

272 @property 

273 def release(self) -> tuple[int, ...]: 

274 """The components of the "release" segment of the version. 

275 

276 >>> Version("1.2.3").release 

277 (1, 2, 3) 

278 >>> Version("2.0.0").release 

279 (2, 0, 0) 

280 >>> Version("1!2.0.0.post0").release 

281 (2, 0, 0) 

282 

283 Includes trailing zeroes but not the epoch or any pre-release / development / 

284 post-release suffixes. 

285 """ 

286 return self._version.release 

287 

288 @property 

289 def pre(self) -> tuple[str, int] | None: 

290 """The pre-release segment of the version. 

291 

292 >>> print(Version("1.2.3").pre) 

293 None 

294 >>> Version("1.2.3a1").pre 

295 ('a', 1) 

296 >>> Version("1.2.3b1").pre 

297 ('b', 1) 

298 >>> Version("1.2.3rc1").pre 

299 ('rc', 1) 

300 """ 

301 return self._version.pre 

302 

303 @property 

304 def post(self) -> int | None: 

305 """The post-release number of the version. 

306 

307 >>> print(Version("1.2.3").post) 

308 None 

309 >>> Version("1.2.3.post1").post 

310 1 

311 """ 

312 return self._version.post[1] if self._version.post else None 

313 

314 @property 

315 def dev(self) -> int | None: 

316 """The development number of the version. 

317 

318 >>> print(Version("1.2.3").dev) 

319 None 

320 >>> Version("1.2.3.dev1").dev 

321 1 

322 """ 

323 return self._version.dev[1] if self._version.dev else None 

324 

325 @property 

326 def local(self) -> str | None: 

327 """The local version segment of the version. 

328 

329 >>> print(Version("1.2.3").local) 

330 None 

331 >>> Version("1.2.3+abc").local 

332 'abc' 

333 """ 

334 if self._version.local: 

335 return ".".join(str(x) for x in self._version.local) 

336 else: 

337 return None 

338 

339 @property 

340 def public(self) -> str: 

341 """The public portion of the version. 

342 

343 >>> Version("1.2.3").public 

344 '1.2.3' 

345 >>> Version("1.2.3+abc").public 

346 '1.2.3' 

347 >>> Version("1!1.2.3dev1+abc").public 

348 '1!1.2.3.dev1' 

349 """ 

350 return str(self).split("+", 1)[0] 

351 

352 @property 

353 def base_version(self) -> str: 

354 """The "base version" of the version. 

355 

356 >>> Version("1.2.3").base_version 

357 '1.2.3' 

358 >>> Version("1.2.3+abc").base_version 

359 '1.2.3' 

360 >>> Version("1!1.2.3dev1+abc").base_version 

361 '1!1.2.3' 

362 

363 The "base version" is the public version of the project without any pre or post 

364 release markers. 

365 """ 

366 release_segment = ".".join(map(str, self.release)) 

367 return f"{self.epoch}!{release_segment}" if self.epoch else release_segment 

368 

369 @property 

370 def is_prerelease(self) -> bool: 

371 """Whether this version is a pre-release. 

372 

373 >>> Version("1.2.3").is_prerelease 

374 False 

375 >>> Version("1.2.3a1").is_prerelease 

376 True 

377 >>> Version("1.2.3b1").is_prerelease 

378 True 

379 >>> Version("1.2.3rc1").is_prerelease 

380 True 

381 >>> Version("1.2.3dev1").is_prerelease 

382 True 

383 """ 

384 return self.dev is not None or self.pre is not None 

385 

386 @property 

387 def is_postrelease(self) -> bool: 

388 """Whether this version is a post-release. 

389 

390 >>> Version("1.2.3").is_postrelease 

391 False 

392 >>> Version("1.2.3.post1").is_postrelease 

393 True 

394 """ 

395 return self.post is not None 

396 

397 @property 

398 def is_devrelease(self) -> bool: 

399 """Whether this version is a development release. 

400 

401 >>> Version("1.2.3").is_devrelease 

402 False 

403 >>> Version("1.2.3.dev1").is_devrelease 

404 True 

405 """ 

406 return self.dev is not None 

407 

408 @property 

409 def major(self) -> int: 

410 """The first item of :attr:`release` or ``0`` if unavailable. 

411 

412 >>> Version("1.2.3").major 

413 1 

414 """ 

415 return self.release[0] if len(self.release) >= 1 else 0 

416 

417 @property 

418 def minor(self) -> int: 

419 """The second item of :attr:`release` or ``0`` if unavailable. 

420 

421 >>> Version("1.2.3").minor 

422 2 

423 >>> Version("1").minor 

424 0 

425 """ 

426 return self.release[1] if len(self.release) >= 2 else 0 

427 

428 @property 

429 def micro(self) -> int: 

430 """The third item of :attr:`release` or ``0`` if unavailable. 

431 

432 >>> Version("1.2.3").micro 

433 3 

434 >>> Version("1").micro 

435 0 

436 """ 

437 return self.release[2] if len(self.release) >= 3 else 0 

438 

439 

440class _TrimmedRelease(Version): 

441 @property 

442 def release(self) -> tuple[int, ...]: 

443 """ 

444 Release segment without any trailing zeros. 

445 

446 >>> _TrimmedRelease('1.0.0').release 

447 (1,) 

448 >>> _TrimmedRelease('0.0').release 

449 (0,) 

450 """ 

451 rel = super().release 

452 i = len(rel) 

453 while i > 1 and rel[i - 1] == 0: 

454 i -= 1 

455 return rel[:i] 

456 

457 

458def _parse_letter_version( 

459 letter: str | None, number: str | bytes | SupportsInt | None 

460) -> tuple[str, int] | None: 

461 if letter: 

462 # We normalize any letters to their lower case form 

463 letter = letter.lower() 

464 

465 # We consider some words to be alternate spellings of other words and 

466 # in those cases we want to normalize the spellings to our preferred 

467 # spelling. 

468 if letter == "alpha": 

469 letter = "a" 

470 elif letter == "beta": 

471 letter = "b" 

472 elif letter in ["c", "pre", "preview"]: 

473 letter = "rc" 

474 elif letter in ["rev", "r"]: 

475 letter = "post" 

476 

477 # We consider there to be an implicit 0 in a pre-release if there is 

478 # not a numeral associated with it. 

479 return letter, int(number or 0) 

480 

481 if number: 

482 # We assume if we are given a number, but we are not given a letter 

483 # then this is using the implicit post release syntax (e.g. 1.0-1) 

484 return "post", int(number) 

485 

486 return None 

487 

488 

489_local_version_separators = re.compile(r"[\._-]") 

490 

491 

492def _parse_local_version(local: str | None) -> LocalType | None: 

493 """ 

494 Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve"). 

495 """ 

496 if local is not None: 

497 return tuple( 

498 part.lower() if not part.isdigit() else int(part) 

499 for part in _local_version_separators.split(local) 

500 ) 

501 return None 

502 

503 

504def _cmpkey( 

505 epoch: int, 

506 release: tuple[int, ...], 

507 pre: tuple[str, int] | None, 

508 post: tuple[str, int] | None, 

509 dev: tuple[str, int] | None, 

510 local: LocalType | None, 

511) -> CmpKey: 

512 # When we compare a release version, we want to compare it with all of the 

513 # trailing zeros removed. So we'll use a reverse the list, drop all the now 

514 # leading zeros until we come to something non zero, then take the rest 

515 # re-reverse it back into the correct order and make it a tuple and use 

516 # that for our sorting key. 

517 _release = tuple( 

518 reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release)))) 

519 ) 

520 

521 # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0. 

522 # We'll do this by abusing the pre segment, but we _only_ want to do this 

523 # if there is not a pre or a post segment. If we have one of those then 

524 # the normal sorting rules will handle this case correctly. 

525 if pre is None and post is None and dev is not None: 

526 _pre: CmpPrePostDevType = NegativeInfinity 

527 # Versions without a pre-release (except as noted above) should sort after 

528 # those with one. 

529 elif pre is None: 

530 _pre = Infinity 

531 else: 

532 _pre = pre 

533 

534 # Versions without a post segment should sort before those with one. 

535 if post is None: 

536 _post: CmpPrePostDevType = NegativeInfinity 

537 

538 else: 

539 _post = post 

540 

541 # Versions without a development segment should sort after those with one. 

542 if dev is None: 

543 _dev: CmpPrePostDevType = Infinity 

544 

545 else: 

546 _dev = dev 

547 

548 if local is None: 

549 # Versions without a local segment should sort before those with one. 

550 _local: CmpLocalType = NegativeInfinity 

551 else: 

552 # Versions with a local segment need that segment parsed to implement 

553 # the sorting rules in PEP440. 

554 # - Alpha numeric segments sort before numeric segments 

555 # - Alpha numeric segments sort lexicographically 

556 # - Numeric segments sort numerically 

557 # - Shorter versions sort before longer versions when the prefixes 

558 # match exactly 

559 _local = tuple( 

560 (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local 

561 ) 

562 

563 return epoch, _release, _pre, _post, _dev, _local