| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import collections |
| 4 |
import copy |
| 5 |
import difflib |
| 6 |
import itertools |
| 7 |
import json |
| 8 |
import os |
| 9 |
import re |
| 10 |
import shlex |
| 11 |
import sys |
| 12 |
from pathlib import Path |
| 13 |
from typing import Any, Callable, Iterable, Iterator, TypeVar, cast |
| 14 |
|
| 15 |
from click.core import ParameterSource |
| 16 |
|
| 17 |
if sys.version_info >= (3, 11): |
| 18 |
import tomllib |
| 19 |
else: |
| 20 |
import tomli as tomllib |
| 21 |
|
| 22 |
import click |
| 23 |
from click.utils import LazyFile |
| 24 |
from pip._internal.req import InstallRequirement |
| 25 |
from pip._internal.req.constructors import install_req_from_line |
| 26 |
from pip._internal.resolution.resolvelib.base import Requirement as PipRequirement |
| 27 |
from pip._internal.utils.misc import redact_auth_from_url |
| 28 |
from pip._internal.vcs import is_url |
| 29 |
from pip._vendor.packaging.markers import Marker |
| 30 |
from pip._vendor.packaging.requirements import Requirement |
| 31 |
from pip._vendor.packaging.specifiers import SpecifierSet |
| 32 |
from pip._vendor.packaging.utils import canonicalize_name |
| 33 |
from pip._vendor.packaging.version import Version |
| 34 |
from pip._vendor.pkg_resources import get_distribution |
| 35 |
|
| 36 |
from piptools._compat import PIP_VERSION |
| 37 |
from piptools.locations import DEFAULT_CONFIG_FILE_NAMES |
| 38 |
from piptools.subprocess_utils import run_python_snippet |
| 39 |
|
| 40 |
_KT = TypeVar("_KT") |
| 41 |
_VT = TypeVar("_VT") |
| 42 |
_T = TypeVar("_T") |
| 43 |
_S = TypeVar("_S") |
| 44 |
|
| 45 |
UNSAFE_PACKAGES = {"setuptools", "distribute", "pip"} |
| 46 |
COMPILE_EXCLUDE_OPTIONS = { |
| 47 |
"--dry-run", |
| 48 |
"--quiet", |
| 49 |
"--rebuild", |
| 50 |
"--upgrade", |
| 51 |
"--upgrade-package", |
| 52 |
"--verbose", |
| 53 |
"--cache-dir", |
| 54 |
"--no-reuse-hashes", |
| 55 |
"--no-config", |
| 56 |
} |
| 57 |
|
| 58 |
# Set of option that are only negative, i.e. --no-<option> |
| 59 |
ONLY_NEGATIVE_OPTIONS = {"--no-index"} |
| 60 |
|
| 61 |
|
| 62 |
def key_from_ireq(ireq: InstallRequirement) -> str: |
| 63 |
"""Get a standardized key for an InstallRequirement.""" |
| 64 |
if ireq.req is None and ireq.link is not None: |
| 65 |
return str(ireq.link) |
| 66 |
else: |
| 67 |
return key_from_req(ireq.req) |
| 68 |
|
| 69 |
|
| 70 |
def key_from_req(req: InstallRequirement | Requirement | PipRequirement) -> str: |
| 71 |
""" |
| 72 |
Get an all-lowercase version of the requirement's name. |
| 73 |
|
| 74 |
**Note:** If the argument is an instance of |
| 75 |
``pip._internal.resolution.resolvelib.base.Requirement`` (like |
| 76 |
``pip._internal.resolution.resolvelib.requirements.SpecifierRequirement``), |
| 77 |
then the name might include an extras specification. |
| 78 |
Apply :py:func:`strip_extras` to the result of this function if you need |
| 79 |
the package name only. |
| 80 |
|
| 81 |
:param req: the requirement the key is computed for |
| 82 |
:return: the canonical name of the requirement |
| 83 |
""" |
| 84 |
return str(canonicalize_name(req.name)) |
| 85 |
|
| 86 |
|
| 87 |
def comment(text: str) -> str: |
| 88 |
return click.style(text, fg="green") |
| 89 |
|
| 90 |
|
| 91 |
def make_install_requirement( |
| 92 |
name: str, version: str | Version, ireq: InstallRequirement |
| 93 |
) -> InstallRequirement: |
| 94 |
# If no extras are specified, the extras string is blank |
| 95 |
extras_string = "" |
| 96 |
extras = ireq.extras |
| 97 |
if extras: |
| 98 |
# Sort extras for stability |
| 99 |
extras_string = f"[{','.join(sorted(extras))}]" |
| 100 |
|
| 101 |
version_pin_operator = "==" |
| 102 |
version_as_str = str(version) |
| 103 |
for specifier in ireq.specifier: |
| 104 |
if specifier.operator == "===" and specifier.version == version_as_str: |
| 105 |
version_pin_operator = "===" |
| 106 |
break |
| 107 |
|
| 108 |
return install_req_from_line( |
| 109 |
str(f"{name}{extras_string}{version_pin_operator}{version}"), |
| 110 |
constraint=ireq.constraint, |
| 111 |
) |
| 112 |
|
| 113 |
|
| 114 |
def is_url_requirement(ireq: InstallRequirement) -> bool: |
| 115 |
""" |
| 116 |
Return True if requirement was specified as a path or URL. |
| 117 |
ireq.original_link will have been set by InstallRequirement.__init__ |
| 118 |
""" |
| 119 |
return bool(ireq.original_link) |
| 120 |
|
| 121 |
|
| 122 |
def format_requirement( |
| 123 |
ireq: InstallRequirement, |
| 124 |
marker: Marker | None = None, |
| 125 |
hashes: set[str] | None = None, |
| 126 |
) -> str: |
| 127 |
""" |
| 128 |
Generic formatter for pretty printing InstallRequirements to the terminal |
| 129 |
in a less verbose way than using its `__str__` method. |
| 130 |
""" |
| 131 |
if ireq.editable: |
| 132 |
line = f"-e {ireq.link.url}" |
| 133 |
elif is_url_requirement(ireq): |
| 134 |
line = _build_direct_reference_best_efforts(ireq) |
| 135 |
else: |
| 136 |
# Canonicalize the requirement name |
| 137 |
# https://packaging.pypa.io/en/latest/utils.html#packaging.utils.canonicalize_name |
| 138 |
req = copy.copy(ireq.req) |
| 139 |
req.name = canonicalize_name(req.name) |
| 140 |
line = str(req) |
| 141 |
|
| 142 |
if marker: |
| 143 |
line = f"{line} ; {marker}" |
| 144 |
|
| 145 |
if hashes: |
| 146 |
for hash_ in sorted(hashes): |
| 147 |
line += f" \\\n --hash={hash_}" |
| 148 |
|
| 149 |
return line |
| 150 |
|
| 151 |
|
| 152 |
def _build_direct_reference_best_efforts(ireq: InstallRequirement) -> str: |
| 153 |
""" |
| 154 |
Returns a string of a direct reference URI, whenever possible. |
| 155 |
See https://www.python.org/dev/peps/pep-0508/ |
| 156 |
""" |
| 157 |
# If the requirement has no name then we cannot build a direct reference. |
| 158 |
if not ireq.name: |
| 159 |
return cast(str, ireq.link.url) |
| 160 |
|
| 161 |
# Look for a relative file path, the direct reference currently does not work with it. |
| 162 |
if ireq.link.is_file and not ireq.link.path.startswith("/"): |
| 163 |
return cast(str, ireq.link.url) |
| 164 |
|
| 165 |
# If we get here then we have a requirement that supports direct reference. |
| 166 |
# We need to remove the egg if it exists and keep the rest of the fragments. |
| 167 |
lowered_ireq_name = canonicalize_name(ireq.name) |
| 168 |
extras = f"[{','.join(sorted(ireq.extras))}]" if ireq.extras else "" |
| 169 |
direct_reference = f"{lowered_ireq_name}{extras} @ {ireq.link.url_without_fragment}" |
| 170 |
fragments = [] |
| 171 |
|
| 172 |
# Check if there is any fragment to add to the URI. |
| 173 |
if ireq.link.subdirectory_fragment: |
| 174 |
fragments.append(f"subdirectory={ireq.link.subdirectory_fragment}") |
| 175 |
|
| 176 |
if ireq.link.has_hash: |
| 177 |
fragments.append(f"{ireq.link.hash_name}={ireq.link.hash}") |
| 178 |
|
| 179 |
# Then add the fragments into the URI, if any. |
| 180 |
if fragments: |
| 181 |
direct_reference += f"#{'&'.join(fragments)}" |
| 182 |
|
| 183 |
return direct_reference |
| 184 |
|
| 185 |
|
| 186 |
def format_specifier(ireq: InstallRequirement) -> str: |
| 187 |
""" |
| 188 |
Generic formatter for pretty printing the specifier part of |
| 189 |
InstallRequirements to the terminal. |
| 190 |
""" |
| 191 |
# TODO: Ideally, this is carried over to the pip library itself |
| 192 |
specs = ireq.specifier if ireq.req is not None else SpecifierSet() |
| 193 |
# FIXME: remove ignore type marker once the following issue get fixed |
| 194 |
# https://github.com/python/mypy/issues/9656 |
| 195 |
specs = sorted(specs, key=lambda x: x.version) |
| 196 |
return ",".join(str(s) for s in specs) or "<any>" |
| 197 |
|
| 198 |
|
| 199 |
def is_pinned_requirement(ireq: InstallRequirement) -> bool: |
| 200 |
""" |
| 201 |
Returns whether an InstallRequirement is a "pinned" requirement. |
| 202 |
|
| 203 |
An InstallRequirement is considered pinned if: |
| 204 |
|
| 205 |
- Is not editable |
| 206 |
- It has exactly one specifier |
| 207 |
- That specifier is "==" |
| 208 |
- The version does not contain a wildcard |
| 209 |
|
| 210 |
Examples: |
| 211 |
django==1.8 # pinned |
| 212 |
django>1.8 # NOT pinned |
| 213 |
django~=1.8 # NOT pinned |
| 214 |
django==1.* # NOT pinned |
| 215 |
""" |
| 216 |
if ireq.editable: |
| 217 |
return False |
| 218 |
|
| 219 |
if ireq.req is None or len(ireq.specifier) != 1: |
| 220 |
return False |
| 221 |
|
| 222 |
spec = next(iter(ireq.specifier)) |
| 223 |
return spec.operator in {"==", "==="} and not spec.version.endswith(".*") |
| 224 |
|
| 225 |
|
| 226 |
def as_tuple(ireq: InstallRequirement) -> tuple[str, str, tuple[str, ...]]: |
| 227 |
""" |
| 228 |
Pulls out the (name: str, version:str, extras:(str)) tuple from |
| 229 |
the pinned InstallRequirement. |
| 230 |
""" |
| 231 |
if not is_pinned_requirement(ireq): |
| 232 |
raise TypeError(f"Expected a pinned InstallRequirement, got {ireq}") |
| 233 |
|
| 234 |
name = key_from_ireq(ireq) |
| 235 |
version = next(iter(ireq.specifier)).version |
| 236 |
extras = tuple(sorted(ireq.extras)) |
| 237 |
return name, version, extras |
| 238 |
|
| 239 |
|
| 240 |
def flat_map( |
| 241 |
fn: Callable[[_T], Iterable[_S]], collection: Iterable[_T] |
| 242 |
) -> Iterator[_S]: |
| 243 |
"""Map a function over a collection and flatten the result by one-level""" |
| 244 |
return itertools.chain.from_iterable(map(fn, collection)) |
| 245 |
|
| 246 |
|
| 247 |
def lookup_table_from_tuples(values: Iterable[tuple[_KT, _VT]]) -> dict[_KT, set[_VT]]: |
| 248 |
""" |
| 249 |
Builds a dict-based lookup table (index) elegantly. |
| 250 |
""" |
| 251 |
lut: dict[_KT, set[_VT]] = collections.defaultdict(set) |
| 252 |
for k, v in values: |
| 253 |
lut[k].add(v) |
| 254 |
return dict(lut) |
| 255 |
|
| 256 |
|
| 257 |
def lookup_table( |
| 258 |
values: Iterable[_VT], key: Callable[[_VT], _KT] |
| 259 |
) -> dict[_KT, set[_VT]]: |
| 260 |
""" |
| 261 |
Builds a dict-based lookup table (index) elegantly. |
| 262 |
""" |
| 263 |
return lookup_table_from_tuples((key(v), v) for v in values) |
| 264 |
|
| 265 |
|
| 266 |
def dedup(iterable: Iterable[_T]) -> Iterable[_T]: |
| 267 |
"""Deduplicate an iterable object like iter(set(iterable)) but |
| 268 |
order-preserved. |
| 269 |
""" |
| 270 |
return iter(dict.fromkeys(iterable)) |
| 271 |
|
| 272 |
|
| 273 |
def drop_extras(ireq: InstallRequirement) -> None: |
| 274 |
"""Remove "extra" markers (PEP-508) from requirement.""" |
| 275 |
if ireq.markers is None: |
| 276 |
return |
| 277 |
ireq.markers._markers = _drop_extras(ireq.markers._markers) |
| 278 |
if not ireq.markers._markers: |
| 279 |
ireq.markers = None |
| 280 |
|
| 281 |
|
| 282 |
def _drop_extras(markers: list[_T]) -> list[_T]: |
| 283 |
# drop `extra` tokens |
| 284 |
to_remove: list[int] = [] |
| 285 |
for i, token in enumerate(markers): |
| 286 |
# operator (and/or) |
| 287 |
if isinstance(token, str): |
| 288 |
continue |
| 289 |
# sub-expression (inside braces) |
| 290 |
if isinstance(token, list): |
| 291 |
markers[i] = _drop_extras(token) # type: ignore |
| 292 |
if markers[i]: |
| 293 |
continue |
| 294 |
to_remove.append(i) |
| 295 |
continue |
| 296 |
# test expression (like `extra == "dev"`) |
| 297 |
assert isinstance(token, tuple) |
| 298 |
if token[0].value == "extra": |
| 299 |
to_remove.append(i) |
| 300 |
for i in reversed(to_remove): |
| 301 |
markers.pop(i) |
| 302 |
|
| 303 |
# drop duplicate bool operators (and/or) |
| 304 |
to_remove = [] |
| 305 |
for i, (token1, token2) in enumerate(zip(markers, markers[1:])): |
| 306 |
if not isinstance(token1, str): |
| 307 |
continue |
| 308 |
if not isinstance(token2, str): |
| 309 |
continue |
| 310 |
if token1 == "and": |
| 311 |
to_remove.append(i) |
| 312 |
else: |
| 313 |
to_remove.append(i + 1) |
| 314 |
for i in reversed(to_remove): |
| 315 |
markers.pop(i) |
| 316 |
if markers and isinstance(markers[0], str): |
| 317 |
markers.pop(0) |
| 318 |
if markers and isinstance(markers[-1], str): |
| 319 |
markers.pop(-1) |
| 320 |
|
| 321 |
return markers |
| 322 |
|
| 323 |
|
| 324 |
def get_hashes_from_ireq(ireq: InstallRequirement) -> set[str]: |
| 325 |
""" |
| 326 |
Given an InstallRequirement, return a set of string hashes in the format |
| 327 |
"{algorithm}:{hash}". Return an empty set if there are no hashes in the |
| 328 |
requirement options. |
| 329 |
""" |
| 330 |
result = set() |
| 331 |
for algorithm, hexdigests in ireq.hash_options.items(): |
| 332 |
for hash_ in hexdigests: |
| 333 |
result.add(f"{algorithm}:{hash_}") |
| 334 |
return result |
| 335 |
|
| 336 |
|
| 337 |
def get_compile_command(click_ctx: click.Context) -> str: |
| 338 |
""" |
| 339 |
Returns a normalized compile command depending on cli context. |
| 340 |
|
| 341 |
The command will be normalized by: |
| 342 |
- expanding options short to long |
| 343 |
- removing values that are already default |
| 344 |
- sorting the arguments |
| 345 |
- removing one-off arguments like '--upgrade' |
| 346 |
- removing arguments that don't change build behaviour like '--verbose' |
| 347 |
""" |
| 348 |
from piptools.scripts.compile import cli |
| 349 |
|
| 350 |
# Map of the compile cli options (option name -> click.Option) |
| 351 |
compile_options = {option.name: option for option in cli.params} |
| 352 |
|
| 353 |
left_args = [] |
| 354 |
right_args = [] |
| 355 |
|
| 356 |
for option_name, value in click_ctx.params.items(): |
| 357 |
option = compile_options[option_name] |
| 358 |
|
| 359 |
# Collect variadic args separately, they will be added |
| 360 |
# at the end of the command later |
| 361 |
if option.nargs < 0: |
| 362 |
# These will necessarily be src_files |
| 363 |
# Re-add click-stripped '--' if any start with '-' |
| 364 |
if any(val.startswith("-") and val != "-" for val in value): |
| 365 |
right_args.append("--") |
| 366 |
right_args.extend([shlex.quote(val) for val in value]) |
| 367 |
continue |
| 368 |
|
| 369 |
assert isinstance(option, click.Option) |
| 370 |
|
| 371 |
# Get the latest option name (usually it'll be a long name) |
| 372 |
option_long_name = option.opts[-1] |
| 373 |
|
| 374 |
# Exclude one-off options (--upgrade/--upgrade-package/--rebuild/...) |
| 375 |
# or options that don't change compile behaviour (--verbose/--dry-run/...) |
| 376 |
if option_long_name in COMPILE_EXCLUDE_OPTIONS: |
| 377 |
continue |
| 378 |
|
| 379 |
# Exclude config option if it's the default one |
| 380 |
if option_long_name == "--config": |
| 381 |
parameter_source = click_ctx.get_parameter_source(option_name) |
| 382 |
if ( |
| 383 |
str(value) in DEFAULT_CONFIG_FILE_NAMES |
| 384 |
or parameter_source == ParameterSource.DEFAULT |
| 385 |
): |
| 386 |
continue |
| 387 |
|
| 388 |
# Skip options without a value |
| 389 |
if option.default is None and not value: |
| 390 |
continue |
| 391 |
|
| 392 |
# Skip options with a default value |
| 393 |
if option.default == value: |
| 394 |
continue |
| 395 |
|
| 396 |
# Use a file name for file-like objects |
| 397 |
if isinstance(value, LazyFile): |
| 398 |
value = value.name |
| 399 |
|
| 400 |
# Convert value to the list |
| 401 |
if not isinstance(value, (tuple, list)): |
| 402 |
value = [value] |
| 403 |
|
| 404 |
for val in value: |
| 405 |
# Flags don't have a value, thus add to args true or false option long name |
| 406 |
if option.is_flag: |
| 407 |
# If there are false-options, choose an option name depending on a value |
| 408 |
if option.secondary_opts: |
| 409 |
# Get the latest false-option |
| 410 |
secondary_option_long_name = option.secondary_opts[-1] |
| 411 |
arg = option_long_name if val else secondary_option_long_name |
| 412 |
# There are no false-options, use true-option |
| 413 |
else: |
| 414 |
arg = option_long_name |
| 415 |
left_args.append(shlex.quote(arg)) |
| 416 |
# Append to args the option with a value |
| 417 |
else: |
| 418 |
if isinstance(val, str) and is_url(val): |
| 419 |
val = redact_auth_from_url(val) |
| 420 |
if option.name == "pip_args_str": |
| 421 |
# shlex.quote() would produce functional but noisily quoted results, |
| 422 |
# e.g. --pip-args='--cache-dir='"'"'/tmp/with spaces'"'"'' |
| 423 |
# Instead, we try to get more legible quoting via repr: |
| 424 |
left_args.append(f"{option_long_name}={repr(val)}") |
| 425 |
else: |
| 426 |
left_args.append(f"{option_long_name}={shlex.quote(str(val))}") |
| 427 |
|
| 428 |
return " ".join(["pip-compile", *sorted(left_args), *sorted(right_args)]) |
| 429 |
|
| 430 |
|
| 431 |
def get_required_pip_specification() -> SpecifierSet: |
| 432 |
""" |
| 433 |
Returns pip version specifier requested by current pip-tools installation. |
| 434 |
""" |
| 435 |
project_dist = get_distribution("pip-tools") |
| 436 |
requirement = next( |
| 437 |
(r for r in project_dist.requires() if r.name == "pip"), None |
| 438 |
) # pragma: no branch |
| 439 |
assert ( |
| 440 |
requirement is not None |
| 441 |
), "'pip' is expected to be in the list of pip-tools requirements" |
| 442 |
return requirement.specifier |
| 443 |
|
| 444 |
|
| 445 |
def get_pip_version_for_python_executable(python_executable: str) -> Version: |
| 446 |
""" |
| 447 |
Returns pip version for the given python executable. |
| 448 |
""" |
| 449 |
str_version = run_python_snippet( |
| 450 |
python_executable, "import pip;print(pip.__version__)" |
| 451 |
) |
| 452 |
return Version(str_version) |
| 453 |
|
| 454 |
|
| 455 |
def get_sys_path_for_python_executable(python_executable: str) -> list[str]: |
| 456 |
""" |
| 457 |
Returns sys.path list for the given python executable. |
| 458 |
""" |
| 459 |
result = run_python_snippet( |
| 460 |
python_executable, "import sys;import json;print(json.dumps(sys.path))" |
| 461 |
) |
| 462 |
|
| 463 |
paths = json.loads(result) |
| 464 |
assert isinstance(paths, list) |
| 465 |
assert all(isinstance(i, str) for i in paths) |
| 466 |
return [os.path.abspath(path) for path in paths] |
| 467 |
|
| 468 |
|
| 469 |
def omit_list_value(lst: list[_T], value: _T) -> list[_T]: |
| 470 |
"""Produce a new list with a given value skipped.""" |
| 471 |
return [item for item in lst if item != value] |
| 472 |
|
| 473 |
|
| 474 |
_strip_extras_re = re.compile(r"\[.+?\]") |
| 475 |
|
| 476 |
|
| 477 |
def strip_extras(name: str) -> str: |
| 478 |
"""Strip extras from package name, e.g. pytest[testing] -> pytest.""" |
| 479 |
return re.sub(_strip_extras_re, "", name) |
| 480 |
|
| 481 |
|
| 482 |
def copy_install_requirement( |
| 483 |
template: InstallRequirement, **extra_kwargs: Any |
| 484 |
) -> InstallRequirement: |
| 485 |
"""Make a copy of a template ``InstallRequirement`` with extra kwargs.""" |
| 486 |
# Prepare install requirement kwargs. |
| 487 |
kwargs = { |
| 488 |
"comes_from": template.comes_from, |
| 489 |
"editable": template.editable, |
| 490 |
"link": template.link, |
| 491 |
"markers": template.markers, |
| 492 |
"use_pep517": template.use_pep517, |
| 493 |
"isolated": template.isolated, |
| 494 |
"global_options": template.global_options, |
| 495 |
"hash_options": template.hash_options, |
| 496 |
"constraint": template.constraint, |
| 497 |
"extras": template.extras, |
| 498 |
"user_supplied": template.user_supplied, |
| 499 |
} |
| 500 |
kwargs.update(extra_kwargs) |
| 501 |
|
| 502 |
if PIP_VERSION[:2] <= (23, 0): |
| 503 |
kwargs["install_options"] = template.install_options |
| 504 |
|
| 505 |
# Original link does not belong to install requirements constructor, |
| 506 |
# pop it now to update later. |
| 507 |
original_link = kwargs.pop("original_link", None) |
| 508 |
|
| 509 |
# Copy template.req if not specified in extra kwargs. |
| 510 |
if "req" not in kwargs: |
| 511 |
kwargs["req"] = copy.deepcopy(template.req) |
| 512 |
|
| 513 |
ireq = InstallRequirement(**kwargs) |
| 514 |
|
| 515 |
# If the original_link was None, keep it so. Passing `link` as an |
| 516 |
# argument to `InstallRequirement` sets it as the original_link. |
| 517 |
ireq.original_link = ( |
| 518 |
template.original_link if original_link is None else original_link |
| 519 |
) |
| 520 |
|
| 521 |
return ireq |
| 522 |
|
| 523 |
|
| 524 |
def override_defaults_from_config_file( |
| 525 |
ctx: click.Context, param: click.Parameter, value: str | None |
| 526 |
) -> Path | None: |
| 527 |
""" |
| 528 |
Overrides ``click.Command`` defaults based on specified or discovered config |
| 529 |
file, returning the ``pathlib.Path`` of that config file if specified or |
| 530 |
discovered. |
| 531 |
|
| 532 |
``None`` is returned if no such file is found. |
| 533 |
|
| 534 |
``pip-tools`` will use the first config file found, searching in this order: |
| 535 |
an explicitly given config file, a ``.pip-tools.toml``, a ``pyproject.toml`` |
| 536 |
file. Those files are searched for in the same directory as the requirements |
| 537 |
input file, or the current working directory if requirements come via stdin. |
| 538 |
""" |
| 539 |
if ctx.params.get("no_config"): |
| 540 |
return None |
| 541 |
|
| 542 |
if value is None: |
| 543 |
config_file = select_config_file(ctx.params.get("src_files", ())) |
| 544 |
if config_file is None: |
| 545 |
return None |
| 546 |
else: |
| 547 |
config_file = Path(value) |
| 548 |
|
| 549 |
config = parse_config_file(ctx, config_file) |
| 550 |
|
| 551 |
_validate_config(ctx, config) |
| 552 |
_assign_config_to_cli_context(ctx, config) |
| 553 |
|
| 554 |
return config_file |
| 555 |
|
| 556 |
|
| 557 |
def _assign_config_to_cli_context( |
| 558 |
click_context: click.Context, |
| 559 |
cli_config_mapping: dict[str, Any], |
| 560 |
) -> None: |
| 561 |
if click_context.default_map is None: |
| 562 |
click_context.default_map = {} |
| 563 |
|
| 564 |
click_context.default_map.update(cli_config_mapping) |
| 565 |
|
| 566 |
|
| 567 |
def _validate_config( |
| 568 |
click_context: click.Context, |
| 569 |
config: dict[str, Any], |
| 570 |
) -> None: |
| 571 |
""" |
| 572 |
Validate parsed config against click command params. |
| 573 |
|
| 574 |
:raises click.NoSuchOption: if config contains unknown keys. |
| 575 |
:raises click.BadOptionUsage: if config contains invalid values. |
| 576 |
""" |
| 577 |
from piptools.scripts.compile import cli as compile_cli |
| 578 |
from piptools.scripts.sync import cli as sync_cli |
| 579 |
|
| 580 |
compile_cli_params = { |
| 581 |
param.name: param for param in compile_cli.params if param.name is not None |
| 582 |
} |
| 583 |
|
| 584 |
sync_cli_params = { |
| 585 |
param.name: param for param in sync_cli.params if param.name is not None |
| 586 |
} |
| 587 |
|
| 588 |
all_keys = set(compile_cli_params) | set(sync_cli_params) |
| 589 |
|
| 590 |
for key, value in config.items(): |
| 591 |
# Validate unknown keys in both compile and sync |
| 592 |
if key not in all_keys: |
| 593 |
possibilities = difflib.get_close_matches(key, all_keys) |
| 594 |
raise click.NoSuchOption( |
| 595 |
option_name=key, |
| 596 |
message=f"No such config key {key!r}.", |
| 597 |
possibilities=possibilities, |
| 598 |
ctx=click_context, |
| 599 |
) |
| 600 |
|
| 601 |
# Get all params associated with this key in both compile and sync |
| 602 |
associated_params = ( |
| 603 |
cli_params[key] |
| 604 |
for cli_params in (compile_cli_params, sync_cli_params) |
| 605 |
if key in cli_params |
| 606 |
) |
| 607 |
|
| 608 |
# Validate value against types of all associated params |
| 609 |
for param in associated_params: |
| 610 |
try: |
| 611 |
param.type_cast_value(value=value, ctx=click_context) |
| 612 |
except Exception as e: |
| 613 |
raise click.BadOptionUsage( |
| 614 |
option_name=key, |
| 615 |
message=( |
| 616 |
f"Invalid value for config key {key!r}: {value!r}.{os.linesep}" |
| 617 |
f"Details: {e}" |
| 618 |
), |
| 619 |
ctx=click_context, |
| 620 |
) from e |
| 621 |
|
| 622 |
|
| 623 |
def select_config_file(src_files: tuple[str, ...]) -> Path | None: |
| 624 |
""" |
| 625 |
Returns the config file to use for defaults given ``src_files`` provided. |
| 626 |
""" |
| 627 |
# NOTE: If no src_files were specified, consider the current directory the |
| 628 |
# NOTE: only config file lookup candidate. This usually happens when a |
| 629 |
# NOTE: pip-tools invocation gets its incoming requirements from standard |
| 630 |
# NOTE: input. |
| 631 |
working_directory = Path.cwd() |
| 632 |
src_files_as_paths = ( |
| 633 |
(working_directory / src_file).resolve() for src_file in src_files or (".",) |
| 634 |
) |
| 635 |
candidate_dirs = (src if src.is_dir() else src.parent for src in src_files_as_paths) |
| 636 |
config_file_path = next( |
| 637 |
( |
| 638 |
candidate_dir / config_file |
| 639 |
for candidate_dir in candidate_dirs |
| 640 |
for config_file in DEFAULT_CONFIG_FILE_NAMES |
| 641 |
if (candidate_dir / config_file).is_file() |
| 642 |
), |
| 643 |
None, |
| 644 |
) |
| 645 |
if config_file_path is None: |
| 646 |
return None |
| 647 |
|
| 648 |
return ( |
| 649 |
config_file_path.relative_to(working_directory) |
| 650 |
if is_path_relative_to(config_file_path, working_directory) |
| 651 |
else config_file_path |
| 652 |
) |
| 653 |
|
| 654 |
|
| 655 |
def get_cli_options(ctx: click.Context) -> dict[str, click.Parameter]: |
| 656 |
cli_opts = { |
| 657 |
opt: option |
| 658 |
for option in ctx.command.params |
| 659 |
for opt in itertools.chain(option.opts, option.secondary_opts) |
| 660 |
if opt.startswith("--") and option.name is not None |
| 661 |
} |
| 662 |
return cli_opts |
| 663 |
|
| 664 |
|
| 665 |
def parse_config_file( |
| 666 |
click_context: click.Context, config_file: Path |
| 667 |
) -> dict[str, Any]: |
| 668 |
try: |
| 669 |
config = tomllib.loads(config_file.read_text(encoding="utf-8")) |
| 670 |
except OSError as os_err: |
| 671 |
raise click.FileError( |
| 672 |
filename=str(config_file), |
| 673 |
hint=f"Could not read '{config_file !s}': {os_err !s}", |
| 674 |
) |
| 675 |
except ValueError as value_err: |
| 676 |
raise click.FileError( |
| 677 |
filename=str(config_file), |
| 678 |
hint=f"Could not parse '{config_file !s}': {value_err !s}", |
| 679 |
) |
| 680 |
|
| 681 |
# In a TOML file, we expect the config to be under `[tool.pip-tools]`, |
| 682 |
# `[tool.pip-tools.compile]` or `[tool.pip-tools.sync]` |
| 683 |
piptools_config: dict[str, Any] = config.get("tool", {}).get("pip-tools", {}) |
| 684 |
|
| 685 |
assert click_context.command.name is not None |
| 686 |
# TODO: Replace with `str.removeprefix()` once dropped 3.8 |
| 687 |
config_section_name = click_context.command.name[len("pip-") :] |
| 688 |
|
| 689 |
piptools_config.update(piptools_config.pop(config_section_name, {})) |
| 690 |
piptools_config.pop("compile", {}) |
| 691 |
piptools_config.pop("sync", {}) |
| 692 |
|
| 693 |
piptools_config = _normalize_keys_in_config(piptools_config) |
| 694 |
piptools_config = _invert_negative_bool_options_in_config( |
| 695 |
ctx=click_context, |
| 696 |
config=piptools_config, |
| 697 |
) |
| 698 |
|
| 699 |
return piptools_config |
| 700 |
|
| 701 |
|
| 702 |
def _normalize_keys_in_config(config: dict[str, Any]) -> dict[str, Any]: |
| 703 |
return {_normalize_config_key(key): value for key, value in config.items()} |
| 704 |
|
| 705 |
|
| 706 |
def _invert_negative_bool_options_in_config( |
| 707 |
ctx: click.Context, config: dict[str, Any] |
| 708 |
) -> dict[str, Any]: |
| 709 |
new_config = {} |
| 710 |
cli_opts = get_cli_options(ctx) |
| 711 |
|
| 712 |
for key, value in config.items(): |
| 713 |
# Transform config key to its equivalent in the CLI |
| 714 |
long_option = _convert_to_long_option(key) |
| 715 |
new_key = cli_opts[long_option].name if long_option in cli_opts else key |
| 716 |
negative_option_prefix = "no_" |
| 717 |
assert new_key is not None |
| 718 |
if ( |
| 719 |
new_key.startswith(negative_option_prefix) |
| 720 |
and long_option not in ONLY_NEGATIVE_OPTIONS |
| 721 |
): |
| 722 |
new_key = new_key[len(negative_option_prefix) :] |
| 723 |
|
| 724 |
# Invert negative boolean according to the CLI |
| 725 |
new_value = ( |
| 726 |
not value |
| 727 |
if long_option.startswith("--no-") |
| 728 |
and long_option not in ONLY_NEGATIVE_OPTIONS |
| 729 |
and isinstance(value, bool) |
| 730 |
else value |
| 731 |
) |
| 732 |
new_config[new_key] = new_value |
| 733 |
|
| 734 |
return new_config |
| 735 |
|
| 736 |
|
| 737 |
def _normalize_config_key(key: str) -> str: |
| 738 |
"""Transform given ``some-key`` into ``some_key``.""" |
| 739 |
return key.lstrip("-").replace("-", "_").lower() |
| 740 |
|
| 741 |
|
| 742 |
def _convert_to_long_option(key: str) -> str: |
| 743 |
"""Transform given ``some-key`` into ``--some-key``.""" |
| 744 |
return "--" + key.lstrip("-").replace("_", "-").lower() |
| 745 |
|
| 746 |
|
| 747 |
def is_path_relative_to(path1: Path, path2: Path) -> bool: |
| 748 |
"""Return True if ``path1`` is relative to ``path2``.""" |
| 749 |
# TODO: remove this function in favor of Path.is_relative_to() |
| 750 |
# when we drop support for Python 3.8 |
| 751 |
try: |
| 752 |
path1.relative_to(path2) |
| 753 |
except ValueError: |
| 754 |
return False |
| 755 |
return True |