Debian Codegraph @

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

raw
1 from __future__ import annotations
2
3 import itertools
4 import os
5 import shlex
6 import sys
7 import tempfile
8 from pathlib import Path
9 from typing import IO, Any, BinaryIO, cast
10
11 import click
12 from build import BuildBackendException
13 from click.utils import LazyFile, safecall
14 from pip._internal.req import InstallRequirement
15 from pip._internal.req.constructors import install_req_from_line
16 from pip._internal.utils.misc import redact_auth_from_url
17
18 from .._compat import parse_requirements
19 from ..build import build_project_metadata
20 from ..cache import DependencyCache
21 from ..exceptions import NoCandidateFound, PipToolsError
22 from ..logging import log
23 from ..repositories import LocalRequirementsRepository, PyPIRepository
24 from ..repositories.base import BaseRepository
25 from ..resolver import BacktrackingResolver, LegacyResolver
26 from ..utils import dedup, drop_extras, is_pinned_requirement, key_from_ireq
27 from ..writer import OutputWriter
28 from . import options
29 from .options import BuildTargetT
30
31 DEFAULT_REQUIREMENTS_FILES = (
32 "requirements.in",
33 "setup.py",
34 "pyproject.toml",
35 "setup.cfg",
36 )
37 DEFAULT_REQUIREMENTS_FILE = "requirements.in"
38 DEFAULT_REQUIREMENTS_OUTPUT_FILE = "requirements.txt"
39 METADATA_FILENAMES = frozenset({"setup.py", "setup.cfg", "pyproject.toml"})
40
41
42 def _determine_linesep(
43 strategy: str = "preserve", filenames: tuple[str, ...] = ()
44 ) -> str:
45 """
46 Determine and return linesep string for OutputWriter to use.
47 Valid strategies: "LF", "CRLF", "native", "preserve"
48 When preserving, files are checked in order for existing newlines.
49 """
50 if strategy == "preserve":
51 for fname in filenames:
52 try:
53 with open(fname, "rb") as existing_file:
54 existing_text = existing_file.read()
55 except FileNotFoundError:
56 continue
57 if b"\r\n" in existing_text:
58 strategy = "CRLF"
59 break
60 elif b"\n" in existing_text:
61 strategy = "LF"
62 break
63 return {
64 "native": os.linesep,
65 "LF": "\n",
66 "CRLF": "\r\n",
67 "preserve": "\n",
68 }[strategy]
69
70
71 @click.command(
72 name="pip-compile",
73 context_settings={"help_option_names": options.help_option_names},
74 )
75 @click.pass_context
76 @options.version
77 @options.color
78 @options.verbose
79 @options.quiet
80 @options.dry_run
81 @options.pre
82 @options.rebuild
83 @options.extra
84 @options.all_extras
85 @options.find_links
86 @options.index_url
87 @options.no_index
88 @options.extra_index_url
89 @options.cert
90 @options.client_cert
91 @options.trusted_host
92 @options.header
93 @options.emit_trusted_host
94 @options.annotate
95 @options.annotation_style
96 @options.upgrade
97 @options.upgrade_package
98 @options.output_file
99 @options.newline
100 @options.allow_unsafe
101 @options.strip_extras
102 @options.generate_hashes
103 @options.reuse_hashes
104 @options.max_rounds
105 @options.src_files
106 @options.build_isolation
107 @options.emit_find_links
108 @options.cache_dir
109 @options.pip_args
110 @options.resolver
111 @options.emit_index_url
112 @options.emit_options
113 @options.unsafe_package
114 @options.config
115 @options.no_config
116 @options.constraint
117 @options.build_deps_for
118 @options.all_build_deps
119 @options.only_build_deps
120 def cli(
121 ctx: click.Context,
122 color: bool | None,
123 verbose: int,
124 quiet: int,
125 dry_run: bool,
126 pre: bool,
127 rebuild: bool,
128 extras: tuple[str, ...],
129 all_extras: bool,
130 find_links: tuple[str, ...],
131 index_url: str,
132 no_index: bool,
133 extra_index_url: tuple[str, ...],
134 cert: str | None,
135 client_cert: str | None,
136 trusted_host: tuple[str, ...],
137 header: bool,
138 emit_trusted_host: bool,
139 annotate: bool,
140 annotation_style: str,
141 upgrade: bool,
142 upgrade_packages: tuple[str, ...],
143 output_file: LazyFile | IO[Any] | None,
144 newline: str,
145 allow_unsafe: bool,
146 strip_extras: bool | None,
147 generate_hashes: bool,
148 reuse_hashes: bool,
149 src_files: tuple[str, ...],
150 max_rounds: int,
151 build_isolation: bool,
152 emit_find_links: bool,
153 cache_dir: str,
154 pip_args_str: str | None,
155 resolver_name: str,
156 emit_index_url: bool,
157 emit_options: bool,
158 unsafe_package: tuple[str, ...],
159 config: Path | None,
160 no_config: bool,
161 constraint: tuple[str, ...],
162 build_deps_targets: tuple[BuildTargetT, ...],
163 all_build_deps: bool,
164 only_build_deps: bool,
165 ) -> None:
166 """
167 Compiles requirements.txt from requirements.in, pyproject.toml, setup.cfg,
168 or setup.py specs.
169 """
170 if color is not None:
171 ctx.color = color
172 log.verbosity = verbose - quiet
173
174 # If ``src-files` was not provided as an input, but rather as config,
175 # it will be part of the click context ``ctx``.
176 # However, if ``src_files`` is specified, then we want to use that.
177 if not src_files and ctx.default_map and "src_files" in ctx.default_map:
178 src_files = ctx.default_map["src_files"]
179
180 if all_build_deps and build_deps_targets:
181 raise click.BadParameter(
182 "--build-deps-for has no effect when used with --all-build-deps"
183 )
184 elif all_build_deps:
185 build_deps_targets = options.ALL_BUILD_TARGETS
186
187 if only_build_deps and not build_deps_targets:
188 raise click.BadParameter(
189 "--only-build-deps requires either --build-deps-for or --all-build-deps"
190 )
191 if only_build_deps and (extras or all_extras):
192 raise click.BadParameter(
193 "--only-build-deps cannot be used with any of --extra, --all-extras"
194 )
195
196 if len(src_files) == 0:
197 for file_path in DEFAULT_REQUIREMENTS_FILES:
198 if os.path.exists(file_path):
199 src_files = (file_path,)
200 break
201 else:
202 raise click.BadParameter(
203 (
204 "If you do not specify an input file, the default is one of: {}"
205 ).format(", ".join(DEFAULT_REQUIREMENTS_FILES))
206 )
207
208 if all_extras and extras:
209 msg = "--extra has no effect when used with --all-extras"
210 raise click.BadParameter(msg)
211
212 if not output_file:
213 # An output file must be provided for stdin
214 if src_files == ("-",):
215 raise click.BadParameter("--output-file is required if input is from stdin")
216 # Use default requirements output file if there is a setup.py the source file
217 elif os.path.basename(src_files[0]) in METADATA_FILENAMES:
218 file_name = os.path.join(
219 os.path.dirname(src_files[0]), DEFAULT_REQUIREMENTS_OUTPUT_FILE
220 )
221 # An output file must be provided if there are multiple source files
222 elif len(src_files) > 1:
223 raise click.BadParameter(
224 "--output-file is required if two or more input files are given."
225 )
226 # Otherwise derive the output file from the source file
227 else:
228 base_name = src_files[0].rsplit(".", 1)[0]
229 file_name = base_name + ".txt"
230
231 output_file = click.open_file(file_name, "w+b", atomic=True, lazy=True)
232
233 # Close the file at the end of the context execution
234 assert output_file is not None
235 # only LazyFile has close_intelligently, newer IO[Any] does not
236 if isinstance(output_file, LazyFile): # pragma: no cover
237 ctx.call_on_close(safecall(output_file.close_intelligently))
238
239 if output_file.name != "-" and output_file.name in src_files:
240 raise click.BadArgumentUsage(
241 f"input and output filenames must not be matched: {output_file.name}"
242 )
243
244 if config:
245 log.debug(f"Using pip-tools configuration defaults found in '{config !s}'.")
246
247 if resolver_name == "legacy":
248 log.warning(
249 "WARNING: the legacy dependency resolver is deprecated and will be removed"
250 " in future versions of pip-tools."
251 )
252
253 ###
254 # Setup
255 ###
256
257 right_args = shlex.split(pip_args_str or "")
258 pip_args = []
259 for link in find_links:
260 pip_args.extend(["-f", link])
261 if index_url:
262 pip_args.extend(["-i", index_url])
263 if no_index:
264 pip_args.extend(["--no-index"])
265 for extra_index in extra_index_url:
266 pip_args.extend(["--extra-index-url", extra_index])
267 if cert:
268 pip_args.extend(["--cert", cert])
269 if client_cert:
270 pip_args.extend(["--client-cert", client_cert])
271 if pre:
272 pip_args.extend(["--pre"])
273 for host in trusted_host:
274 pip_args.extend(["--trusted-host", host])
275 if not build_isolation:
276 pip_args.append("--no-build-isolation")
277 if resolver_name == "legacy":
278 pip_args.extend(["--use-deprecated", "legacy-resolver"])
279 if resolver_name == "backtracking" and cache_dir:
280 pip_args.extend(["--cache-dir", cache_dir])
281 pip_args.extend(right_args)
282
283 repository: BaseRepository
284 repository = PyPIRepository(pip_args, cache_dir=cache_dir)
285
286 # Parse all constraints coming from --upgrade-package/-P
287 upgrade_reqs_gen = (install_req_from_line(pkg) for pkg in upgrade_packages)
288 upgrade_install_reqs = {
289 key_from_ireq(install_req): install_req for install_req in upgrade_reqs_gen
290 }
291
292 # Exclude packages from --upgrade-package/-P from the existing constraints
293 existing_pins = {}
294
295 # Proxy with a LocalRequirementsRepository if --upgrade is not specified
296 # (= default invocation)
297 output_file_exists = os.path.exists(output_file.name)
298 if not upgrade and output_file_exists:
299 output_file_is_empty = os.path.getsize(output_file.name) == 0
300 if upgrade_install_reqs and output_file_is_empty:
301 log.warning(
302 f"WARNING: the output file {output_file.name} exists but is empty. "
303 "Pip-tools cannot upgrade only specific packages (using -P/--upgrade-package) "
304 "without an existing pin file to provide constraints. "
305 "This often occurs if you redirect standard output to your output file, "
306 "as any existing content is truncated."
307 )
308
309 # Use a temporary repository to ensure outdated(removed) options from
310 # existing requirements.txt wouldn't get into the current repository.
311 tmp_repository = PyPIRepository(pip_args, cache_dir=cache_dir)
312 ireqs = parse_requirements(
313 output_file.name,
314 finder=tmp_repository.finder,
315 session=tmp_repository.session,
316 options=tmp_repository.options,
317 )
318
319 for ireq in filter(is_pinned_requirement, ireqs):
320 key = key_from_ireq(ireq)
321 if key not in upgrade_install_reqs:
322 existing_pins[key] = ireq
323 repository = LocalRequirementsRepository(
324 existing_pins, repository, reuse_hashes=reuse_hashes
325 )
326
327 ###
328 # Parsing/collecting initial requirements
329 ###
330
331 constraints: list[InstallRequirement] = []
332 setup_file_found = False
333 for src_file in src_files:
334 is_setup_file = os.path.basename(src_file) in METADATA_FILENAMES
335 if not is_setup_file and build_deps_targets:
336 msg = (
337 "--build-deps-for and --all-build-deps can be used only with the "
338 "setup.py, setup.cfg and pyproject.toml specs."
339 )
340 raise click.BadParameter(msg)
341
342 if src_file == "-":
343 # pip requires filenames and not files. Since we want to support
344 # piping from stdin, we need to briefly save the input from stdin
345 # to a temporary file and have pip read that. also used for
346 # reading requirements from install_requires in setup.py.
347 tmpfile = tempfile.NamedTemporaryFile(mode="wt", delete=False)
348 tmpfile.write(sys.stdin.read())
349 comes_from = "-r -"
350 tmpfile.flush()
351 reqs = list(
352 parse_requirements(
353 tmpfile.name,
354 finder=repository.finder,
355 session=repository.session,
356 options=repository.options,
357 )
358 )
359 for req in reqs:
360 req.comes_from = comes_from
361 constraints.extend(reqs)
362 elif is_setup_file:
363 setup_file_found = True
364 try:
365 metadata = build_project_metadata(
366 src_file=Path(src_file),
367 build_targets=build_deps_targets,
368 isolated=build_isolation,
369 quiet=log.verbosity <= 0,
370 )
371 except BuildBackendException as e:
372 log.error(str(e))
373 log.error(f"Failed to parse {os.path.abspath(src_file)}")
374 sys.exit(2)
375
376 if not only_build_deps:
377 constraints.extend(metadata.requirements)
378 if all_extras:
379 extras += metadata.extras
380 if build_deps_targets:
381 constraints.extend(metadata.build_requirements)
382 else:
383 constraints.extend(
384 parse_requirements(
385 src_file,
386 finder=repository.finder,
387 session=repository.session,
388 options=repository.options,
389 )
390 )
391
392 # Parse all constraints from `--constraint` files
393 for filename in constraint:
394 constraints.extend(
395 parse_requirements(
396 filename,
397 constraint=True,
398 finder=repository.finder,
399 options=repository.options,
400 session=repository.session,
401 )
402 )
403
404 if upgrade_packages:
405 constraints_file = tempfile.NamedTemporaryFile(mode="wt", delete=False)
406 constraints_file.write("\n".join(upgrade_packages))
407 constraints_file.flush()
408 try:
409 reqs = list(
410 parse_requirements(
411 constraints_file.name,
412 finder=repository.finder,
413 session=repository.session,
414 options=repository.options,
415 constraint=True,
416 )
417 )
418 finally:
419 constraints_file.close()
420 os.unlink(constraints_file.name)
421 for req in reqs:
422 req.comes_from = None
423 constraints.extend(reqs)
424
425 extras = tuple(itertools.chain.from_iterable(ex.split(",") for ex in extras))
426
427 if extras and not setup_file_found:
428 msg = "--extra has effect only with setup.py and PEP-517 input formats"
429 raise click.BadParameter(msg)
430
431 primary_packages = {
432 key_from_ireq(ireq) for ireq in constraints if not ireq.constraint
433 }
434
435 constraints.extend(
436 ireq for key, ireq in upgrade_install_reqs.items() if key in primary_packages
437 )
438
439 constraints = [req for req in constraints if req.match_markers(extras)]
440 for req in constraints:
441 drop_extras(req)
442
443 if repository.finder.index_urls:
444 log.debug("Using indexes:")
445 with log.indentation():
446 for index_url in dedup(repository.finder.index_urls):
447 log.debug(redact_auth_from_url(index_url))
448 else:
449 log.debug("Ignoring indexes.")
450
451 if repository.finder.find_links:
452 log.debug("")
453 log.debug("Using links:")
454 with log.indentation():
455 for find_link in dedup(repository.finder.find_links):
456 log.debug(redact_auth_from_url(find_link))
457
458 resolver_cls = LegacyResolver if resolver_name == "legacy" else BacktrackingResolver
459 try:
460 resolver = resolver_cls(
461 constraints=constraints,
462 existing_constraints=existing_pins,
463 repository=repository,
464 prereleases=repository.finder.allow_all_prereleases or pre,
465 cache=DependencyCache(cache_dir),
466 clear_caches=rebuild,
467 allow_unsafe=allow_unsafe,
468 unsafe_packages=set(unsafe_package),
469 )
470 results = resolver.resolve(max_rounds=max_rounds)
471 hashes = resolver.resolve_hashes(results) if generate_hashes else None
472 except NoCandidateFound as e:
473 if resolver_cls == LegacyResolver: # pragma: no branch
474 log.error(
475 "Using legacy resolver. "
476 "Consider using backtracking resolver with "
477 "`--resolver=backtracking`."
478 )
479
480 log.error(str(e))
481 sys.exit(2)
482 except PipToolsError as e:
483 log.error(str(e))
484 sys.exit(2)
485
486 log.debug("")
487
488 linesep = _determine_linesep(
489 strategy=newline, filenames=(output_file.name, *src_files)
490 )
491
492 if strip_extras is None:
493 strip_extras = False
494 log.warning(
495 "WARNING: --strip-extras is becoming the default "
496 "in version 8.0.0. To silence this warning, "
497 "either use --strip-extras to opt into the new default "
498 "or use --no-strip-extras to retain the existing behavior."
499 )
500
501 ##
502 # Output
503 ##
504
505 writer = OutputWriter(
506 cast(BinaryIO, output_file),
507 click_ctx=ctx,
508 dry_run=dry_run,
509 emit_header=header,
510 emit_index_url=emit_index_url,
511 emit_trusted_host=emit_trusted_host,
512 annotate=annotate,
513 annotation_style=annotation_style,
514 strip_extras=strip_extras,
515 generate_hashes=generate_hashes,
516 default_index_url=repository.DEFAULT_INDEX_URL,
517 index_urls=repository.finder.index_urls,
518 trusted_hosts=repository.finder.trusted_hosts,
519 format_control=repository.finder.format_control,
520 linesep=linesep,
521 allow_unsafe=allow_unsafe,
522 find_links=repository.finder.find_links,
523 emit_find_links=emit_find_links,
524 emit_options=emit_options,
525 )
526 writer.write(
527 results=results,
528 unsafe_packages=resolver.unsafe_packages,
529 unsafe_requirements=resolver.unsafe_constraints,
530 markers={
531 key_from_ireq(ireq): ireq.markers for ireq in constraints if ireq.markers
532 },
533 hashes=hashes,
534 )
535
536 if dry_run:
537 log.info("Dry-run, so nothing updated.")