reqexpand 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
reqexpand/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """Expand package extras without dropping PEP 508 environment markers."""
2
+
3
+ from reqexpand.expand import CycleError, combine_markers, expand_requirements
4
+ from reqexpand.pyproject import PyprojectError, expand_pyproject
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ __all__ = [
9
+ "CycleError",
10
+ "PyprojectError",
11
+ "__version__",
12
+ "combine_markers",
13
+ "expand_pyproject",
14
+ "expand_requirements",
15
+ ]
reqexpand/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from reqexpand.cli import main
2
+
3
+ raise SystemExit(main())
reqexpand/cli.py ADDED
@@ -0,0 +1,110 @@
1
+ """Command-line entry point for reqexpand."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from reqexpand import __version__
9
+ from reqexpand.expand import CycleError, expand_requirements
10
+ from reqexpand.pyproject import PyprojectError, expand_pyproject
11
+
12
+
13
+ def _parse_extras(parser: argparse.ArgumentParser, items: list[str]) -> dict[str, list[str]]:
14
+ extras: dict[str, list[str]] = {}
15
+ for item in items:
16
+ if "=" not in item:
17
+ parser.error(f"--extra must be NAME=REQUIREMENT, got {item!r}")
18
+ extra_name, requirement = item.split("=", 1)
19
+ extra_name = extra_name.strip()
20
+ requirement = requirement.strip()
21
+ if not extra_name or not requirement:
22
+ parser.error(f"--extra must be NAME=REQUIREMENT, got {item!r}")
23
+ extras.setdefault(extra_name, []).append(requirement)
24
+ return extras
25
+
26
+
27
+ def main(argv: list[str] | None = None) -> int:
28
+ parser = argparse.ArgumentParser(
29
+ prog="reqexpand",
30
+ description=(
31
+ "Expand extras of a local project into concrete requirements, "
32
+ "keeping PEP 508 environment markers."
33
+ ),
34
+ )
35
+ parser.add_argument("--version", action="version", version=f"reqexpand {__version__}")
36
+ parser.add_argument(
37
+ "--pyproject",
38
+ metavar="PATH",
39
+ help=(
40
+ "pyproject.toml, or a directory containing one; extras come from "
41
+ "[project.optional-dependencies] and --name defaults to [project].name"
42
+ ),
43
+ )
44
+ parser.add_argument(
45
+ "--name",
46
+ help="name of the local project whose extras should be expanded "
47
+ "(required unless --pyproject is given)",
48
+ )
49
+ parser.add_argument(
50
+ "--group",
51
+ metavar="NAME",
52
+ help=(
53
+ "expand a PEP 735 [dependency-groups] entry instead of "
54
+ "[project].dependencies (requires --pyproject)"
55
+ ),
56
+ )
57
+ parser.add_argument(
58
+ "--extra",
59
+ action="append",
60
+ default=[],
61
+ metavar="NAME=REQUIREMENT",
62
+ dest="extras",
63
+ help=(
64
+ "dependency of a local extra; pass once per requirement, "
65
+ "repeating the extra name to add more"
66
+ ),
67
+ )
68
+ parser.add_argument(
69
+ "requirements",
70
+ nargs="*",
71
+ help="requirement strings, for example 'my-app[win]; sys_platform == \"win32\"'",
72
+ )
73
+ args = parser.parse_args(argv)
74
+ extras = _parse_extras(parser, args.extras)
75
+
76
+ if args.group and args.pyproject is None:
77
+ parser.error("--group requires --pyproject")
78
+ if args.group and args.requirements:
79
+ parser.error("pass --group or requirement arguments, not both")
80
+
81
+ if args.pyproject is None:
82
+ if not args.name:
83
+ parser.error("--name is required unless --pyproject is given")
84
+ if not args.requirements:
85
+ parser.error("at least one requirement is required unless --pyproject is given")
86
+ try:
87
+ expanded = expand_requirements(args.requirements, extras, name=args.name)
88
+ except (CycleError, ValueError) as exc:
89
+ print(f"reqexpand: {exc}", file=sys.stderr)
90
+ return 1
91
+ else:
92
+ try:
93
+ expanded = expand_pyproject(
94
+ args.pyproject,
95
+ args.requirements or None,
96
+ extras=extras or None,
97
+ name=args.name,
98
+ group=args.group,
99
+ )
100
+ except (CycleError, PyprojectError, ValueError) as exc:
101
+ print(f"reqexpand: {exc}", file=sys.stderr)
102
+ return 1
103
+
104
+ for line in expanded:
105
+ print(line)
106
+ return 0
107
+
108
+
109
+ if __name__ == "__main__":
110
+ raise SystemExit(main())
reqexpand/expand.py ADDED
@@ -0,0 +1,171 @@
1
+ """Expand a local project's extras, combining PEP 508 markers with ``and``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Mapping, Sequence
7
+
8
+ from packaging.markers import Marker
9
+ from packaging.requirements import InvalidRequirement, Requirement
10
+ from packaging.utils import canonicalize_name
11
+
12
+ from reqexpand.extra_marker import resolve_extra
13
+
14
+ _EXTRA_SEP = re.compile(r"[-_.]+")
15
+
16
+
17
+ class CycleError(ValueError):
18
+ """Raised when an extra of the local project refers back to itself."""
19
+
20
+
21
+ def normalize_extra(name: str) -> str:
22
+ """Normalize an extra name (PEP 685: lowercase, ``[-_.]`` become ``-``)."""
23
+ return _EXTRA_SEP.sub("-", name.strip().lower())
24
+
25
+
26
+ def combine_markers(*markers: Marker | str | None) -> Marker | None:
27
+ """Return the conjunction of any non-empty markers, or ``None``.
28
+
29
+ Parts that already contain ``and`` or ``or`` are wrapped in parentheses
30
+ so a parent marker is not broken by a child, or the other way around.
31
+ """
32
+ parts: list[str] = []
33
+ for marker in markers:
34
+ if marker is None:
35
+ continue
36
+ text = str(marker).strip()
37
+ if not text:
38
+ continue
39
+ parts.append(_group(text))
40
+ if not parts:
41
+ return None
42
+ if len(parts) == 1:
43
+ return Marker(parts[0])
44
+ return Marker(" and ".join(parts))
45
+
46
+
47
+ def _group(text: str) -> str:
48
+ if _is_wrapped(text):
49
+ return text
50
+ padded = f" {text} "
51
+ if " and " in padded or " or " in padded:
52
+ return f"({text})"
53
+ return text
54
+
55
+
56
+ def _is_wrapped(text: str) -> bool:
57
+ if not (text.startswith("(") and text.endswith(")")):
58
+ return False
59
+ depth = 0
60
+ for index, char in enumerate(text):
61
+ if char == "(":
62
+ depth += 1
63
+ elif char == ")":
64
+ depth -= 1
65
+ if depth == 0:
66
+ return index == len(text) - 1
67
+ if depth < 0:
68
+ return False
69
+ return False
70
+
71
+
72
+ def expand_requirements(
73
+ requirements: Sequence[str],
74
+ extras: Mapping[str, Sequence[str]],
75
+ *,
76
+ name: str,
77
+ ) -> list[str]:
78
+ """Replace extras of *name* with their dependencies, keeping markers.
79
+
80
+ Only extras on requirements whose distribution name matches *name*
81
+ (PEP 503 normalization) are expanded. Other requirements are returned
82
+ unchanged and as written, including third-party extras such as
83
+ ``coverage[toml]``; so is an expanded dependency whose marker did not
84
+ have to change.
85
+ A version specifier or URL on an expanded requirement is dropped,
86
+ since the project is being replaced by its own dependencies. Exact
87
+ duplicates in the result are listed once.
88
+
89
+ The marker on a parent requirement is combined with each expanded
90
+ dependency's own marker using ``and``. Nested extras of *name* are
91
+ expanded too. A cycle raises :class:`CycleError`. An unknown extra
92
+ of *name* raises ``ValueError``.
93
+ """
94
+ project = canonicalize_name(name)
95
+ extra_map = {normalize_extra(key): list(value) for key, value in extras.items()}
96
+ expanded: list[str] = []
97
+ for raw in requirements:
98
+ for text in _expand_one(_parse(raw, "requirement"), raw, extra_map, project, ()):
99
+ if text not in expanded:
100
+ expanded.append(text)
101
+ return expanded
102
+
103
+
104
+ def _parse(raw: str, where: str) -> Requirement:
105
+ """Parse *raw*, naming the offending string and its place in errors."""
106
+ try:
107
+ return Requirement(raw)
108
+ except InvalidRequirement as exc:
109
+ reason = str(exc).splitlines()[0]
110
+ raise InvalidRequirement(f"invalid {where}: {raw!r} ({reason})") from None
111
+
112
+
113
+ _EXTRAS_CLAUSE = re.compile(r"\[([^\]]+)\]")
114
+
115
+
116
+ def _extras_in_declaration_order(req: Requirement, raw: str) -> list[str]:
117
+ """Prefer the order written in *raw*; packaging stores extras as a set."""
118
+ match = _EXTRAS_CLAUSE.search(raw)
119
+ if not match:
120
+ return list(req.extras)
121
+ declared = [part.strip() for part in match.group(1).split(",") if part.strip()]
122
+ wanted = {normalize_extra(extra) for extra in req.extras}
123
+ ordered = [extra for extra in declared if normalize_extra(extra) in wanted]
124
+ seen = {normalize_extra(extra) for extra in ordered}
125
+ ordered.extend(extra for extra in req.extras if normalize_extra(extra) not in seen)
126
+ return ordered
127
+
128
+
129
+ def _expand_one(
130
+ req: Requirement,
131
+ raw: str,
132
+ extra_map: Mapping[str, Sequence[str]],
133
+ project: str,
134
+ stack: tuple[str, ...],
135
+ changed: bool = False,
136
+ ) -> list[str]:
137
+ if canonicalize_name(req.name) != project or not req.extras:
138
+ # Keep the text as written unless its marker had to change.
139
+ return [_with_marker(req, raw) if changed else raw.strip()]
140
+ out: list[str] = []
141
+ for extra in _extras_in_declaration_order(req, raw):
142
+ key = normalize_extra(extra)
143
+ if key not in extra_map:
144
+ known = ", ".join(sorted(extra_map)) or "none"
145
+ raise ValueError(
146
+ f"unknown extra {extra!r} for project {project} (known extras: {known})"
147
+ )
148
+ if key in stack:
149
+ raise CycleError(f"cycle in extras: {' -> '.join((*stack, key))}")
150
+ for dep_str in extra_map[key]:
151
+ dep = _parse(dep_str, f"requirement in extra {key!r}")
152
+ settled = resolve_extra(dep.marker, key)
153
+ if settled is False:
154
+ continue
155
+ combined = combine_markers(req.marker, settled)
156
+ altered = _marker_text(combined) != _marker_text(dep.marker)
157
+ dep.marker = combined
158
+ out.extend(_expand_one(dep, dep_str, extra_map, project, (*stack, key), altered))
159
+ return out
160
+
161
+
162
+ def _with_marker(req: Requirement, raw: str) -> str:
163
+ """Write *req* with its current marker, keeping the rest of *raw* as written."""
164
+ if req.url is not None:
165
+ return str(req)
166
+ head = raw.split(";", 1)[0].strip()
167
+ return head if req.marker is None else f"{head}; {req.marker}"
168
+
169
+
170
+ def _marker_text(marker: Marker | None) -> str:
171
+ return "" if marker is None else str(marker)
@@ -0,0 +1,112 @@
1
+ """Resolve ``extra == "..."`` clauses once an extra has been selected.
2
+
3
+ A dependency listed under an extra often carries ``extra == "name"`` in its
4
+ marker, as in built wheel metadata. Once the extra is expanded into plain
5
+ requirements that clause would be evaluated without any extra and the
6
+ requirement would never install, so the clause is settled here: true for the
7
+ extra being expanded, false for any other.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Literal
13
+
14
+ from packaging.markers import Marker
15
+
16
+ # Truth value of a settled clause, or the text of one that is still open.
17
+ _Result = bool | str
18
+
19
+
20
+ def resolve_extra(marker: Marker | None, extra: str) -> Marker | Literal[False] | None:
21
+ """Settle ``extra`` clauses in *marker* for the selected *extra*.
22
+
23
+ Returns ``None`` when no condition is left, ``False`` when the marker
24
+ can never hold for this extra, and a ``Marker`` otherwise. Markers
25
+ without an ``extra`` clause are returned unchanged.
26
+ """
27
+ if marker is None or "extra" not in str(marker):
28
+ return marker
29
+ from reqexpand.expand import normalize_extra
30
+
31
+ result = _resolve(marker._markers, normalize_extra(extra))
32
+ if result is True:
33
+ return None
34
+ if result is False:
35
+ return False
36
+ assert isinstance(result, str)
37
+ return Marker(result)
38
+
39
+
40
+ def _resolve(items: list, extra: str) -> _Result:
41
+ groups: list[list[_Result]] = [[]]
42
+ for item in items:
43
+ if item == "or":
44
+ groups.append([])
45
+ elif item == "and":
46
+ continue
47
+ elif isinstance(item, list):
48
+ groups[-1].append(_resolve(item, extra))
49
+ else:
50
+ groups[-1].append(_atom(item, extra))
51
+ return _join_or([_join_and(group) for group in groups])
52
+
53
+
54
+ def _atom(clause: tuple, extra: str) -> _Result:
55
+ from reqexpand.expand import normalize_extra
56
+
57
+ lhs, op, rhs = clause
58
+ names = {type(lhs).__name__, type(rhs).__name__}
59
+ is_extra = "Variable" in names and "extra" in (
60
+ getattr(lhs, "value", None),
61
+ getattr(rhs, "value", None),
62
+ )
63
+ if is_extra and op.value in ("==", "!="):
64
+ value = rhs.value if type(lhs).__name__ == "Variable" else lhs.value
65
+ same = normalize_extra(value) == extra
66
+ return same if op.value == "==" else not same
67
+ return f"{_side(lhs)} {op.value} {_side(rhs)}"
68
+
69
+
70
+ def _side(part: object) -> str:
71
+ value = part.value # type: ignore[attr-defined]
72
+ if type(part).__name__ == "Variable":
73
+ return str(value)
74
+ return f"'{value}'" if '"' in value else f'"{value}"'
75
+
76
+
77
+ def _join_and(parts: list[_Result]) -> _Result:
78
+ if any(part is False for part in parts):
79
+ return False
80
+ open_parts = [part for part in parts if isinstance(part, str)]
81
+ if not open_parts:
82
+ return True
83
+ if len(open_parts) == 1:
84
+ return open_parts[0]
85
+ return " and ".join(f"({p})" if " or " in f" {p} " else p for p in open_parts)
86
+
87
+
88
+ def _join_or(parts: list[_Result]) -> _Result:
89
+ if any(part is True for part in parts):
90
+ return True
91
+ open_parts = [part for part in parts if isinstance(part, str)]
92
+ if not open_parts:
93
+ return False
94
+ return " or ".join(open_parts)
95
+
96
+
97
+ def settle_requirements(requirements: list[str], extra: str) -> list[str]:
98
+ """Apply :func:`resolve_extra` to each requirement listed under *extra*.
99
+
100
+ Requirements that can never hold for *extra* are dropped.
101
+ """
102
+ from packaging.requirements import Requirement
103
+
104
+ settled: list[str] = []
105
+ for text in requirements:
106
+ req = Requirement(text)
107
+ marker = resolve_extra(req.marker, extra)
108
+ if marker is False:
109
+ continue
110
+ req.marker = marker
111
+ settled.append(str(req))
112
+ return settled
@@ -0,0 +1,72 @@
1
+ """Hatch metadata hook that writes expanded requirements into project metadata.
2
+
3
+ Declare ``dependencies`` and ``optional-dependencies`` as dynamic and list
4
+ them under ``[tool.hatch.metadata.hooks.reqexpand]``. Requirements there may
5
+ name the project's own extras, and may pull in PEP 735 groups with
6
+ ``{include-group = "name"}``. The built metadata holds the flattened list,
7
+ with each parent marker combined into the requirements it replaced.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from collections.abc import Mapping
13
+ from pathlib import Path
14
+
15
+ from hatchling.metadata.plugin.interface import MetadataHookInterface
16
+ from hatchling.plugin import hookimpl
17
+
18
+ from reqexpand.expand import expand_requirements, normalize_extra
19
+ from reqexpand.extra_marker import settle_requirements
20
+ from reqexpand.pyproject import PyprojectError, load_pyproject, resolve_entries
21
+
22
+ _SECTION = "[tool.hatch.metadata.hooks.reqexpand]"
23
+
24
+
25
+ class ReqexpandMetadataHook(MetadataHookInterface):
26
+ PLUGIN_NAME = "reqexpand"
27
+
28
+ def update(self, metadata: dict) -> None:
29
+ data = load_pyproject(Path(self.root))
30
+ entries = self._entries("dependencies")
31
+ raw_extras = self._extras()
32
+ extras = {
33
+ normalize_extra(key): resolve_entries(
34
+ data, value, f"{_SECTION[:-1]}.optional-dependencies.{key}]"
35
+ )
36
+ for key, value in raw_extras.items()
37
+ }
38
+ name = metadata.get("name")
39
+ if not isinstance(name, str) or not name:
40
+ raise PyprojectError("pyproject.toml has no [project].name")
41
+ if entries is not None:
42
+ deps = resolve_entries(data, entries, f"{_SECTION[:-1]}.dependencies]")
43
+ metadata["dependencies"] = expand_requirements(deps, extras, name=name)
44
+ if raw_extras:
45
+ metadata["optional-dependencies"] = {
46
+ key: settle_requirements(
47
+ expand_requirements(extras[normalize_extra(key)], extras, name=name), key
48
+ )
49
+ for key in raw_extras
50
+ }
51
+
52
+ def _entries(self, key: str) -> list | None:
53
+ value = self.config.get(key)
54
+ if value is None:
55
+ return None
56
+ if not isinstance(value, list):
57
+ raise PyprojectError(f"{_SECTION[:-1]}.{key}] must be a list")
58
+ return value
59
+
60
+ def _extras(self) -> Mapping[str, list]:
61
+ value = self.config.get("optional-dependencies") or {}
62
+ if not isinstance(value, Mapping):
63
+ raise PyprojectError(f"{_SECTION[:-1]}.optional-dependencies] must be a table")
64
+ for key, items in value.items():
65
+ if not isinstance(items, list):
66
+ raise PyprojectError(f"{_SECTION[:-1]}.optional-dependencies.{key}] must be a list")
67
+ return value
68
+
69
+
70
+ @hookimpl
71
+ def hatch_register_metadata_hook() -> type[ReqexpandMetadataHook]:
72
+ return ReqexpandMetadataHook
reqexpand/py.typed ADDED
File without changes
reqexpand/pyproject.py ADDED
@@ -0,0 +1,184 @@
1
+ """Read extras and dependencies from a local pyproject.toml."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from collections.abc import Mapping, Sequence
7
+ from pathlib import Path
8
+
9
+ if sys.version_info >= (3, 11):
10
+ import tomllib
11
+ else:
12
+ import tomli as tomllib
13
+
14
+ from reqexpand.expand import CycleError, expand_requirements, normalize_extra
15
+
16
+
17
+ class PyprojectError(ValueError):
18
+ """Raised when a pyproject.toml is missing or not usable."""
19
+
20
+
21
+ def _open_pyproject(path: str | Path) -> Path:
22
+ location = Path(path)
23
+ if location.is_dir():
24
+ location = location / "pyproject.toml"
25
+ if not location.is_file():
26
+ raise PyprojectError(f"no pyproject.toml at {path}")
27
+ return location
28
+
29
+
30
+ def load_pyproject(path: str | Path) -> dict:
31
+ """Parse *path* (a file, or a directory containing pyproject.toml)."""
32
+ location = _open_pyproject(path)
33
+ try:
34
+ with location.open("rb") as handle:
35
+ return tomllib.load(handle)
36
+ except tomllib.TOMLDecodeError as exc:
37
+ raise PyprojectError(f"invalid TOML in {location}: {exc}") from exc
38
+
39
+
40
+ def project_name(data: Mapping) -> str:
41
+ name = data.get("project", {}).get("name") if isinstance(data.get("project"), Mapping) else None
42
+ if not name or not isinstance(name, str):
43
+ raise PyprojectError("pyproject.toml has no [project].name")
44
+ return name
45
+
46
+
47
+ def project_dependencies(data: Mapping) -> list[str]:
48
+ project = data.get("project")
49
+ if not isinstance(project, Mapping):
50
+ return []
51
+ deps = project.get("dependencies") or []
52
+ if not isinstance(deps, list) or not all(isinstance(item, str) for item in deps):
53
+ raise PyprojectError("[project.dependencies] must be a list of strings")
54
+ return list(deps)
55
+
56
+
57
+ def optional_dependencies(data: Mapping) -> dict[str, list[str]]:
58
+ project = data.get("project")
59
+ if not isinstance(project, Mapping):
60
+ return {}
61
+ extras = project.get("optional-dependencies") or {}
62
+ if not isinstance(extras, Mapping):
63
+ raise PyprojectError("[project.optional-dependencies] must be a table")
64
+ out: dict[str, list[str]] = {}
65
+ for key, value in extras.items():
66
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
67
+ raise PyprojectError(f"[project.optional-dependencies.{key}] must be a list of strings")
68
+ out[str(key)] = list(value)
69
+ return out
70
+
71
+
72
+ def merge_extras(
73
+ file_extras: Mapping[str, Sequence[str]],
74
+ explicit: Mapping[str, Sequence[str]] | None = None,
75
+ ) -> dict[str, list[str]]:
76
+ """Use extras from the file, then append any explicit extras of the same name."""
77
+ merged: dict[str, list[str]] = {
78
+ normalize_extra(key): list(value) for key, value in file_extras.items()
79
+ }
80
+ if not explicit:
81
+ return merged
82
+ for key, value in explicit.items():
83
+ merged.setdefault(normalize_extra(key), []).extend(value)
84
+ return merged
85
+
86
+
87
+ def dependency_groups(data: Mapping) -> dict[str, list]:
88
+ """Return the raw ``[dependency-groups]`` table, keyed by normalized name."""
89
+ raw = data.get("dependency-groups") or {}
90
+ if not isinstance(raw, Mapping):
91
+ raise PyprojectError("[dependency-groups] must be a table")
92
+ out: dict[str, list] = {}
93
+ for key, value in raw.items():
94
+ if not isinstance(value, list):
95
+ raise PyprojectError(f"[dependency-groups.{key}] must be a list")
96
+ out[normalize_extra(str(key))] = list(value)
97
+ return out
98
+
99
+
100
+ def resolve_dependency_group(
101
+ data: Mapping,
102
+ name: str,
103
+ _stack: tuple[str, ...] = (),
104
+ ) -> list[str]:
105
+ """Flatten a PEP 735 dependency group, following ``include-group`` entries.
106
+
107
+ A cycle raises :class:`CycleError`. Unknown groups and malformed
108
+ entries raise :class:`PyprojectError`.
109
+ """
110
+ groups = dependency_groups(data)
111
+ key = normalize_extra(name)
112
+ if key not in groups:
113
+ known = ", ".join(sorted(groups)) or "none"
114
+ raise PyprojectError(f"unknown dependency group {name!r} (known groups: {known})")
115
+ if key in _stack:
116
+ raise CycleError(f"cycle in dependency groups: {' -> '.join((*_stack, key))}")
117
+ return resolve_entries(data, groups[key], f"[dependency-groups.{name}]", (*_stack, key))
118
+
119
+
120
+ def resolve_entries(
121
+ data: Mapping,
122
+ entries: Sequence,
123
+ label: str,
124
+ stack: tuple[str, ...] = (),
125
+ ) -> list[str]:
126
+ """Flatten requirement strings and ``{include-group = ...}`` tables.
127
+
128
+ *label* names the list in error messages. *stack* holds the groups
129
+ being resolved, so that a cycle can be reported.
130
+ """
131
+ resolved: list[str] = []
132
+ for index, item in enumerate(entries):
133
+ if isinstance(item, str):
134
+ resolved.append(item)
135
+ continue
136
+ if isinstance(item, Mapping) and set(item.keys()) == {"include-group"}:
137
+ included = item["include-group"]
138
+ if not isinstance(included, str) or not included.strip():
139
+ raise PyprojectError(f"{label}[{index}].include-group must be a group name")
140
+ resolved.extend(resolve_dependency_group(data, included, stack))
141
+ continue
142
+ raise PyprojectError(
143
+ f'{label}[{index}] must be a requirement string or a table {{include-group = "..."}}'
144
+ )
145
+ return resolved
146
+
147
+
148
+ def expand_pyproject(
149
+ path: str | Path,
150
+ requirements: Sequence[str] | None = None,
151
+ *,
152
+ extras: Mapping[str, Sequence[str]] | None = None,
153
+ name: str | None = None,
154
+ group: str | None = None,
155
+ ) -> list[str]:
156
+ """Expand requirements using extras declared in *path*.
157
+
158
+ *name* defaults to ``[project].name``; a file with no ``[project]``
159
+ table has no local extras, so *name* is not needed there. *requirements* defaults to
160
+ ``[project].dependencies``, or to the named PEP 735 dependency
161
+ group when *group* is set. *requirements* and *group* cannot both
162
+ be passed. Explicit *extras* are appended to
163
+ ``[project.optional-dependencies]`` of the same name; the existing
164
+ ``expand_requirements`` mapping is otherwise unchanged.
165
+ """
166
+ data = load_pyproject(path)
167
+ if name is not None:
168
+ project = name
169
+ elif "project" in data:
170
+ project = project_name(data)
171
+ else:
172
+ # A file with only [dependency-groups] has no local project, so
173
+ # there are no extras to expand and any name will do.
174
+ project = ""
175
+ if group is not None and requirements is not None:
176
+ raise PyprojectError("pass requirements or group, not both")
177
+ if group is not None:
178
+ reqs = resolve_dependency_group(data, group)
179
+ elif requirements is not None:
180
+ reqs = list(requirements)
181
+ else:
182
+ reqs = project_dependencies(data)
183
+ mapping = merge_extras(optional_dependencies(data), extras)
184
+ return expand_requirements(reqs, mapping, name=project)
@@ -0,0 +1,265 @@
1
+ Metadata-Version: 2.5
2
+ Name: reqexpand
3
+ Version: 0.1.0
4
+ Summary: Expand package extras without dropping PEP 508 environment markers.
5
+ Project-URL: Homepage, https://github.com/driftwright/reqexpand
6
+ Project-URL: Issues, https://github.com/driftwright/reqexpand/issues
7
+ Project-URL: Changelog, https://github.com/driftwright/reqexpand/blob/main/CHANGELOG.md
8
+ Author: driftwright
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: extras,markers,packaging,pep508,requirements
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: Hatch
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Build Tools
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: packaging>=23
25
+ Requires-Dist: tomli>=2; python_version < '3.11'
26
+ Provides-Extra: dev
27
+ Requires-Dist: build>=1; extra == 'dev'
28
+ Requires-Dist: hatchling>=1.18; extra == 'dev'
29
+ Requires-Dist: mypy>=1.10; extra == 'dev'
30
+ Requires-Dist: pytest>=7; extra == 'dev'
31
+ Requires-Dist: ruff==0.17.6; extra == 'dev'
32
+ Requires-Dist: tomli>=2; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # reqexpand
36
+
37
+ Expand a local project's extras into concrete requirements without dropping
38
+ PEP 508 environment markers.
39
+
40
+ A requirement such as `my-app[win]; sys_platform == "win32"` often loses that
41
+ marker when a tool substitutes the `win` extra's dependencies. reqexpand
42
+ replaces extras of the named project with those dependencies and combines
43
+ the parent marker with each dependency's own marker using `and`. Third-party
44
+ extras such as `coverage[toml]` are left alone.
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install reqexpand
50
+ ```
51
+
52
+ The package is not on PyPI yet; install from a clone:
53
+
54
+ ```bash
55
+ pip install -e ".[dev]"
56
+ ```
57
+
58
+ ## Library
59
+
60
+ ```python
61
+ from reqexpand import expand_requirements
62
+
63
+ expand_requirements(
64
+ ["my-app[win]; sys_platform == 'win32'"],
65
+ extras={"win": ["pywin32>=306"]},
66
+ name="my-app",
67
+ )
68
+ # ['pywin32>=306; sys_platform == "win32"']
69
+
70
+ expand_requirements(
71
+ ["my-app[win]; sys_platform == 'win32'"],
72
+ extras={"win": ['pywin32>=306; python_version >= "3.10"']},
73
+ name="my-app",
74
+ )
75
+ # ['pywin32>=306; sys_platform == "win32" and python_version >= "3.10"']
76
+ ```
77
+
78
+ A dependency listed under an extra may carry its own `extra == "..."`
79
+ clause, as it does in built wheel metadata. Once the extra is expanded into
80
+ plain requirements that clause would be evaluated with no extra and the
81
+ requirement would never install, so it is settled first: `x; extra == "a"`
82
+ under extra `a` becomes `x`, `x; extra == "a" and os_name == "nt"` becomes
83
+ `x; os_name == "nt"`, and a dependency tied to a different extra is left out.
84
+
85
+ `name` is the local project. Only extras on requirements of that project
86
+ (after PEP 503 name normalization) are expanded. Nested extras are expanded
87
+ too; a cycle raises `CycleError`, and an unknown extra raises `ValueError`.
88
+
89
+ To take extras from the project's `pyproject.toml` instead of passing the
90
+ mapping by hand:
91
+
92
+ ```python
93
+ from reqexpand import expand_pyproject
94
+
95
+ # uses [project].name, [project].dependencies, and
96
+ # [project.optional-dependencies]
97
+ expand_pyproject("pyproject.toml")
98
+
99
+ # explicit requirements, extras from the file
100
+ expand_pyproject("pyproject.toml", ["my-app[win]; sys_platform == 'win32'"])
101
+ ```
102
+
103
+ `expand_pyproject` also accepts a directory that contains `pyproject.toml`.
104
+ Pass `extras=` to append more dependencies to the extras declared in the
105
+ file, and `name=` to override `[project].name`. The original
106
+ `expand_requirements` API is unchanged.
107
+
108
+ ## Command line
109
+
110
+ ```bash
111
+ reqexpand --name my-app --extra 'win=pywin32>=306' \
112
+ 'my-app[win]; sys_platform == "win32"'
113
+ # pywin32>=306; sys_platform == "win32"
114
+ ```
115
+
116
+ Pass `--extra NAME=REQUIREMENT` once per dependency. Repeating the extra
117
+ name appends another dependency.
118
+
119
+ Read extras and, unless you pass requirements yourself, `[project].dependencies`
120
+ from a `pyproject.toml`:
121
+
122
+ ```bash
123
+ reqexpand --pyproject pyproject.toml
124
+ reqexpand --pyproject . 'my-app[win]; sys_platform == "win32"'
125
+ ```
126
+
127
+ `--name` defaults to `[project].name` when `--pyproject` is used. `--extra`
128
+ still works and is appended to the extras from the file.
129
+
130
+ PEP 735 dependency groups in the same file can be expanded instead of
131
+ `[project].dependencies`. Local extras inside a group are still expanded,
132
+ and `{include-group = "..."}` entries are followed. A cycle raises
133
+ `CycleError`.
134
+
135
+ ```python
136
+ expand_pyproject("pyproject.toml", group="dev")
137
+ ```
138
+
139
+ ```bash
140
+ reqexpand --pyproject pyproject.toml --group dev
141
+ ```
142
+
143
+ `--group` cannot be combined with requirement arguments. A file that has
144
+ only `[dependency-groups]` and no `[project]` table works too; there are no
145
+ local extras to expand, so `--name` is not needed.
146
+
147
+ ## Examples
148
+
149
+ The first two start from this `pyproject.toml`:
150
+
151
+ ```toml
152
+ [project]
153
+ name = "my-app"
154
+ version = "1.0"
155
+ dependencies = ["click>=8", "my-app[win]; sys_platform == 'win32'"]
156
+
157
+ [project.optional-dependencies]
158
+ win = ["pywin32>=306", "colorama; python_version < '3.12'"]
159
+ docs = ["sphinx>=7"]
160
+ all = ["my-app[win,docs]"]
161
+
162
+ [dependency-groups]
163
+ test = ["pytest>=7", "my-app[docs]", "coverage[toml]"]
164
+ lint = ["ruff"]
165
+ ci = [{ include-group = "test" }, { include-group = "lint" }]
166
+ ```
167
+
168
+ **Extras.** The project's own dependencies, with the `win` extra replaced and
169
+ its marker kept and combined with the extra's own:
170
+
171
+ ```console
172
+ $ reqexpand --pyproject .
173
+ click>=8
174
+ pywin32>=306; sys_platform == "win32"
175
+ colorama; sys_platform == "win32" and python_version < "3.12"
176
+ ```
177
+
178
+ Pass a requirement to expand just that one:
179
+
180
+ ```console
181
+ $ reqexpand --pyproject . 'my-app[all]'
182
+ pywin32>=306
183
+ colorama; python_version < '3.12'
184
+ sphinx>=7
185
+ ```
186
+
187
+ Requirements that need no change are printed exactly as written (note the
188
+ single quotes above, copied from `pyproject.toml`). Only a requirement whose
189
+ marker had to be combined is rewritten, and then only its marker.
190
+
191
+ **Dependency groups.** Flatten a group for a CI job. `include-group` is
192
+ followed, the project's `docs` extra is expanded, and `coverage[toml]`
193
+ is a third-party extra, so it is left as it is:
194
+
195
+ ```console
196
+ $ reqexpand --pyproject . --group ci > requirements-ci.txt
197
+ $ cat requirements-ci.txt
198
+ pytest>=7
199
+ sphinx>=7
200
+ coverage[toml]
201
+ ruff
202
+ $ pip install -r requirements-ci.txt
203
+ ```
204
+
205
+ **Hatch.** Move `dependencies` and the extras into the hook table described
206
+ in the next section (and list both as `dynamic`), and the built wheel carries
207
+ no `my-app[...]` requirement:
208
+
209
+ ```text
210
+ Requires-Dist: click>=8
211
+ Requires-Dist: colorama; sys_platform == 'win32' and python_version < '3.12'
212
+ Requires-Dist: pywin32>=306; sys_platform == 'win32'
213
+ Provides-Extra: all
214
+ Requires-Dist: colorama; (python_version < '3.12') and extra == 'all'
215
+ Requires-Dist: pywin32>=306; extra == 'all'
216
+ Requires-Dist: sphinx>=7; extra == 'all'
217
+ ```
218
+
219
+ ## Hatch
220
+
221
+ A Hatch metadata hook can write the expanded lists into the built
222
+ metadata, so a wheel never contains a self-referencing requirement such as
223
+ `my-app[win]`. Make the fields dynamic and describe them under the hook
224
+ table:
225
+
226
+ ```toml
227
+ [build-system]
228
+ requires = ["hatchling", "reqexpand"]
229
+ build-backend = "hatchling.build"
230
+
231
+ [project]
232
+ name = "my-app"
233
+ dynamic = ["dependencies", "optional-dependencies"]
234
+
235
+ [dependency-groups]
236
+ runtime = ["attrs>=23", "colorama; sys_platform == 'win32'"]
237
+
238
+ [tool.hatch.metadata.hooks.reqexpand]
239
+ dependencies = [{ include-group = "runtime" }]
240
+
241
+ [tool.hatch.metadata.hooks.reqexpand.optional-dependencies]
242
+ win = ["pywin32>=306; sys_platform == 'win32'"]
243
+ all = ["my-app[win]", { include-group = "runtime" }]
244
+ ```
245
+
246
+ Hatch requires a field to be either static or dynamic, so the lists live in
247
+ the hook table, not in `[project]`. Entries may name the project's own
248
+ extras and may use `{include-group = "..."}` to pull in a PEP 735 group
249
+ from `[dependency-groups]`. Parent markers are combined with each
250
+ replaced requirement's marker as described above. If `dependencies` is
251
+ left out of the hook table, it is not touched. An `extra == "..."` clause on
252
+ an extra's own requirement is dropped, since Hatch adds that clause itself,
253
+ and a requirement tied to a different extra is left out of this one. Unknown extras, unknown
254
+ groups, and cycles fail the build with the same errors as the library.
255
+
256
+ ## Tests
257
+
258
+ ```bash
259
+ pip install -e ".[dev]"
260
+ pytest
261
+ ```
262
+
263
+ ## License
264
+
265
+ MIT
@@ -0,0 +1,13 @@
1
+ reqexpand/__init__.py,sha256=uz3EOaYCjrdIMYV8SjSJ8x_5cZiwCfq2pL_3gfGWF5M,389
2
+ reqexpand/__main__.py,sha256=vgLYeTDbhLh-Gfelud2YenUh0NDJdbj68d2YCAnrBJ8,57
3
+ reqexpand/cli.py,sha256=mxho7plpZNCh9a3AHjGfnAXMbysRW3YXRaHNAUSG0aE,3672
4
+ reqexpand/expand.py,sha256=uqy9DjKFvcZMM0arYXVhavCwwzNxLWK5jXHPpOJgALk,6010
5
+ reqexpand/extra_marker.py,sha256=JH_anvMr7RibDY5-29_2rb_xcV0D--iAVRRVlRudU2M,3725
6
+ reqexpand/hatch_plugin.py,sha256=iYp6xqeeNot9lSQ1qeeBwXJqMUGs7SGl-2-IWON1fso,2864
7
+ reqexpand/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ reqexpand/pyproject.py,sha256=v-KOwFGWquZvDEUPa8GVb9-qj2eNovl4l_Awv47jK6U,6794
9
+ reqexpand-0.1.0.dist-info/METADATA,sha256=XAY8k32AE4Bo2OhgtyIAqRfQgLKZBVpK18KD7tYSyCY,8487
10
+ reqexpand-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
11
+ reqexpand-0.1.0.dist-info/entry_points.txt,sha256=Fi0_-Pmdp4JiyQSSKkgF98eO3EElCHqRs4AjmTl_tWA,93
12
+ reqexpand-0.1.0.dist-info/licenses/LICENSE,sha256=swBJDfN2CS-z8FZlsThHsALLeq9aHDfXh5G4Up7gvhc,1068
13
+ reqexpand-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,5 @@
1
+ [console_scripts]
2
+ reqexpand = reqexpand.cli:main
3
+
4
+ [hatch]
5
+ reqexpand = reqexpand.hatch_plugin
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 driftwright
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING WITHOUT LIMITATION THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.