Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add a poetry-specific parser, and a mechanism for selecting it. #33

Merged
merged 5 commits into from
Aug 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions doc-source/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ By passing :func:`globalns=globals() <globals>` to the class constructor, the ke
This will prevent warnings from linters etc., but is not necessary for Sphinx to see the configuration.


.. note::

At time of writing the "Poetry" tool does not support PEP 621. To enable a mode compatible with
the ``[tool.poetry]`` heading supply the argument ``style="poetry"``. For example:

.. code-block:: python

config = SphinxConfig("../pyproject.toml", style="poetry")


Configuration
----------------

Expand Down
81 changes: 76 additions & 5 deletions sphinx_pyproject/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#

# stdlib
import re
from typing import Any, Dict, Iterator, List, Mapping, MutableMapping, Optional

# 3rd party
Expand All @@ -43,7 +44,7 @@
__version__: str = "0.1.0"
__email__: str = "dominic@davis-foster.co.uk"

__all__ = ["SphinxConfig", "ProjectParser"]
__all__ = ["SphinxConfig", "ProjectParser", "PoetryProjectParser"]


class SphinxConfig(Mapping[str, Any]):
Expand All @@ -55,6 +56,9 @@ class SphinxConfig(Mapping[str, Any]):
The variables parsed from the ``[tool.sphinx-pyproject]`` table will be added to this namespace.
By default, or if explicitly :py:obj:`None`, this does not happen.
:no-default globalns:
:param style: Either ``pep621`` (default), or ``poetry`` to read configuration from the ``[tool.poetry]`` table.
:no-default style:


.. autosummary-widths:: 1/4
"""
Expand Down Expand Up @@ -122,15 +126,19 @@ def __init__(
pyproject_file: PathLike = "../pyproject.toml",
*,
globalns: Optional[MutableMapping] = None,
style: str = "pep621",
):

pyproject_file = PathPlus(pyproject_file).abspath()
config = dom_toml.load(pyproject_file, decoder=TomlPureDecoder)

if "project" not in config:
raise BadConfigError(f"No 'project' table found in {pyproject_file.as_posix()}")
parser_cls = project_parser_styles.get(style)
if parser_cls is None:
styles = ", ".join(project_parser_styles)
raise ValueError(f"'style' argument must be one of: {styles}")

pep621_config = ProjectParser().parse(config["project"])
namespace = parser_cls.get_namespace(pyproject_file, config)
pep621_config = parser_cls().parse(namespace)

for key in ("name", "version", "description"):
if key not in pep621_config:
Expand Down Expand Up @@ -191,6 +199,22 @@ class ProjectParser(AbstractConfigParser):
.. autosummary-widths:: 7/16
"""

@staticmethod
def get_namespace(filename: PathPlus, config: Dict[str, TOML_TYPES]) -> Dict[str, TOML_TYPES]:
"""
Returns the ``[project]`` table in a ``project.toml`` file.

:param filename: The filename the TOML data was read from. Used in error messages.
:param config: The data from the TOML file.

.. versionadded:: 0.2.0
"""

if "project" not in config:
raise BadConfigError(f"No 'project' table found in {filename.as_posix()}")

return config["project"]

def parse_name(self, config: Dict[str, TOML_TYPES]) -> str:
"""
Parse the :pep621:`name` key.
Expand Down Expand Up @@ -273,10 +297,57 @@ def parse(
:param config:
:param set_defaults: Has no effect in this class.
"""

if "authors" in config:
config["author"] = config.pop("authors")
elif "maintainers" in config:
config["author"] = config.pop("maintainers")

return super().parse(config)


class PoetryProjectParser(ProjectParser):
"""
Parser for poetry metadata from ``pyproject.toml``.

.. versionadded:: 0.2.0
"""

@staticmethod
def get_namespace(filename: PathPlus, config: Dict[str, TOML_TYPES]) -> Dict[str, TOML_TYPES]:
"""
Returns the ``[tool.poetry]`` table in a ``project.toml`` file.

:param filename: The filename the TOML data was read from. Used in error messages.
:param config: The data from the TOML file.
"""

result = config.get("tool", {}).get("poetry")
if result is None:
raise BadConfigError(f"No 'tool.poetry' table found in {filename.as_posix()}")

return result

@staticmethod
def parse_author(config: Dict[str, TOML_TYPES]) -> str:
"""
Parse poetry's authors key.

:param config: The unparsed TOML config for the ``[tool.poetry]`` table.
"""

pep621_style_authors: List[Dict[str, str]] = []

for author in config["author"]:
match = re.match(r"(?P<name>.*)<(?P<email>.*)>", author)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I originally implemented this as a straight-copy of the base class's parse_author. The implementation used a simpler string splitting mechanism to just pull out the name, which is the required field for "author", iirc.

But given the 100% coverage requirement, I wanted to get reuse out of the preexisting test that handles lack of any authors at all, so it felt perhaps better to redirect back to the base class's implementation ultimately.

But I could just as easily add a test and have the simpler impl here.

if match:
name = match.group("name").strip()
email = match.group("email").strip()
pep621_style_authors.append({"name": name, "email": email})

return ProjectParser.parse_author({"author": pep621_style_authors})


project_parser_styles = {
"pep621": ProjectParser,
"poetry": PoetryProjectParser,
}
55 changes: 55 additions & 0 deletions tests/test_sphinx_pyproject.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# stdlib
import textwrap
from typing import Any, Dict

# 3rd party
Expand Down Expand Up @@ -153,3 +154,57 @@ def test_missing_keys(tmp_pathplus: PathPlus, config: str):

with pytest.raises(BadConfigError, match=err):
SphinxConfig(tmp_pathplus / "pyproject.toml")


POETRY_AUTHORS = """
[tool.poetry]
name = 'foo'
version = '1.2.3'
description = 'desc'
authors = ["Person <example@email.com>"]
"""

POETRY_MAINTAINERS = """
[tool.poetry]
name = 'foo'
version = '1.2.3'
description = 'desc'
maintainers = ["Person <example@email.com>"]
"""


@pytest.mark.parametrize(
"toml", [
pytest.param(POETRY_AUTHORS, id="authors"),
pytest.param(POETRY_MAINTAINERS, id="maintainers"),
]
)
def test_poetry(tmp_pathplus: PathPlus, toml: str):
(tmp_pathplus / "pyproject.toml").write_text(toml)

config = SphinxConfig(tmp_pathplus / "pyproject.toml", style="poetry")
assert config.name == "foo"
assert config.version == "1.2.3"
assert config.author == "Person"
assert config.description == "desc"


def test_poetry_missing_heading(tmp_pathplus: PathPlus):
toml = textwrap.dedent("""
[other.table]
name = 'foo'
""")

(tmp_pathplus / "pyproject.toml").write_text(toml)

err = "No 'tool.poetry' table found in"
with pytest.raises(BadConfigError, match=err):
SphinxConfig(tmp_pathplus / "pyproject.toml", style="poetry")


def test_invalid_style(tmp_pathplus: PathPlus):
(tmp_pathplus / "pyproject.toml").write_text('')

err = "'style' argument must be one of: pep621, poetry"
with pytest.raises(ValueError, match=err):
SphinxConfig(tmp_pathplus / "pyproject.toml", style="other")
1 change: 1 addition & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ plugins = coverage_pyver_pragma

[coverage:report]
fail_under = 100
show_missing = true
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was having trouble figuring out which lines were missing coverage, given the requirement that it be 100% coverage.

exclude_lines =
raise AssertionError
raise NotImplementedError
Expand Down
Loading