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

refactor: Split a sphinxnotes.jinja extension #44

Draft
wants to merge 8 commits into
base: v3
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion docs/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ help:
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) -v
3 changes: 2 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@
autoclass_content = 'init'
autodoc_typehints = 'description'

extensions.append('sphinx.ext.intersphinx')
# extensions.append('sphinx.ext.intersphinx')
intersphinx_mapping = {
'python': ('https://docs.python.org/3', None),
'sphinx': ('https://www.sphinx-doc.org/en/master', None),
Expand All @@ -111,6 +111,7 @@
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../src/sphinxnotes'))
extensions.append('any')
extensions.append('jinja')

#
# DOG FOOD CONFIGURATION START
Expand Down
102 changes: 21 additions & 81 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,92 +5,32 @@
sphinxnotes-any
===============

.. |docs| image:: https://img.shields.io/github/deployments/sphinx-notes/any/github-pages
:target: https://sphinx.silverrainz.me/any
:alt: Documentation Status
Role:

.. |license| image:: https://img.shields.io/github/license/sphinx-notes/any
:target: https://github.com/sphinx-notes/any/blob/master/LICENSE
:alt: Open Source License
:rrr:`Hey!`

.. |pypi| image:: https://img.shields.io/pypi/v/sphinxnotes-any.svg
:target: https://pypi.python.org/pypi/sphinxnotes-any
:alt: PyPI Package

.. |download| image:: https://img.shields.io/pypi/dm/sphinxnotes-any
:target: https://pypi.python.org/pypi/sphinxnotes-any
:alt: PyPI Package Downloads
Directive:

|docs| |license| |pypi| |download|

Introduction
============
.. ddd:: Hey!

.. INTRODUCTION START
I am here.

The extension provides a domain which allows user creates directive and roles
to descibe, reference and index arbitrary object in documentation.
It is a bit like :py:meth:`sphinx.application.Sphinx.add_object_type`,
but more powerful.
.. autoclass:: jinja.context.NodeAdapter
:members:

.. INTRODUCTION END
.. template:: git
:extra: env app json:xxx.json

Getting Started
===============

.. note::

We assume you already have a Sphinx documentation,
if not, see `Getting Started with Sphinx`_.

First, downloading extension from PyPI:

.. code-block:: console

$ pip install sphinxnotes-any

Then, add the extension name to ``extensions`` configuration item in your
:parsed_literal:`conf.py_`:

.. code-block:: python

extensions = [
# …
'sphinxnotes.any',
# …
]

.. _Getting Started with Sphinx: https://www.sphinx-doc.org/en/master/usage/quickstart.html
.. _conf.py: https://www.sphinx-doc.org/en/master/usage/configuration.html

.. ADDITIONAL CONTENT START

See :doc:`usage` and :doc:`conf` for more details.

.. ADDITIONAL CONTENT END

Contents
========

.. toctree::
:caption: Contents

usage
conf
tips
changelog

The Sphinx Notes Project
========================

The project is developed by `Shengyu Zhang`__,
as part of **The Sphinx Notes Project**.

.. toctree::
:caption: The Sphinx Notes Project

Home <https://sphinx.silverrainz.me/>
Blog <https://silverrainz.me/blog/category/sphinx.html>
PyPI <https://pypi.org/search/?q=sphinxnotes>

__ https://github.com/SilverRainZ
{% for r in revisions %}
:{{ r.date | strftime }}:
{% if r.modification %}
- 修改了 {{ r.modification | roles("doc") | join("、") }}
{% endif %}
{% if r.addition %}
- 新增了 {{ r.addition | roles("doc") | join("、") }}
{% endif %}
{% if r.deletion %}
- 删除了 {{ r.deletion | join("、") }}
{% endif %}
{% endfor %}
21 changes: 21 additions & 0 deletions src/sphinxnotes/jinja/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""
sphinxnotes.jinja
~~~~~~~~~~~~~~~~~

Sphinx extension entrypoint of sphinxnotes-jinja.

:copyright: Copyright 2024 Shengyu Zhang
:license: BSD, see LICENSE for details.
"""

from importlib.metadata import version
from sphinx.application import Sphinx
from .context import ContextRole, ContextDirective

def setup(app: Sphinx):
"""Sphinx extension entrypoint."""

app.add_role('rrr', ContextRole.derive('rrr')())
app.add_directive('ddd', ContextDirective.derive('ddd', required_arguments=1, has_content=True))

return {}
136 changes: 136 additions & 0 deletions src/sphinxnotes/jinja/context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
"""
sphinxnotes.jinja.context
~~~~~~~~~~~~~~~~~~~~~~~~~

Build :cls:`jinja2.runtime.Context` from reStructuredText.

context:

- env: Sphinx env
- doc: Current documentation
doc.docname
doc.section.title
- node: next, prev
- self $.name

:copyright: Copyright 2024 Shengyu Zhang
:license: BSD, see LICENSE for details.
"""

from __future__ import annotations
from typing import Any, TYPE_CHECKING
from abc import ABC, abstractmethod

from docutils import nodes
from sphinx.util.docutils import SphinxDirective, SphinxRole
from sphinx.util import logging

if TYPE_CHECKING:
from sphinx.application import Sphinx
from sphinx.environment import BuildEnvironment


logger = logging.getLogger(__name__)

class ContextGenerator(ABC):
@abstractmethod
def gen(self) -> dict[str, Any]:
raise NotImplementedError()

_registry: dict[str, ContextGenerator] = {}

class SphinxContext(ContextGenerator):
_env: BuildEnvironment

def __init__(self, env: BuildEnvironment):
self._env = env

def gen(self) -> dict[str, Any]:
return {
'app': self._env.app,
'env': self._env,
'cfg': self._env.config,
'builder': self._env.app.builder,
}

class DocContext(ContextGenerator):
_node: nodes.Node

def __init__(self, node: nodes.Node):
self._node = node

def gen(self) -> dict[str, Any]:
return {
'root': self._node.document,
'section': self._node.next_node(nodes.section,include_self=False, descend=False,
siblings=False, ascend=False)
}

class SourceContext(ContextGenerator):
_markup: SphinxDirective | SphinxRole

def __init__(self, markup: SphinxDirective | SphinxRole):
self._markup = markup

def gen(self) -> dict[str, Any]:
if isinstance(self._markup, SphinxDirective):
rawtext = self._markup.block_text
elif isinstance(self._markup, SphinxRole):
rawtext = self._markup.rawtext
else:
raise ValueError()

source, lineno = self._markup.get_source_info()
return {
'name': self._markup.name,
'rawtext': rawtext,
'source': source,
'lineno': lineno,
}


class DirectiveContext(ContextGenerator):
_dir: SphinxDirective

def __init__(self, dir: SphinxDirective):
self._dir = dir

def gen(self) -> dict[str, Any]:
ctx: dict[str,Any] = {
'opts': {},
}
if self._dir.required_arguments + self._dir.optional_arguments != 0:
ctx['args'] = self._dir.arguments
if self._dir.has_content:
ctx['content'] = self._dir.content # TODO: StringList
for key in self._dir.option_spec or {}:
ctx['opts'][key] = self._dir.options.get(key)
return ctx


class RoleContext(ContextGenerator):
_role: SphinxRole

def __init__(self, role: SphinxRole):
self._role = role

def gen(self) -> dict[str, Any]:
return {
'content': self._role.text,
}

def _load_single_ctx(env: BuildEnvironment, ctxname: str) -> dict[str, Any]:
if ctxname == 'sphinx':
return SphinxContext(env).gen()
elif ctxname == 'doc':
return DocContext(env).gen()


def load_and_fuse(
buildenv: BuildEnvironment,
fuse_ctxs: list[str],
separate_ctxs: list[str],
allow_duplicate: bool = False) -> dict[str, Any]:



61 changes: 61 additions & 0 deletions src/sphinxnotes/jinja/directives.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
from typing import Type, Callable, Any

from docutils.nodes import Node
from docutils.parsers.rst import directives
from sphinx.util.docutils import SphinxDirective

from . import template

class ContextDirective(SphinxDirective):
@classmethod
def derive(cls,
directive_name: str,
required_arguments: int = 0,
optional_arguments: int = 0,
final_argument_whitespace: bool = False,
option_spec: list[str] | dict[str, Callable[[str], Any]] = {},
has_content: bool = False) -> Type['ContextDirective']:
"""Generate directive class."""

# If no conversion function provided in option_spec, fallback to directive.unchanged.
if isinstance(option_spec, list):
option_spec = {k: directives.unchanged for k in option_spec}

return type(
directive_name.title() + 'ContextDirective',
(ContextDirective,),
{
# Member of docutils.parsers.rst.Directive.
'required_arguments': required_arguments,
'optional_arguments': optional_arguments,
'final_argument_whitespace': final_argument_whitespace,
'option_spec': option_spec,
'has_content': has_content,
},
)


def run(self) -> list[Node]:
ctx = {}
text = template.render(self, ctx)

return self.parse_text_to_nodes(text, allow_section_headings=True)


class TemplateDirective(SphinxDirective):
required_arguments = 0
optional_arguments = 10
final_argument_whitespace = False
option_spec = {}
has_content = True

def run(self) -> list[nodes.Node]:
ctx = {}
for ctxname in self.arguments:
ctx = {
ctxname: context.load(ctxname)
}

text = template.render(self, ctx)

return self.parse_text_to_nodes(text, allow_section_headings=True)
Loading
Loading