Skip to content

Commit

Permalink
feat: 'only' decorator set warning for builder restricts.
Browse files Browse the repository at this point in the history
  • Loading branch information
attakei committed Mar 16, 2024
1 parent 8c33618 commit aab83a4
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 2 deletions.
56 changes: 56 additions & 0 deletions src/atsphinx/helpers/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Helpful decorators."""

import functools
from typing import Callable, List, Optional, Union

from sphinx.application import Sphinx
from sphinx.util.logging import getLogger

Logger = getLogger(__name__)


def only(*, builders: Optional[List[str]] = None, formats: Optional[List[str]] = None):
"""Restict extension by builder types or formats.
This is decorator function.
You can message for users that this extension is created for specify builders.
.. code-block:: python
:caption: your_extension.py
:name: your_extension.py
# Display warning when user runs by not 'html' builders.
@only(builder=["html"])
def setup(app):
...
:params builders: List of builder names for restrict target.
:params formats: List of format types for restrict target.
"""
if builders is None and formats is None:
Logger.warning(
"To use @only, you should set argument builders or formats at least."
)

def _only(func: Callable[[Sphinx], Union[dict, None]]):
logger = getLogger(func.__module__ or "confpy")

def _restrict_builder(app: Sphinx):
target = func.__module__ or "setup() on conf.py"
if builders and app.builder.name not in builders:
logger.warning(
f"{target} is not supported '{app.builder.name}' builder."
)
if formats and app.builder.format not in formats:
logger.warning(
f"{target} is not supported '{app.builder.format}' format."
)

@functools.wraps(func)
def __only(app: Sphinx):
app.connect("builder-inited", _restrict_builder)
func(app)

return __only

return _only
7 changes: 7 additions & 0 deletions tests/test-root/conf.py
Original file line number Diff line number Diff line change
@@ -1 +1,8 @@
from atsphinx.helpers.decorators import only

extensions = []


@only(builders=["linkcheck"])
def setup(app):
pass
5 changes: 3 additions & 2 deletions tests/test_it.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@


@pytest.mark.sphinx("html")
def test__it(app: SphinxTestApp, status: StringIO, warning: StringIO):
"""Test to pass."""
def test__print_warning(app: SphinxTestApp, warning: StringIO):
app.build()
expected = "is not supported 'html' builder."
assert expected in warning.getvalue()

0 comments on commit aab83a4

Please sign in to comment.