Debian Codegraph @

tasks/deps/_inspect/_index.py

raw symbols SCIP
1 # -*- coding: ascii -*-
2 #
3 # Copyright 2018 - 2025
4 # Andr\xe9 Malo or his licensors, as applicable
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 """
18 Inspect package versions in index
19 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
20
21 """
22
23 import json as _json
24 import logging as _logging
25
26 import pkg_resources as _pkg_resources
27
28 try:
29 from setuptools import package_index as _pkg_index
30 except ImportError:
31 _pkg_index = None
32 import invoke as _invoke
33
34 from ... import pypi as _pypi
35 from ..._inv import tasks as _tasks
36 from .. import _parse
37
38 # pylint: disable = import-outside-toplevel
39
40 logger = _logging.getLogger("deps.inspect.index")
41
42
43 class PipIndex(_pkg_resources.Environment):
44 """Query the index using pip"""
45
46 _is_available = None
47
48 def __init__(self, *args, **kwargs):
49 super(PipIndex, self).__init__(*args, **kwargs)
50 self._ctx = _tasks.new_context()
51 self._cache = set()
52
53 @classmethod
54 def is_available(cls):
55 """Is the pip index available?"""
56 if cls._is_available is not None:
57 return cls._is_available
58
59 ctx = _tasks.new_context()
60 try:
61 ctx.run(
62 ctx.c(
63 "pip index -i %s versions --json pip",
64 _pypi.index_url(ctx),
65 ),
66 hide=True,
67 echo=False,
68 )
69 except _invoke.UnexpectedExit:
70 cls._is_available = False
71 else:
72 cls._is_available = True
73
74 return cls._is_available
75
76 def find_packages(self, requirement):
77 """Find packages"""
78 if requirement.key in self._cache:
79 return
80
81 ctx = self._ctx
82 index_info = _json.loads(
83 ctx.run(
84 ctx.c(
85 [
86 "pip",
87 "index",
88 "-i",
89 _pypi.index_url(ctx),
90 "versions",
91 "--json",
92 requirement.project_name,
93 ]
94 ),
95 hide=True,
96 ).stdout.strip()
97 )
98 for version in index_info.get("versions", ()):
99 self.add(
100 _pkg_resources.Distribution(
101 project_name=requirement.project_name,
102 version=version,
103 precedence=_pkg_resources.EGG_DIST + 1,
104 )
105 )
106 self._cache.add(requirement.key)
107
108 def obtain(self, requirement, installer=None):
109 self.find_packages(requirement)
110 for dist in self[requirement.key]:
111 if dist in requirement:
112 return dist
113 return super().obtain(requirement, installer)
114
115
116 class Index(object):
117 """Python package index container"""
118
119 def __init__(self):
120 """Initialization"""
121 if PipIndex.is_available():
122 self._index = PipIndex(search_path=[])
123 elif _pkg_index is not None:
124 self._index = _pkg_index.PackageIndex(search_path=[])
125 else:
126 raise RuntimeError("No index access tool available")
127
128 self._wset = _pkg_resources.WorkingSet([])
129
130 def lookup(self, req):
131 """
132 Find the best-fitting requirement in the index
133
134 Parameters:
135 req (Requirement):
136 The requirement to look up
137
138 Returns:
139 Distribution: The found distribution or ``None``
140 """
141 dist = self._index.best_match(req, self._wset)
142 logger.debug("Index lookup result of %r: %r", str(req), dist)
143 return dist
144
145 def scanner(self, version):
146 """
147 Create a new package scanner
148
149 Parameters:
150 version (str):
151 The package version to compare to
152
153 Returns:
154 PackageScanner: New package scanner
155 """
156 return PackageScanner(self, version)
157
158
159 class PackageScanner(object):
160 """Container for scanning a single package"""
161
162 def __init__(self, index, package_version):
163 """
164 Initialization
165
166 Parameters:
167 index (Index):
168 The index container
169
170 package_version (str):
171 The installed package version
172 """
173 self._index = index
174 self._version = package_version and _parse.version(package_version)
175 self._result = {}
176
177 def result(self):
178 """
179 Get the aggregated result
180
181 Returns:
182 dict: The result
183 """
184 final = dict(self._result)
185 if (
186 final.get("latest") is not None
187 and final.get("compatible") is not None
188 and final["latest"] == final["compatible"]
189 ):
190 del final["latest"]
191
192 if (
193 final.get("compatible") is not None
194 and final.get("unchanged") is not None
195 and final["compatible"] == final["unchanged"]
196 ):
197 del final["compatible"]
198
199 # if (
200 # final.get("unchanged") is not None
201 # and final["unchanged"] == self._version
202 # ):
203 # del final["unchanged"]
204
205 return {
206 key: str(value)
207 for key, value in final.items()
208 if value is not None
209 }
210
211 def inspect(self, req):
212 """
213 Lookup requirement versions in index
214
215 The aggregated result can be retrieved by calling ``.result()``
216
217 Parameters:
218 req (Requirement):
219 The requirement to look up
220 """
221 # we want a specifically typed copy
222 if PipIndex.is_available():
223 req = _pkg_resources.Requirement.parse(str(req))
224 else:
225 req = _pkg_index.Requirement.parse(str(req))
226
227 self._update_field("unchanged", req)
228 self._find_compat(req)
229 self._find_latest(req)
230
231 def _find_compat(self, req):
232 """
233 Find compatible version
234
235 Parameters:
236 req (Requirement):
237 The requirement to look up
238 """
239 req = req.parse(str(req)) # copy
240
241 # We turn == into ~=, which finds compatible versions
242 # (last digit update)
243 specs = []
244 for spec in req.specifier:
245 operator = spec.operator
246 if operator == "==":
247 operator = "~="
248 specs.append("%s%s" % (operator, spec.version))
249
250 try:
251 # pylint: disable = unnecessary-dunder-call
252 req.specifier.__init__(",".join(specs), prereleases=False)
253 except _pkg_resources.packaging.specifiers.InvalidSpecifier:
254 logger.debug("Invalid compat %r", ",".join(specs))
255 return
256
257 logger.debug("Valid compat %r", str(req))
258 self._update_field("compatible", req)
259
260 def _find_latest(self, req):
261 """
262 Find latest version
263
264 Parameters:
265 req (Requirement):
266 The requirement to look up
267 """
268 req = req.parse(str(req)) # copy
269
270 spec = None if self._version is None else ">=%s" % (self._version,)
271 # pylint: disable = unnecessary-dunder-call
272 req.specifier.__init__(spec or "", prereleases=False)
273
274 correction = self._update_field("latest", req)
275 if correction:
276 correction = "< %s" % (correction,)
277 spec = ", ".join((spec, correction)) if spec else correction
278 req.specifier.__init__(spec or "", prereleases=False)
279 self._update_field("latest", req)
280
281 def _update_field(self, field, req):
282 """
283 Update version info field
284
285 Parameters:
286 field (str):
287 The field to update
288
289 req (Requirement):
290 The requirement to evaluate
291 """
292 dist = self._index.lookup(req.parse(str(req)))
293 if dist is None:
294 return None
295
296 dist_version = _parse.version(dist.version)
297 if dist_version.is_prerelease:
298 return dist_version
299
300 if (self._version is None or dist_version >= self._version) and (
301 self._result.get(field) is None
302 or dist_version > self._result[field]
303 ):
304 self._result[field] = dist_version
305
306 return None