You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.5 KiB

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