65 lines
1.9 KiB
Python
65 lines
1.9 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
|
||
|
||
from httpx import get
|
||
|
||
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]
|
||
content = get(url)
|
||
#paragraph_node = nodes.paragraph(text=f'hello {self.arguments[0]}!')
|
||
code = content.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
|
||
# FIXME handle the `name` option too
|
||
|
||
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,
|
||
}
|