Debian Codegraph @

third_party/python/pip_tools/piptools/scripts/sync.py

raw
1 from __future__ import annotations
2
3 import itertools
4 import os
5 import shlex
6 import shutil
7 import sys
8 from pathlib import Path
9 from typing import cast
10
11 import click
12 from pip._internal.commands import create_command
13 from pip._internal.commands.install import InstallCommand
14 from pip._internal.index.package_finder import PackageFinder
15 from pip._internal.metadata import get_environment
16
17 from .. import sync
18 from .._compat import Distribution, parse_requirements
19 from ..exceptions import PipToolsError
20 from ..logging import log
21 from ..repositories import PyPIRepository
22 from ..utils import (
23 flat_map,
24 get_pip_version_for_python_executable,
25 get_required_pip_specification,
26 get_sys_path_for_python_executable,
27 )
28 from . import options
29
30 DEFAULT_REQUIREMENTS_FILE = "requirements.txt"
31
32
33 @click.command(
34 name="pip-sync", context_settings={"help_option_names": options.help_option_names}
35 )
36 @options.version
37 @options.ask
38 @options.dry_run
39 @options.force
40 @options.find_links
41 @options.index_url
42 @options.extra_index_url
43 @options.trusted_host
44 @options.no_index
45 @options.python_executable
46 @options.verbose
47 @options.quiet
48 @options.user
49 @options.cert
50 @options.client_cert
51 @options.src_files
52 @options.pip_args
53 @options.config
54 @options.no_config
55 def cli(
56 ask: bool,
57 dry_run: bool,
58 force: bool,
59 find_links: tuple[str, ...],
60 index_url: str | None,
61 extra_index_url: tuple[str, ...],
62 trusted_host: tuple[str, ...],
63 no_index: bool,
64 python_executable: str | None,
65 verbose: int,
66 quiet: int,
67 user_only: bool,
68 cert: str | None,
69 client_cert: str | None,
70 src_files: tuple[str, ...],
71 pip_args_str: str | None,
72 config: Path | None,
73 no_config: bool,
74 ) -> None:
75 """Synchronize virtual environment with requirements.txt."""
76 log.verbosity = verbose - quiet
77
78 if not src_files:
79 if os.path.exists(DEFAULT_REQUIREMENTS_FILE):
80 src_files = (DEFAULT_REQUIREMENTS_FILE,)
81 else:
82 msg = "No requirement files given and no {} found in the current directory"
83 log.error(msg.format(DEFAULT_REQUIREMENTS_FILE))
84 sys.exit(2)
85
86 if any(src_file.endswith(".in") for src_file in src_files):
87 msg = (
88 "Some input files have the .in extension, which is most likely an error "
89 "and can cause weird behaviour. You probably meant to use "
90 "the corresponding *.txt file?"
91 )
92 if force:
93 log.warning("WARNING: " + msg)
94 else:
95 log.error("ERROR: " + msg)
96 sys.exit(2)
97
98 if config:
99 log.debug(f"Using pip-tools configuration defaults found in '{config !s}'.")
100
101 if python_executable:
102 _validate_python_executable(python_executable)
103
104 install_command = cast(InstallCommand, create_command("install"))
105 options, _ = install_command.parse_args([])
106 session = install_command._build_session(options)
107 finder = install_command._build_package_finder(options=options, session=session)
108
109 # Parse requirements file. Note, all options inside requirements file
110 # will be collected by the finder.
111 requirements = flat_map(
112 lambda src: parse_requirements(src, finder=finder, session=session), src_files
113 )
114
115 try:
116 merged_requirements = sync.merge(requirements, ignore_conflicts=force)
117 except PipToolsError as e:
118 log.error(str(e))
119 sys.exit(2)
120
121 paths = (
122 None
123 if python_executable is None
124 else get_sys_path_for_python_executable(python_executable)
125 )
126 installed_dists = _get_installed_distributions(
127 user_only=user_only,
128 local_only=python_executable is None,
129 paths=paths,
130 )
131 to_install, to_uninstall = sync.diff(merged_requirements, installed_dists)
132
133 install_flags = _compose_install_flags(
134 finder,
135 no_index=no_index,
136 index_url=index_url,
137 extra_index_url=extra_index_url,
138 trusted_host=trusted_host,
139 find_links=find_links,
140 user_only=user_only,
141 cert=cert,
142 client_cert=client_cert,
143 ) + shlex.split(pip_args_str or "")
144 sys.exit(
145 sync.sync(
146 to_install,
147 to_uninstall,
148 dry_run=dry_run,
149 install_flags=install_flags,
150 ask=ask,
151 python_executable=python_executable,
152 )
153 )
154
155
156 def _validate_python_executable(python_executable: str) -> None:
157 """
158 Validates incoming python_executable argument passed to CLI.
159 """
160 resolved_python_executable = shutil.which(python_executable)
161 if resolved_python_executable is None:
162 msg = "Could not resolve '{}' as valid executable path or alias."
163 log.error(msg.format(python_executable))
164 sys.exit(2)
165
166 # Ensure that target python executable has the right version of pip installed
167 pip_version = get_pip_version_for_python_executable(python_executable)
168 required_pip_specification = get_required_pip_specification()
169 if not required_pip_specification.contains(pip_version, prereleases=True):
170 msg = (
171 "Target python executable '{}' has pip version {} installed. "
172 "Version {} is expected."
173 )
174 log.error(
175 msg.format(python_executable, pip_version, required_pip_specification)
176 )
177 sys.exit(2)
178
179
180 def _compose_install_flags(
181 finder: PackageFinder,
182 no_index: bool,
183 index_url: str | None,
184 extra_index_url: tuple[str, ...],
185 trusted_host: tuple[str, ...],
186 find_links: tuple[str, ...],
187 user_only: bool,
188 cert: str | None,
189 client_cert: str | None,
190 ) -> list[str]:
191 """
192 Compose install flags with the given finder and CLI options.
193 """
194 result = []
195
196 # Build --index-url/--extra-index-url/--no-index
197 if no_index:
198 result.append("--no-index")
199 elif index_url is not None:
200 result.extend(["--index-url", index_url])
201 elif finder.index_urls:
202 finder_index_url = finder.index_urls[0]
203 if finder_index_url != PyPIRepository.DEFAULT_INDEX_URL:
204 result.extend(["--index-url", finder_index_url])
205 for extra_index in finder.index_urls[1:]:
206 result.extend(["--extra-index-url", extra_index])
207 else:
208 result.append("--no-index")
209
210 for extra_index in extra_index_url:
211 result.extend(["--extra-index-url", extra_index])
212
213 # Build --trusted-hosts
214 for host in itertools.chain(trusted_host, finder.trusted_hosts):
215 result.extend(["--trusted-host", host])
216
217 # Build --find-links
218 for link in itertools.chain(find_links, finder.find_links):
219 result.extend(["--find-links", link])
220
221 # Build format controls --no-binary/--only-binary
222 for format_control in ("no_binary", "only_binary"):
223 formats = getattr(finder.format_control, format_control)
224 if not formats:
225 continue
226 result.extend(
227 ["--" + format_control.replace("_", "-"), ",".join(sorted(formats))]
228 )
229
230 if user_only:
231 result.append("--user")
232
233 if cert is not None:
234 result.extend(["--cert", cert])
235
236 if client_cert is not None:
237 result.extend(["--client-cert", client_cert])
238
239 return result
240
241
242 def _get_installed_distributions(
243 local_only: bool = True,
244 user_only: bool = False,
245 paths: list[str] | None = None,
246 ) -> list[Distribution]:
247 """Return a list of installed Distribution objects."""
248
249 env = get_environment(paths)
250 dists = env.iter_installed_distributions(
251 local_only=local_only,
252 user_only=user_only,
253 skip=[],
254 )
255 return [Distribution.from_pip_distribution(dist) for dist in dists]