|
| 1 | +# Copyright 2022 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import functools |
| 16 | +import re |
| 17 | + |
| 18 | +import semver |
| 19 | + |
| 20 | +_PAD_WIDTH = 8 |
| 21 | +_FAKE_PRE_WIDTH = 16 |
| 22 | + |
| 23 | + |
| 24 | +def _strip_leading_v(version): |
| 25 | + """Strip leading v from the version, if any.""" |
| 26 | + # Versions starting with "v" aren't valid SemVer, but we handle them just in |
| 27 | + # case. |
| 28 | + if version.startswith("v"): |
| 29 | + return version[1:] |
| 30 | + |
| 31 | + return version |
| 32 | + |
| 33 | + |
| 34 | +def _remove_leading_zero(component): |
| 35 | + """Remove leading zeros from a component.""" |
| 36 | + if component[0] == ".": |
| 37 | + return "." + str(int(component[1:])) |
| 38 | + |
| 39 | + return str(int(component)) |
| 40 | + |
| 41 | + |
| 42 | +def coerce(version): |
| 43 | + """Coerce a potentially invalid semver into valid semver.""" |
| 44 | + version = _strip_leading_v(version) |
| 45 | + version_pattern = re.compile(r"^(\d+)(\.\d+)?(\.\d+)?(.*)$") |
| 46 | + match = version_pattern.match(version) |
| 47 | + if not match: |
| 48 | + return version |
| 49 | + |
| 50 | + return ( |
| 51 | + _remove_leading_zero(match.group(1)) |
| 52 | + + _remove_leading_zero(match.group(2) or ".0") |
| 53 | + + _remove_leading_zero(match.group(3) or ".0") |
| 54 | + + match.group(4) |
| 55 | + ) |
| 56 | + |
| 57 | + |
| 58 | +def is_valid(version): |
| 59 | + """Returns whether or not the version is a valid semver.""" |
| 60 | + return semver.VersionInfo.isvalid(_strip_leading_v(version)) |
| 61 | + |
| 62 | + |
| 63 | +def parse(version): |
| 64 | + """Parse a SemVer.""" |
| 65 | + return semver.VersionInfo.parse(coerce(version)) |
| 66 | + |
| 67 | + |
| 68 | +def normalize(version): |
| 69 | + """Normalize semver version for indexing (to allow for lexical |
| 70 | + sorting/filtering).""" |
| 71 | + version = parse(version) |
| 72 | + |
| 73 | + # Precedence rules: https://semver.org/#spec-item-11 |
| 74 | + |
| 75 | + # 1. Precedence MUST be calculated by separating the version into major, |
| 76 | + # minor, patch and pre-release identifiers in that order (Build metadata does |
| 77 | + # not figure into precedence). |
| 78 | + # |
| 79 | + # Normalization: Per spec build metadata is ignored. |
| 80 | + |
| 81 | + # 2. Precedence is determined by the first difference when comparing each of |
| 82 | + # these identifiers from left to right as follows: Major, minor, and patch |
| 83 | + # versions are always compared numerically. |
| 84 | + # |
| 85 | + # Normalization: Pad the components with '0' to allow for lexical ordering of |
| 86 | + # numbers. |
| 87 | + core_parts = "{}.{}.{}".format( |
| 88 | + str(version.major).rjust(_PAD_WIDTH, "0"), |
| 89 | + str(version.minor).rjust(_PAD_WIDTH, "0"), |
| 90 | + str(version.patch).rjust(_PAD_WIDTH, "0"), |
| 91 | + ) |
| 92 | + |
| 93 | + # 3. When major, minor, and patch are equal, a pre-release version has lower |
| 94 | + # precedence than a normal version: |
| 95 | + # |
| 96 | + # Normalization: Attach a very long fake prerelease version that is most |
| 97 | + # likely to come after any real prelease version. |
| 98 | + if not version.prerelease: |
| 99 | + pre = "z" * _FAKE_PRE_WIDTH |
| 100 | + return f"{core_parts}-{pre}" |
| 101 | + |
| 102 | + # 4. Precedence for two pre-release versions with the same major, minor, and |
| 103 | + # patch version MUST be determined by comparing each dot separated identifier |
| 104 | + # from left to right until a difference is found as follows: |
| 105 | + # |
| 106 | + # Normalization: Pad the components. |
| 107 | + pre_components = [] |
| 108 | + for component in version.prerelease.split("."): |
| 109 | + # 3. Numeric identifiers always have lower precedence than non-numeric |
| 110 | + # identifiers. |
| 111 | + # |
| 112 | + # Normalization: Pad numeric components with '0', and prefix alphanumeric |
| 113 | + # with a single '1' (to ensure they always come after). |
| 114 | + if component.isdigit(): |
| 115 | + # 1. Identifiers consisting of only digits are compared numerically. |
| 116 | + pre_components.append(component.rjust(_PAD_WIDTH, "0")) |
| 117 | + else: |
| 118 | + # 2. Identifiers with letters or hyphens are compared lexically in ASCII |
| 119 | + # sort order. |
| 120 | + pre_components.append("1" + component) |
| 121 | + |
| 122 | + # 4. A larger set of pre-release fields has a higher precedence than a smaller |
| 123 | + # set, if all of the preceding identifiers are equal. |
| 124 | + # |
| 125 | + # Consistent with lexical sorting after normalization. |
| 126 | + |
| 127 | + pre = ".".join(pre_components) |
| 128 | + return f"{core_parts}-{pre}" |
| 129 | + |
| 130 | + |
| 131 | +def _extract_revision(str_version): |
| 132 | + """Extract revision (4th component) from version number (if any).""" |
| 133 | + # e.g. '1.0.0.0-prerelease' |
| 134 | + pattern = re.compile(r"^(\d+)(\.\d+)(\.\d+)(\.\d+)(.*)") |
| 135 | + match = pattern.match(str_version) |
| 136 | + if not match: |
| 137 | + return str_version, 0 |
| 138 | + |
| 139 | + return ( |
| 140 | + "".join((match.group(1), match.group(2), match.group(3), match.group(5))), |
| 141 | + int(match.group(4)[1:]), |
| 142 | + ) |
| 143 | + |
| 144 | + |
| 145 | +@functools.total_ordering |
| 146 | +class Version: |
| 147 | + """NuGet version.""" |
| 148 | + |
| 149 | + def __init__(self, base_semver, revision): |
| 150 | + self._base_semver = base_semver |
| 151 | + if self._base_semver.prerelease: |
| 152 | + self._base_semver = self._base_semver.replace(prerelease=base_semver.prerelease.lower()) |
| 153 | + self._revision = revision |
| 154 | + |
| 155 | + def __eq__(self, other): |
| 156 | + return self._base_semver == other._base_semver and self._revision == other._revision |
| 157 | + |
| 158 | + def __lt__(self, other): |
| 159 | + if self._base_semver.replace(prerelease="") == other._base_semver.replace(prerelease=""): |
| 160 | + # If the first three components are the same, compare the revision. |
| 161 | + if self._revision != other._revision: |
| 162 | + return self._revision < other._revision |
| 163 | + |
| 164 | + # Revision is the same, so ignore it for comparison purposes. |
| 165 | + return self._base_semver < other._base_semver |
| 166 | + |
| 167 | + @classmethod |
| 168 | + def from_string(cls, str_version): |
| 169 | + str_version = coerce(str_version) |
| 170 | + str_version, revision = _extract_revision(str_version) |
| 171 | + return Version(parse(str_version), revision) |
0 commit comments