rougail/docs/ext/extinclude.py

69 lines
2 KiB
Python

from __future__ import annotations
from docutils import nodes
from sphinx.application import Sphinx
from sphinx.util.docutils import SphinxDirective, SphinxRole
from sphinx.util.typing import ExtensionMetadata
from sphinx.directives.code import LiteralInclude, container_wrapper
import requests
class ExtInclude(LiteralInclude):
"""A directive to include code that comes from an url
Sample use::
.. extinclude:: https://forge.cloud.silique.fr/stove/rougail-tutorials/raw/tag/v1.1_010/firefox/00-proxy.yml
:linenos:
:language: yaml
:caption: this is a interesting code
- parameter required
- linenos, language and caption are optionnal.
:default language: yaml
:default caption: extinclude parameter (url)
"""
def run(self) -> list[nodes.Node]:
url = self.arguments[0]
headers = {
'accept': 'application/text',
'Content-Type': 'application/text',
}
response = requests.get(url, headers=headers)
#paragraph_node = nodes.paragraph(text=f'hello {self.arguments[0]}!')
code = response.text
literal = nodes.literal_block(code, code)
if 'language' in self.options:
literal['language'] = self.options['language']
else:
literal['language'] = 'yaml'
literal['linenos'] = 'linenos' in self.options
if 'caption' in self.options:
caption = self.options.get('caption')
else:
caption = url
literal['caption'] = caption
if 'name' in self.options:
literal['name'] = self.options.get('name')
literal = container_wrapper(self, literal, caption)
self.add_name(literal)
return [literal]
#paragraph_node = nodes.paragraph(text=content.text)
#return [paragraph_node]
def setup(app: Sphinx) -> ExtensionMetadata:
app.add_directive('extinclude', ExtInclude)
return {
'version': '0.1',
'parallel_read_safe': True,
'parallel_write_safe': True,
}