Debian Codegraph @

tasks/deps/_inspect/_inspect.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 current dependencies
19 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
20
21 """
22
23 import collections as _collections
24 import json as _json
25 import logging as _logging
26 import os as _os
27 import re as _re
28
29 from .. import _parse
30 from . import _index
31 from . import _req_file
32
33 # pylint: disable = import-outside-toplevel
34
35 logger = _logging.getLogger("deps.inspect")
36
37
38 def inspect_dependencies(ctx, config, verbose=True, debug=False):
39 """
40 Inspect dependencies
41
42 Parameters:
43 config (adict):
44 deps config
45
46 verbose (bool):
47 Verbose mode? Default: true
48
49 debug (bool):
50 Debug mode? Default: false
51
52 Returns:
53 dict: package -> info mapping
54 """
55 logger.setLevel("DEBUG" if debug else ("INFO" if verbose else "WARN"))
56
57 requirements, _ = _scan_toplevel(ctx, config.toplevel)
58 index = _index.Index()
59
60 return {
61 name: _inspect_package(index, name, version, places)
62 for (name, version), places in requirements.items()
63 }
64
65
66 def _scan_toplevel(ctx, req_files):
67 """
68 Find toplevel packages
69
70 Parameters:
71 req_files (list):
72 Requirement file names
73
74 Returns:
75 tuple: {(normname, installed-version) -> [{line, requirement}]},
76 [constraint]
77 """
78 installed = _find_installed(ctx)
79
80 req = _collections.defaultdict(list)
81 con = []
82
83 for item in _req_file.tokens(req_files, base=ctx.shell.root):
84 if item.type == _req_file.REQUIREMENT:
85 name = _parse.normalize(item.value.name)
86 version = installed.get(name, {}).get("version")
87 key = (name, version)
88 logger.debug("Parsed %r -> %r", item.line.content.strip(), key)
89 req[key].append(dict(line=item.line, requirement=item.value))
90 continue
91
92 if item.type == _req_file.EDITABLE:
93 for parsed, extras in _find_editable_deps(ctx, installed, item):
94 name = _parse.normalize(parsed.name)
95 version = installed.get(name, {}).get("version")
96 key = (name, version)
97 logger.debug("Found editable dependency %r", key)
98 req[key].append(
99 dict(line=None, requirement=parsed, extras=extras)
100 )
101 continue
102
103 if item.type == _req_file.CONSTRAINT:
104 con.append(item.value)
105 continue
106
107 return dict(req), con
108
109
110 def _inspect_package(index, name, version, places):
111 """
112 Inspect a single package (in multiple locations)
113
114 Parameters:
115 index (PackageIndex):
116 package index connector
117
118 wset (WorkingSet):
119 Working set to use
120
121 name (str):
122 The (normalized) package name
123
124 version (str):
125 Installed version (or ``None``)
126
127 places (list):
128 Places where the requirement was found
129 """
130 logger.info("Inspecting %s (%s)", name, version)
131
132 scanner = index.scanner(version)
133 locations = [
134 _inspect_place(scanner, place)
135 for place in places
136 if _place_evaluates(place)
137 ]
138 return dict(
139 installed=version,
140 locations=locations,
141 updates=scanner.result() or None,
142 )
143
144
145 def _inspect_place(scanner, place):
146 """
147 Inspect a single place
148
149 Parameters:
150 index (PackageIndex):
151 package index connector
152
153 wset (WorkingSet):
154 Working set to use
155
156 place (dict):
157 The place to inspect
158
159 version (Version):
160 parsed installed version
161
162 version_info (dict):
163 Index version info. Modified in-place.
164
165 Returns:
166 dict: The fully inspected place description
167 """
168 result = dict(requirement=place["requirement"])
169 if place["line"]:
170 result["file"] = dict(
171 name=place["line"].file,
172 line=place["line"].lineno,
173 content=place["line"].content,
174 )
175 logger.debug("Adding location %r", result["file"])
176
177 scanner.inspect(place["requirement"])
178 return result
179
180
181 def _place_evaluates(place):
182 """
183 Does a place evaluate in the current environment?
184
185 Parameters:
186 place (dict):
187 The place to inspect
188
189 Returns:
190 bool: The the place's requirement evaluate in the current environment?
191 """
192 if not place["requirement"].marker:
193 return True
194
195 if not place.get("extras"):
196 if place["requirement"].marker.evaluate({}):
197 return True
198 else:
199 for extra in place["extras"]:
200 env = dict(extra=_parse.safe_extra(extra))
201 if place["requirement"].marker.evaluate(env):
202 return True
203
204 logger.debug(
205 "Ignoring %r because it doesn't evaluate", str(place["requirement"])
206 )
207 return False
208
209
210 def _find_editable_deps(ctx, installed, spec):
211 """
212 Find direct dependencies for editable installation
213
214 Parameters:
215 installed (dict):
216 Installed packages
217
218 spec (Token):
219 The editable dep file token
220
221 Returns:
222 iterable: List of (requirement, needed-extras) tuples
223 """
224 pkg_name = _find_editable(ctx, installed, spec)
225 if pkg_name:
226 parts = spec.value.split("[", 1)
227 parts[0] = pkg_name
228 extras = sorted(_parse.requirement("[".join(parts)).extras)
229 logger.debug("Extras for editable installation: %r", extras)
230
231 try:
232 try:
233 from importlib import metadata as _metadata
234 except ImportError:
235 import importlib_metadata as _metadata
236 except ImportError:
237 import pkg_resources as _pkg_resources
238
239 dist = _pkg_resources.working_set.by_key[pkg_name]
240 for item in dist.requires(extras):
241 yield item, extras
242 else:
243 for item in _metadata.requires(pkg_name) or ():
244 parsed = _parse.requirement(item)
245 yield parsed, extras
246
247
248 def _find_editable(ctx, installed, spec):
249 """
250 Find editable package installation
251
252 Parameters:
253 installed (dict):
254 Installed packages
255
256 spec (Token):
257 The editable dep file token
258
259 Returns:
260 str: The normalized name
261 """
262 local_path = spec.value.split("[", 1)[0].strip()
263 path = _os.path.normpath(
264 _os.path.join(_os.path.dirname(spec.line.file), local_path)
265 )
266 if not _os.path.isdir(path):
267 logger.debug("%r does not point to a path -> skipping", spec.value)
268 return None
269
270 info = None
271 for normname, info in installed.items():
272 if "editable" not in info:
273 continue
274
275 installed_path = _os.path.normpath(info["editable"])
276 if installed_path == path:
277 logger.debug(
278 "Editable installation of %r found at %r", spec.value, path
279 )
280 return normname
281
282 logger.debug(
283 "Skipping editable %r (path does not match)", info["name"]
284 )
285
286 logger.debug("Editable %r not found", spec.value)
287 return None
288
289
290 def _find_installed(ctx):
291 """
292 Find installed packages
293
294 Returns:
295 dict: norm-name (str) -> {name: str, version: str[, editable: str]}
296 """
297 found = _json.loads(
298 ctx.run(
299 ctx.c("pip list --local --format json"),
300 echo=False,
301 hide=True,
302 ).stdout
303 )
304 name_match = _re.compile(r"^(?:%s)$" % (_parse.regex.idre,)).match
305
306 result = {}
307 for pkg in found:
308 assert name_match(pkg["name"])
309 item = dict(name=pkg["name"], version=pkg["version"])
310 if "editable_project_location" in pkg:
311 item["editable"] = pkg["editable_project_location"]
312 result[_parse.normalize(pkg["name"])] = item
313
314 return result