Debian Codegraph @

mesonbuild/cargo/version.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright © 2022-2023 Intel Corporation
3
4 """Convert Cargo versions into Meson compatible ones."""
5
6 from __future__ import annotations
7 from functools import lru_cache
8 import operator
9 import re
10 import typing as T
11
12 from ..mesonlib import MesonException
13
14 def _api_of(version: str) -> str:
15 # x.y.z -> x
16 # 0.x.y -> 0.x
17 # 0.0.x -> 0
18 vers = version.split('.')
19 if not vers[0] or int(vers[0]) != 0:
20 return vers[0]
21 elif len(vers) >= 2 and int(vers[1]) != 0:
22 return f'0.{vers[1]}'
23 return '0'
24
25
26 def split(cargo_ver: str) -> T.Iterable[tuple[str, str]]:
27 """Canonicalization of Cargo version requirements"""
28 cargo_ver = cargo_ver.strip()
29 if not cargo_ver:
30 return
31 for ver in cargo_ver.split(','):
32 ver = ver.strip()
33 if ver == '*':
34 continue
35
36 if ver.startswith(('>=', '<=', '!=')):
37 yield ver[0:2], ver[2:].lstrip()
38 elif ver.startswith(('~', '=', '^', '>', '<')):
39 yield ver[0], ver[1:].lstrip()
40 elif ver.endswith('.*'):
41 # asterisk requirements are same as tilde: 1.* == ~1
42 # https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#wildcard-requirements
43 yield '~', ver[:-2].lstrip()
44 else:
45 # caret requirement is the default strategy
46 yield '^', ver
47
48
49 def api(cargo_ver: str) -> str:
50 """Determine the API version implied by a Cargo version requirement.
51
52 :param cargo_ver: A Cargo version string.
53 :return: empty string if no lower bound establishes an API, otherwise the
54 major version (or ``"0.x"`` / ``"0"`` for 0.x.y / 0.0.x versions).
55 Raise exception if constraints disagree on the API.
56 """
57 apis: T.Set[str] = set()
58 for op, ver in split(cargo_ver):
59 if op in {'>=', '=', '^', '~'}:
60 apis.add(_api_of(ver))
61 if not apis:
62 return ''
63 elif len(apis) == 1:
64 return apis.pop()
65 else:
66 raise MesonException(f'Cannot determine API version from {cargo_ver!r}.')
67
68
69 # Tokens: a digit run, an alphanumeric-with-hyphens identifier (covers the
70 # leading ``-`` of the pre-release section and identifiers within it), or the
71 # ``+`` that introduces build metadata.
72 _SEMVER_TOK_RE = re.compile(r'(\d+)|([A-Za-z-][0-9A-Za-z-]*)|(\+.*)')
73
74
75 class SemVer:
76 """A SemVer 2.0.0 version, suitable for ordering.
77
78 Adapted from ``mesonlib.Version`` but with the int/str precedence
79 reversed: SemVer says numeric pre-release identifiers sort *below*
80 alphanumeric ones, whereas Meson's ``Version`` does the opposite.
81
82 Versions are represented as a flat list:
83 [major, minor, patch, 0] for normal versions
84 [major, minor, patch, -1, *pre_idents] for pre-releases
85
86 The fourth slot (0 for normal, -1 for pre-release) makes a normal
87 version sort *above* the corresponding pre-release.
88 Missing minor/patch components default to 0.
89 """
90
91 __slots__ = ('_v', 'specified_count')
92
93 def __init__(self, in_: str | list[int | str] = None) -> None:
94 vec: list[int | str]
95 if isinstance(in_, str):
96 vec = []
97 pre = False
98 specified_count = 0
99 for m in _SEMVER_TOK_RE.finditer(in_):
100 if m.group(1):
101 if pre or specified_count < 3:
102 vec.append(int(m.group(1)))
103 if not pre:
104 specified_count += 1
105 elif m.group(2):
106 ident = m.group(2)
107 if not pre:
108 # The leading ``-`` is just a section marker.
109 if ident.startswith('-'):
110 ident = ident[1:]
111 if not ident:
112 continue
113 while len(vec) < 3:
114 vec.append(0)
115 vec.append(-1)
116 pre = True
117 vec.append(ident)
118 else:
119 break # +build metadata: discard the rest
120 else:
121 # Direct construction from a pre-built component list.
122 vec = list(in_)
123 specified_count = min(3, len(in_))
124
125 while len(vec) < 4:
126 vec.append(0)
127 self._v = vec
128 self.specified_count = specified_count
129
130 def __repr__(self) -> str:
131 s = '.'.join(str(c) for c in self._v[:self.specified_count])
132 if len(self._v) > 4:
133 s += '-' + '.'.join(str(c) for c in self._v[4:])
134 return f'<SemVer: {s}>'
135
136 @property
137 def has_prerelease(self) -> bool:
138 return self._v[3] == -1
139
140 def __lt__(self, other: object) -> bool:
141 if isinstance(other, SemVer):
142 return self.__cmp(other._v, operator.lt)
143 return NotImplemented
144
145 def __gt__(self, other: object) -> bool:
146 if isinstance(other, SemVer):
147 return self.__cmp(other._v, operator.gt)
148 return NotImplemented
149
150 def __le__(self, other: object) -> bool:
151 if isinstance(other, SemVer):
152 return self.__cmp(other._v, operator.le)
153 return NotImplemented
154
155 def __ge__(self, other: object) -> bool:
156 if isinstance(other, SemVer):
157 return self.__cmp(other._v, operator.ge)
158 return NotImplemented
159
160 def __eq__(self, other: object) -> bool:
161 if isinstance(other, SemVer):
162 return self._v == other._v
163 return NotImplemented
164
165 def __ne__(self, other: object) -> bool:
166 if isinstance(other, SemVer):
167 return self._v != other._v
168 return NotImplemented
169
170 def __cmp(self, other: list[int | str], comparator: T.Callable[[T.Any, T.Any], bool]) -> bool:
171 for ours, theirs in zip(self._v, other):
172 ours_is_int = isinstance(ours, int)
173 theirs_is_int = isinstance(theirs, int)
174 if ours_is_int != theirs_is_int:
175 # SemVer: int (numeric) < str (alphanumeric).
176 return comparator(theirs_is_int, ours_is_int)
177 if ours != theirs:
178 return comparator(ours, theirs)
179 # "A larger set of pre-release fields has a higher precedence."
180 return comparator(len(self._v), len(other))
181
182 def next_ver(self, bump_idx: int) -> SemVer:
183 """Return a new SemVer with the component at ``bump_idx`` (0=major,
184 1=minor, 2=patch) bumped, following normal-version components zeroed,
185 and any pre-release dropped."""
186 v = list(self._v[:3])
187 last = v[bump_idx]
188 assert isinstance(last, int)
189 v[bump_idx] = last + 1
190 for i in range(bump_idx + 1, 3):
191 v[i] = 0
192 return SemVer(v)
193
194
195 @lru_cache(maxsize=None)
196 def cargo_parse(cargo_ver: str) -> T.Callable[[str], bool]:
197 """Return a function that checks a Version against a Cargo version
198 requirement.
199
200 :param cargo_ver: The version, as Cargo specifies
201 :return: A function returning true if the version is accepted.
202 """
203 out: list[tuple[T.Callable[[T.Any, T.Any], bool], SemVer]] = []
204 # Pre-release versions only match when at least one constraint
205 # names a pre-release.
206 accept_prerelease = False
207 for op, ver in split(cargo_ver):
208 semver = SemVer(ver)
209 accept_prerelease = accept_prerelease or semver.has_prerelease
210
211 # https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#comparison-requirements
212 if op == '<=':
213 # Bump the last *specified* component and convert to `<`.
214 nextver = semver.next_ver(semver.specified_count - 1)
215 out.append((operator.lt, nextver))
216
217 elif op == '~':
218 # Tilde requirements are the same as asterisk, so 1.* == ~1
219 # https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#tilde-requirements
220 # we convert those into a pair of constraints
221 out.append((operator.ge, semver))
222 if semver.specified_count >= 2:
223 nextver = semver.next_ver(1)
224 else:
225 nextver = semver.next_ver(0)
226 out.append((operator.lt, nextver))
227
228 elif op == '^':
229 # https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#caret-requirements
230 # Bump the leftmost non-zero major/minor/patch component
231 out.append((operator.ge, semver))
232 for bump_idx in range(3):
233 if semver._v[bump_idx] != 0:
234 break
235 else:
236 # All zeros: ``^0.0.0`` means ``< 1.0.0``, so bump the major.
237 bump_idx = 0
238 nextver = semver.next_ver(bump_idx)
239 out.append((operator.lt, nextver))
240
241 elif op == '>=':
242 out.append((operator.ge, semver))
243 elif op == '!=':
244 out.append((operator.ne, semver))
245 elif op == '=':
246 out.append((operator.eq, semver))
247 elif op == '>':
248 out.append((operator.gt, semver))
249 elif op == '<':
250 out.append((operator.lt, semver))
251
252 def compare(ver: str) -> bool:
253 lhs = SemVer(ver)
254 if lhs.has_prerelease and not accept_prerelease:
255 return False
256 for op, rhs in out:
257 if not op(lhs, rhs):
258 return False
259 return True
260
261 if not out:
262 return lambda v: True
263 return compare