1
1
Fork 0
mirror of https://github.com/pypa/pip synced 2023-12-13 21:30:23 +01:00
pip/src/pip/_vendor/packaging/utils.py

63 lines
1.7 KiB
Python
Raw Normal View History

2016-02-09 23:52:29 +01:00
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
import re
2020-01-06 20:04:07 +01:00
from ._typing import MYPY_CHECK_RUNNING
2018-03-20 16:23:38 +01:00
from .version import InvalidVersion, Version
2020-01-06 20:04:07 +01:00
if MYPY_CHECK_RUNNING: # pragma: no cover
from typing import Union
2016-02-09 23:52:29 +01:00
_canonicalize_regex = re.compile(r"[-_.]+")
def canonicalize_name(name):
2020-01-06 20:04:07 +01:00
# type: (str) -> str
2016-02-09 23:52:29 +01:00
# This is taken from PEP 503.
return _canonicalize_regex.sub("-", name).lower()
2018-03-20 16:23:38 +01:00
2020-01-06 20:04:07 +01:00
def canonicalize_version(_version):
# type: (str) -> Union[Version, str]
2018-03-20 16:23:38 +01:00
"""
2020-01-06 20:04:07 +01:00
This is very similar to Version.__str__, but has one subtle difference
2018-03-20 16:23:38 +01:00
with the way it handles the release segment.
"""
try:
2020-01-06 20:04:07 +01:00
version = Version(_version)
2018-03-20 16:23:38 +01:00
except InvalidVersion:
# Legacy versions cannot be normalized
2020-01-06 20:04:07 +01:00
return _version
2018-03-20 16:23:38 +01:00
parts = []
# Epoch
if version.epoch != 0:
parts.append("{0}!".format(version.epoch))
# Release segment
# NB: This strips trailing '.0's to normalize
2019-01-20 12:22:52 +01:00
parts.append(re.sub(r"(\.0)+$", "", ".".join(str(x) for x in version.release)))
2018-03-20 16:23:38 +01:00
# Pre-release
if version.pre is not None:
parts.append("".join(str(x) for x in version.pre))
# Post-release
if version.post is not None:
parts.append(".post{0}".format(version.post))
# Development release
if version.dev is not None:
parts.append(".dev{0}".format(version.dev))
# Local version segment
if version.local is not None:
parts.append("+{0}".format(version.local))
return "".join(parts)