|
| 1 | +from typing import Any, Dict, Iterable, Iterator, List, Tuple |
| 2 | + |
| 3 | +from pip._vendor import tomli |
| 4 | +from pip._vendor.dependency_groups import DependencyGroupResolver |
| 5 | + |
| 6 | +from pip._internal.exceptions import InstallationError |
| 7 | + |
| 8 | + |
| 9 | +def parse_dependency_groups(groups: List[Tuple[str, str]]) -> List[str]: |
| 10 | + """ |
| 11 | + Parse dependency groups data as provided via the CLI, in a `[path:]group` syntax. |
| 12 | +
|
| 13 | + Raises InstallationErrors if anything goes wrong. |
| 14 | + """ |
| 15 | + resolvers = _build_resolvers(path for (path, _) in groups) |
| 16 | + return list(_resolve_all_groups(resolvers, groups)) |
| 17 | + |
| 18 | + |
| 19 | +def _resolve_all_groups( |
| 20 | + resolvers: Dict[str, DependencyGroupResolver], groups: List[Tuple[str, str]] |
| 21 | +) -> Iterator[str]: |
| 22 | + """ |
| 23 | + Run all resolution, converting any error from `DependencyGroupResolver` into |
| 24 | + an InstallationError. |
| 25 | + """ |
| 26 | + for path, groupname in groups: |
| 27 | + resolver = resolvers[path] |
| 28 | + try: |
| 29 | + yield from (str(req) for req in resolver.resolve(groupname)) |
| 30 | + except (ValueError, TypeError, LookupError) as e: |
| 31 | + raise InstallationError( |
| 32 | + f"[dependency-groups] resolution failed for '{groupname}' " |
| 33 | + f"from '{path}': {e}" |
| 34 | + ) from e |
| 35 | + |
| 36 | + |
| 37 | +def _build_resolvers(paths: Iterable[str]) -> Dict[str, Any]: |
| 38 | + resolvers = {} |
| 39 | + for path in paths: |
| 40 | + if path in resolvers: |
| 41 | + continue |
| 42 | + |
| 43 | + pyproject = _load_pyproject(path) |
| 44 | + if "dependency-groups" not in pyproject: |
| 45 | + raise InstallationError( |
| 46 | + f"[dependency-groups] table was missing from '{path}'. " |
| 47 | + "Cannot resolve '--group' option." |
| 48 | + ) |
| 49 | + raw_dependency_groups = pyproject["dependency-groups"] |
| 50 | + if not isinstance(raw_dependency_groups, dict): |
| 51 | + raise InstallationError( |
| 52 | + f"[dependency-groups] table was malformed in {path}. " |
| 53 | + "Cannot resolve '--group' option." |
| 54 | + ) |
| 55 | + |
| 56 | + resolvers[path] = DependencyGroupResolver(raw_dependency_groups) |
| 57 | + return resolvers |
| 58 | + |
| 59 | + |
| 60 | +def _load_pyproject(path: str) -> Dict[str, Any]: |
| 61 | + """ |
| 62 | + This helper loads a pyproject.toml as TOML. |
| 63 | +
|
| 64 | + It raises an InstallationError if the operation fails. |
| 65 | + """ |
| 66 | + try: |
| 67 | + with open(path, "rb") as fp: |
| 68 | + return tomli.load(fp) |
| 69 | + except FileNotFoundError: |
| 70 | + raise InstallationError(f"{path} not found. Cannot resolve '--group' option.") |
| 71 | + except tomli.TOMLDecodeError as e: |
| 72 | + raise InstallationError(f"Error parsing {path}: {e}") from e |
| 73 | + except OSError as e: |
| 74 | + raise InstallationError(f"Error reading {path}: {e}") from e |
0 commit comments