Skip to content

Commit fb55c1d

Browse files
committed
Add 'dependency-groups==1.3.0' to vendored libs
Steps taken: - add `dependency-groups==1.3.0` to vendor.txt - add dependency-groups to vendor __init__.py - run vendoring sync - examine results to confirm apparent correctness (rewritten tomli imports)
1 parent af92b41 commit fb55c1d

File tree

10 files changed

+432
-0
lines changed

10 files changed

+432
-0
lines changed

src/pip/_vendor/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ def vendored(modulename):
6060
# Actually alias all of our vendored dependencies.
6161
vendored("cachecontrol")
6262
vendored("certifi")
63+
vendored("dependency-groups")
6364
vendored("distlib")
6465
vendored("distro")
6566
vendored("packaging")
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
MIT License
2+
3+
Copyright (c) 2024-present Stephen Rosen <[email protected]>
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6+
7+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8+
9+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from ._implementation import (
2+
CyclicDependencyError,
3+
DependencyGroupInclude,
4+
DependencyGroupResolver,
5+
resolve,
6+
)
7+
8+
__all__ = (
9+
"CyclicDependencyError",
10+
"DependencyGroupInclude",
11+
"DependencyGroupResolver",
12+
"resolve",
13+
)
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import argparse
2+
import sys
3+
4+
from ._implementation import resolve
5+
from ._toml_compat import tomllib
6+
7+
8+
def main() -> None:
9+
if tomllib is None:
10+
print(
11+
"Usage error: dependency-groups CLI requires tomli or Python 3.11+",
12+
file=sys.stderr,
13+
)
14+
raise SystemExit(2)
15+
16+
parser = argparse.ArgumentParser(
17+
description=(
18+
"A dependency-groups CLI. Prints out a resolved group, newline-delimited."
19+
)
20+
)
21+
parser.add_argument(
22+
"GROUP_NAME", nargs="*", help="The dependency group(s) to resolve."
23+
)
24+
parser.add_argument(
25+
"-f",
26+
"--pyproject-file",
27+
default="pyproject.toml",
28+
help="The pyproject.toml file. Defaults to trying in the current directory.",
29+
)
30+
parser.add_argument(
31+
"-o",
32+
"--output",
33+
help="An output file. Defaults to stdout.",
34+
)
35+
parser.add_argument(
36+
"-l",
37+
"--list",
38+
action="store_true",
39+
help="List the available dependency groups",
40+
)
41+
args = parser.parse_args()
42+
43+
with open(args.pyproject_file, "rb") as fp:
44+
pyproject = tomllib.load(fp)
45+
46+
dependency_groups_raw = pyproject.get("dependency-groups", {})
47+
48+
if args.list:
49+
print(*dependency_groups_raw.keys())
50+
return
51+
if not args.GROUP_NAME:
52+
print("A GROUP_NAME is required", file=sys.stderr)
53+
raise SystemExit(3)
54+
55+
content = "\n".join(resolve(dependency_groups_raw, *args.GROUP_NAME))
56+
57+
if args.output is None or args.output == "-":
58+
print(content)
59+
else:
60+
with open(args.output, "w", encoding="utf-8") as fp:
61+
print(content, file=fp)
62+
63+
64+
if __name__ == "__main__":
65+
main()
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
from __future__ import annotations
2+
3+
import dataclasses
4+
import re
5+
from collections.abc import Mapping
6+
7+
from pip._vendor.packaging.requirements import Requirement
8+
9+
10+
def _normalize_name(name: str) -> str:
11+
return re.sub(r"[-_.]+", "-", name).lower()
12+
13+
14+
def _normalize_group_names(
15+
dependency_groups: Mapping[str, str | Mapping[str, str]]
16+
) -> Mapping[str, str | Mapping[str, str]]:
17+
original_names: dict[str, list[str]] = {}
18+
normalized_groups = {}
19+
20+
for group_name, value in dependency_groups.items():
21+
normed_group_name = _normalize_name(group_name)
22+
original_names.setdefault(normed_group_name, []).append(group_name)
23+
normalized_groups[normed_group_name] = value
24+
25+
errors = []
26+
for normed_name, names in original_names.items():
27+
if len(names) > 1:
28+
errors.append(f"{normed_name} ({', '.join(names)})")
29+
if errors:
30+
raise ValueError(f"Duplicate dependency group names: {', '.join(errors)}")
31+
32+
return normalized_groups
33+
34+
35+
@dataclasses.dataclass
36+
class DependencyGroupInclude:
37+
include_group: str
38+
39+
40+
class CyclicDependencyError(ValueError):
41+
"""
42+
An error representing the detection of a cycle.
43+
"""
44+
45+
def __init__(self, requested_group: str, group: str, include_group: str) -> None:
46+
self.requested_group = requested_group
47+
self.group = group
48+
self.include_group = include_group
49+
50+
if include_group == group:
51+
reason = f"{group} includes itself"
52+
else:
53+
reason = f"{include_group} -> {group}, {group} -> {include_group}"
54+
super().__init__(
55+
"Cyclic dependency group include while resolving "
56+
f"{requested_group}: {reason}"
57+
)
58+
59+
60+
class DependencyGroupResolver:
61+
"""
62+
A resolver for Dependency Group data.
63+
64+
This class handles caching, name normalization, cycle detection, and other
65+
parsing requirements. There are only two public methods for exploring the data:
66+
``lookup()`` and ``resolve()``.
67+
68+
:param dependency_groups: A mapping, as provided via pyproject
69+
``[dependency-groups]``.
70+
"""
71+
72+
def __init__(
73+
self,
74+
dependency_groups: Mapping[str, str | Mapping[str, str]],
75+
) -> None:
76+
if not isinstance(dependency_groups, Mapping):
77+
raise TypeError("Dependency Groups table is not a mapping")
78+
self.dependency_groups = _normalize_group_names(dependency_groups)
79+
# a map of group names to parsed data
80+
self._parsed_groups: dict[
81+
str, tuple[Requirement | DependencyGroupInclude, ...]
82+
] = {}
83+
# a map of group names to their ancestors, used for cycle detection
84+
self._include_graph_ancestors: dict[str, tuple[str, ...]] = {}
85+
# a cache of completed resolutions to Requirement lists
86+
self._resolve_cache: dict[str, tuple[Requirement, ...]] = {}
87+
88+
def lookup(self, group: str) -> tuple[Requirement | DependencyGroupInclude, ...]:
89+
"""
90+
Lookup a group name, returning the parsed dependency data for that group.
91+
This will not resolve includes.
92+
93+
:param group: the name of the group to lookup
94+
95+
:raises ValueError: if the data does not appear to be valid dependency group
96+
data
97+
:raises TypeError: if the data is not a string
98+
:raises LookupError: if group name is absent
99+
:raises packaging.requirements.InvalidRequirement: if a specifier is not valid
100+
"""
101+
if not isinstance(group, str):
102+
raise TypeError("Dependency group name is not a str")
103+
group = _normalize_name(group)
104+
return self._parse_group(group)
105+
106+
def resolve(self, group: str) -> tuple[Requirement, ...]:
107+
"""
108+
Resolve a dependency group to a list of requirements.
109+
110+
:param group: the name of the group to resolve
111+
112+
:raises TypeError: if the inputs appear to be the wrong types
113+
:raises ValueError: if the data does not appear to be valid dependency group
114+
data
115+
:raises LookupError: if group name is absent
116+
:raises packaging.requirements.InvalidRequirement: if a specifier is not valid
117+
"""
118+
if not isinstance(group, str):
119+
raise TypeError("Dependency group name is not a str")
120+
group = _normalize_name(group)
121+
return self._resolve(group, group)
122+
123+
def _parse_group(
124+
self, group: str
125+
) -> tuple[Requirement | DependencyGroupInclude, ...]:
126+
# short circuit -- never do the work twice
127+
if group in self._parsed_groups:
128+
return self._parsed_groups[group]
129+
130+
if group not in self.dependency_groups:
131+
raise LookupError(f"Dependency group '{group}' not found")
132+
133+
raw_group = self.dependency_groups[group]
134+
if not isinstance(raw_group, list):
135+
raise TypeError(f"Dependency group '{group}' is not a list")
136+
137+
elements: list[Requirement | DependencyGroupInclude] = []
138+
for item in raw_group:
139+
if isinstance(item, str):
140+
# packaging.requirements.Requirement parsing ensures that this is a
141+
# valid PEP 508 Dependency Specifier
142+
# raises InvalidRequirement on failure
143+
elements.append(Requirement(item))
144+
elif isinstance(item, dict):
145+
if tuple(item.keys()) != ("include-group",):
146+
raise ValueError(f"Invalid dependency group item: {item}")
147+
148+
include_group = next(iter(item.values()))
149+
elements.append(DependencyGroupInclude(include_group=include_group))
150+
else:
151+
raise ValueError(f"Invalid dependency group item: {item}")
152+
153+
self._parsed_groups[group] = tuple(elements)
154+
return self._parsed_groups[group]
155+
156+
def _resolve(self, group: str, requested_group: str) -> tuple[Requirement, ...]:
157+
"""
158+
This is a helper for cached resolution to strings.
159+
160+
:param group: The name of the group to resolve.
161+
:param requested_group: The group which was used in the original, user-facing
162+
request.
163+
"""
164+
if group in self._resolve_cache:
165+
return self._resolve_cache[group]
166+
167+
parsed = self._parse_group(group)
168+
169+
resolved_group = []
170+
for item in parsed:
171+
if isinstance(item, Requirement):
172+
resolved_group.append(item)
173+
elif isinstance(item, DependencyGroupInclude):
174+
if item.include_group in self._include_graph_ancestors.get(group, ()):
175+
raise CyclicDependencyError(
176+
requested_group, group, item.include_group
177+
)
178+
self._include_graph_ancestors[item.include_group] = (
179+
*self._include_graph_ancestors.get(group, ()),
180+
group,
181+
)
182+
resolved_group.extend(
183+
self._resolve(item.include_group, requested_group)
184+
)
185+
else: # unreachable
186+
raise NotImplementedError(
187+
f"Invalid dependency group item after parse: {item}"
188+
)
189+
190+
self._resolve_cache[group] = tuple(resolved_group)
191+
return self._resolve_cache[group]
192+
193+
194+
def resolve(
195+
dependency_groups: Mapping[str, str | Mapping[str, str]], /, *groups: str
196+
) -> tuple[str, ...]:
197+
"""
198+
Resolve a dependency group to a tuple of requirements, as strings.
199+
200+
:param dependency_groups: the parsed contents of the ``[dependency-groups]`` table
201+
from ``pyproject.toml``
202+
:param groups: the name of the group(s) to resolve
203+
204+
:raises TypeError: if the inputs appear to be the wrong types
205+
:raises ValueError: if the data does not appear to be valid dependency group data
206+
:raises LookupError: if group name is absent
207+
:raises packaging.requirements.InvalidRequirement: if a specifier is not valid
208+
"""
209+
return tuple(
210+
str(r)
211+
for group in groups
212+
for r in DependencyGroupResolver(dependency_groups).resolve(group)
213+
)
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
from __future__ import annotations
2+
3+
import argparse
4+
import sys
5+
6+
from ._implementation import DependencyGroupResolver
7+
from ._toml_compat import tomllib
8+
9+
10+
def main(*, argv: list[str] | None = None) -> None:
11+
if tomllib is None:
12+
print(
13+
"Usage error: dependency-groups CLI requires tomli or Python 3.11+",
14+
file=sys.stderr,
15+
)
16+
raise SystemExit(2)
17+
18+
parser = argparse.ArgumentParser(
19+
description=(
20+
"Lint Dependency Groups for validity. "
21+
"This will eagerly load and check all of your Dependency Groups."
22+
)
23+
)
24+
parser.add_argument(
25+
"-f",
26+
"--pyproject-file",
27+
default="pyproject.toml",
28+
help="The pyproject.toml file. Defaults to trying in the current directory.",
29+
)
30+
args = parser.parse_args(argv if argv is not None else sys.argv[1:])
31+
32+
with open(args.pyproject_file, "rb") as fp:
33+
pyproject = tomllib.load(fp)
34+
dependency_groups_raw = pyproject.get("dependency-groups", {})
35+
36+
errors: list[str] = []
37+
try:
38+
resolver = DependencyGroupResolver(dependency_groups_raw)
39+
except (ValueError, TypeError) as e:
40+
errors.append(f"{type(e).__name__}: {e}")
41+
else:
42+
for groupname in resolver.dependency_groups:
43+
try:
44+
resolver.resolve(groupname)
45+
except (LookupError, ValueError, TypeError) as e:
46+
errors.append(f"{type(e).__name__}: {e}")
47+
48+
if errors:
49+
print("errors encountered while examining dependency groups:")
50+
for msg in errors:
51+
print(f" {msg}")
52+
sys.exit(1)
53+
else:
54+
print("ok")
55+
sys.exit(0)
56+
57+
58+
if __name__ == "__main__":
59+
main()

0 commit comments

Comments
 (0)