Skip to content

Commit

Permalink
feat: helper to get dependency-groups
Browse files Browse the repository at this point in the history
Signed-off-by: Henry Schreiner <henryschreineriii@gmail.com>
  • Loading branch information
henryiii committed Oct 28, 2024
1 parent 5e02a64 commit 58834db
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 2 deletions.
80 changes: 78 additions & 2 deletions nox/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,21 @@
from pathlib import Path
from typing import TYPE_CHECKING

import packaging.requirements

if TYPE_CHECKING:
from typing import Any
from collections.abc import Generator
from typing import Any, TypeVar

T = TypeVar("T")

if sys.version_info < (3, 11):
import tomli as tomllib
else:
import tomllib


__all__ = ["load_toml"]
__all__ = ["load_toml", "dependency_groups"]


def __dir__() -> list[str]:
Expand Down Expand Up @@ -67,3 +72,74 @@ def _load_script_block(filepath: Path) -> dict[str, Any]:
for line in matches[0].group("content").splitlines(keepends=True)
)
return tomllib.loads(content)


def _normalize_name(name: str) -> str:
return re.sub(r"[-_.]+", "-", name).lower()


def _normalize_group_names(dependency_groups: dict[str, T]) -> dict[str, T]:
original_names: dict[str, list[str]] = {}
normalized_groups = {}

for group_name, value in dependency_groups.items():
normed_group_name = _normalize_name(group_name)
original_names.setdefault(normed_group_name, []).append(group_name)
normalized_groups[normed_group_name] = value

errors = []
for normed_name, names in original_names.items():
if len(names) > 1:
errors.append(f"{normed_name} ({', '.join(names)})")
if errors:
raise ValueError(f"Duplicate dependency group names: {', '.join(errors)}")

return normalized_groups


def _resolve_dependency_group(
dependency_groups: dict[str, Any], group: str, *past_groups: str
) -> Generator[str, None, None]:
if group in past_groups:
raise ValueError(f"Cyclic dependency group include: {group} -> {past_groups}")

if group not in dependency_groups:
raise LookupError(f"Dependency group '{group}' not found")

raw_group = dependency_groups[group]
if not isinstance(raw_group, list):
raise ValueError(f"Dependency group '{group}' is not a list")

for item in raw_group:
if isinstance(item, str):
# packaging.requirements.Requirement parsing ensures that this is a valid
# PEP 508 Dependency Specifier
# raises InvalidRequirement on failure
packaging.requirements.Requirement(item)
yield item
elif isinstance(item, dict):
if tuple(item.keys()) != ("include-group",):
raise ValueError(f"Invalid dependency group item: {item}")

include_group = _normalize_name(next(iter(item.values())))
yield from _resolve_dependency_group(
dependency_groups, include_group, *past_groups, group
)
else:
raise ValueError(f"Invalid dependency group item: {item}")


def _resolve(
dependency_groups: dict[str, Any], *groups: str
) -> Generator[str, None, None]:
if not isinstance(dependency_groups, dict):
raise TypeError("Dependency Groups table is not a dict")
for group in groups:
if not isinstance(group, str):
raise TypeError("Dependency group name is not a str")
yield from _resolve_dependency_group(dependency_groups, group)


def dependency_groups(pyproject: dict[str, Any], *groups: str) -> list[str]:
norm_groups = (_normalize_name(g) for g in groups)
return list(_resolve(pyproject["dependency-groups"], *norm_groups))
32 changes: 32 additions & 0 deletions tests/test_project.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import nox.project


def test_dependency_groups():
example = {
"dependency-groups": {
"test": ["pytest", "coverage"],
"docs": ["sphinx", "sphinx-rtd-theme"],
"typing": ["mypy", "types-requests"],
"typing-test": [
{"include-group": "typing"},
{"include-group": "test"},
"useful-types",
],
}
}

assert nox.project.dependency_groups(example, "test") == ["pytest", "coverage"]
assert nox.project.dependency_groups(example, "typing-test") == [
"mypy",
"types-requests",
"pytest",
"coverage",
"useful-types",
]
assert nox.project.dependency_groups(example, "typing_test") == [
"mypy",
"types-requests",
"pytest",
"coverage",
"useful-types",
]

0 comments on commit 58834db

Please sign in to comment.