utils.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. from __future__ import absolute_import, division, print_function
  5. import re
  6. from ._typing import MYPY_CHECK_RUNNING
  7. from .version import InvalidVersion, Version
  8. if MYPY_CHECK_RUNNING: # pragma: no cover
  9. from typing import Union
  10. _canonicalize_regex = re.compile(r"[-_.]+")
  11. def canonicalize_name(name):
  12. # type: (str) -> str
  13. # This is taken from PEP 503.
  14. return _canonicalize_regex.sub("-", name).lower()
  15. def canonicalize_version(_version):
  16. # type: (str) -> Union[Version, str]
  17. """
  18. This is very similar to Version.__str__, but has one subtle difference
  19. with the way it handles the release segment.
  20. """
  21. try:
  22. version = Version(_version)
  23. except InvalidVersion:
  24. # Legacy versions cannot be normalized
  25. return _version
  26. parts = []
  27. # Epoch
  28. if version.epoch != 0:
  29. parts.append("{0}!".format(version.epoch))
  30. # Release segment
  31. # NB: This strips trailing '.0's to normalize
  32. parts.append(re.sub(r"(\.0)+$", "", ".".join(str(x) for x in version.release)))
  33. # Pre-release
  34. if version.pre is not None:
  35. parts.append("".join(str(x) for x in version.pre))
  36. # Post-release
  37. if version.post is not None:
  38. parts.append(".post{0}".format(version.post))
  39. # Development release
  40. if version.dev is not None:
  41. parts.append(".dev{0}".format(version.dev))
  42. # Local version segment
  43. if version.local is not None:
  44. parts.append("+{0}".format(version.local))
  45. return "".join(parts)