Debian Codegraph @

third_party/python/pip_tools/piptools/sync.py

raw
1 from __future__ import annotations
2
3 import collections
4 import os
5 import sys
6 import tempfile
7 from subprocess import run # nosec
8 from typing import Deque, Iterable, Mapping, ValuesView
9
10 import click
11 from pip._internal.models.direct_url import ArchiveInfo
12 from pip._internal.req import InstallRequirement
13 from pip._internal.utils.compat import stdlib_pkgs
14 from pip._internal.utils.direct_url_helpers import (
15 direct_url_as_pep440_direct_reference,
16 direct_url_from_link,
17 )
18 from pip._vendor.packaging.utils import canonicalize_name
19
20 from ._compat import Distribution, get_dev_pkgs
21 from .exceptions import IncompatibleRequirements
22 from .logging import log
23 from .utils import (
24 flat_map,
25 format_requirement,
26 get_hashes_from_ireq,
27 is_url_requirement,
28 key_from_ireq,
29 key_from_req,
30 )
31
32 PACKAGES_TO_IGNORE = [
33 "-markerlib",
34 "pip",
35 "pip-tools",
36 "pip-review",
37 "pkg-resources",
38 *stdlib_pkgs,
39 *get_dev_pkgs(),
40 ]
41
42
43 def dependency_tree(
44 installed_keys: Mapping[str, Distribution], root_key: str
45 ) -> set[str]:
46 """
47 Calculate the dependency tree for the package `root_key` and return
48 a collection of all its dependencies. Uses a DFS traversal algorithm.
49
50 `installed_keys` should be a {key: requirement} mapping, e.g.
51 {'django': from_line('django==1.8')}
52 `root_key` should be the key to return the dependency tree for.
53 """
54 dependencies = set()
55 queue: Deque[Distribution] = collections.deque()
56
57 if root_key in installed_keys:
58 dep = installed_keys[root_key]
59 queue.append(dep)
60
61 while queue:
62 v = queue.popleft()
63 key = str(canonicalize_name(v.key))
64 if key in dependencies:
65 continue
66
67 dependencies.add(key)
68
69 for dep_specifier in v.requires:
70 dep_name = key_from_req(dep_specifier)
71 if dep_name in installed_keys:
72 dep = installed_keys[dep_name]
73
74 if dep_specifier.specifier.contains(dep.version):
75 queue.append(dep)
76
77 return dependencies
78
79
80 def get_dists_to_ignore(installed: Iterable[Distribution]) -> list[str]:
81 """
82 Returns a collection of package names to ignore when performing pip-sync,
83 based on the currently installed environment. For example, when pip-tools
84 is installed in the local environment, it should be ignored, including all
85 of its dependencies (e.g. click). When pip-tools is not installed
86 locally, click should also be installed/uninstalled depending on the given
87 requirements.
88 """
89 installed_keys = {str(canonicalize_name(r.key)): r for r in installed}
90 return list(
91 flat_map(lambda req: dependency_tree(installed_keys, req), PACKAGES_TO_IGNORE)
92 )
93
94
95 def merge(
96 requirements: Iterable[InstallRequirement], ignore_conflicts: bool
97 ) -> ValuesView[InstallRequirement]:
98 by_key: dict[str, InstallRequirement] = {}
99
100 for ireq in requirements:
101 # Limitation: URL requirements are merged by precise string match, so
102 # "file:///example.zip#egg=example", "file:///example.zip", and
103 # "example==1.0" will not merge with each other
104 if ireq.match_markers():
105 key = key_from_ireq(ireq)
106
107 if not ignore_conflicts:
108 existing_ireq = by_key.get(key)
109 if existing_ireq:
110 # NOTE: We check equality here since we can assume that the
111 # requirements are all pinned
112 if (
113 ireq.req
114 and existing_ireq.req
115 and ireq.specifier != existing_ireq.specifier
116 ):
117 raise IncompatibleRequirements(ireq, existing_ireq)
118
119 # TODO: Always pick the largest specifier in case of a conflict
120 by_key[key] = ireq
121 return by_key.values()
122
123
124 def diff_key_from_ireq(ireq: InstallRequirement) -> str:
125 """
126 Calculate a key for comparing a compiled requirement with installed modules.
127 For URL requirements, only provide a useful key if the url includes
128 a hash, e.g. #sha1=..., in any of the supported hash algorithms.
129 Otherwise return ireq.link so the key will not match and the package will
130 reinstall. Reinstall is necessary to ensure that packages will reinstall
131 if the contents at the URL have changed but the version has not.
132 """
133 if is_url_requirement(ireq):
134 if getattr(ireq.req, "name", None) and ireq.link.has_hash:
135 return str(
136 direct_url_as_pep440_direct_reference(
137 direct_url_from_link(ireq.link), ireq.req.name
138 )
139 )
140 # TODO: Also support VCS and editable installs.
141 return str(ireq.link)
142 return key_from_ireq(ireq)
143
144
145 def diff_key_from_req(req: Distribution) -> str:
146 """Get a unique key for the requirement."""
147 key = str(canonicalize_name(req.key))
148 if (
149 req.direct_url
150 and isinstance(req.direct_url.info, ArchiveInfo)
151 and req.direct_url.info.hash
152 ):
153 key = direct_url_as_pep440_direct_reference(req.direct_url, key)
154 # TODO: Also support VCS and editable installs.
155 return key
156
157
158 def diff(
159 compiled_requirements: Iterable[InstallRequirement],
160 installed_dists: Iterable[Distribution],
161 ) -> tuple[set[InstallRequirement], set[str]]:
162 """
163 Calculate which packages should be installed or uninstalled, given a set
164 of compiled requirements and a list of currently installed modules.
165 """
166 requirements_lut = {diff_key_from_ireq(r): r for r in compiled_requirements}
167
168 satisfied = set() # holds keys
169 to_install = set() # holds InstallRequirement objects
170 to_uninstall = set() # holds keys
171
172 pkgs_to_ignore = get_dists_to_ignore(installed_dists)
173 for dist in installed_dists:
174 key = diff_key_from_req(dist)
175 if key not in requirements_lut or not requirements_lut[key].match_markers():
176 to_uninstall.add(key)
177 elif requirements_lut[key].specifier.contains(dist.version):
178 satisfied.add(key)
179
180 for key, requirement in requirements_lut.items():
181 if key not in satisfied and requirement.match_markers():
182 to_install.add(requirement)
183
184 # Make sure to not uninstall any packages that should be ignored
185 to_uninstall -= set(pkgs_to_ignore)
186
187 return (to_install, to_uninstall)
188
189
190 def sync(
191 to_install: Iterable[InstallRequirement],
192 to_uninstall: Iterable[InstallRequirement],
193 dry_run: bool = False,
194 install_flags: list[str] | None = None,
195 ask: bool = False,
196 python_executable: str | None = None,
197 ) -> int:
198 """
199 Install and uninstalls the given sets of modules.
200 """
201 exit_code = 0
202
203 python_executable = python_executable or sys.executable
204
205 if not to_uninstall and not to_install:
206 log.info("Everything up-to-date", err=False)
207 return exit_code
208
209 pip_flags = []
210 if log.verbosity < 0:
211 pip_flags += ["-q"]
212
213 if ask:
214 dry_run = True
215
216 if dry_run:
217 if to_uninstall:
218 click.echo("Would uninstall:")
219 for pkg in sorted(to_uninstall):
220 click.echo(f" {pkg}")
221
222 if to_install:
223 click.echo("Would install:")
224 for ireq in sorted(to_install, key=key_from_ireq):
225 click.echo(f" {format_requirement(ireq)}")
226
227 exit_code = 1
228
229 if ask and click.confirm("Would you like to proceed with these changes?"):
230 dry_run = False
231 exit_code = 0
232
233 if not dry_run:
234 if to_uninstall:
235 run( # nosec
236 [
237 python_executable,
238 "-m",
239 "pip",
240 "uninstall",
241 "-y",
242 *pip_flags,
243 *sorted(to_uninstall),
244 ],
245 check=True,
246 )
247
248 if to_install:
249 if install_flags is None:
250 install_flags = []
251 # prepare requirement lines
252 req_lines = []
253 for ireq in sorted(to_install, key=key_from_ireq):
254 ireq_hashes = get_hashes_from_ireq(ireq)
255 req_lines.append(format_requirement(ireq, hashes=ireq_hashes))
256
257 # save requirement lines to a temporary file
258 tmp_req_file = tempfile.NamedTemporaryFile(mode="wt", delete=False)
259 tmp_req_file.write("\n".join(req_lines))
260 tmp_req_file.close()
261
262 try:
263 run( # nosec
264 [
265 python_executable,
266 "-m",
267 "pip",
268 "install",
269 "-r",
270 tmp_req_file.name,
271 *pip_flags,
272 *install_flags,
273 ],
274 check=True,
275 )
276 finally:
277 os.unlink(tmp_req_file.name)
278
279 return exit_code