Created
April 15, 2025 11:53
-
-
Save Julien00859/822835b0c75e8bfe0e1c003a32c029d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import docutils.core | |
import fileinput | |
import inspect | |
import sys | |
from docutils import nodes | |
from docutils.parsers.rst import roles | |
from docutils.parsers.rst.directives.admonitions import Note | |
if '-h' in sys.argv or '--help' in sys.argv: | |
sys.exit(inspect.cleandoc(""" | |
usage: docstring.py [-h] [--html] [file] | |
It trims, unindent and then parses the input as reStructuredText | |
to produce and print the parsed AST on stdout. | |
--html: print HTML instead. | |
It reads the input from stdin unless you give a file. Reading | |
from stdin is handy to copy/paste a docstring directly to your | |
terminal, press ctrl-d once the docstring is pasted to close stdin. | |
""")) | |
html = '--html' in sys.argv | |
if html: | |
sys.argv.remove('--html') | |
def role_function(name, rawtext, text, lineno, inliner, options=None, content=None): | |
if text.startswith('~'): | |
text = text.rpartition('.')[2] | |
return [nodes.reference(rawtext, text, refuri='#')], [] | |
for role in ('attr', 'attribute', 'class', 'func', 'meth', 'ref', 'const', 'samp', 'term'): | |
roles.register_local_role(role, role_function) | |
for directive in ('attribute', 'deprecated'): | |
docutils.parsers.rst.directives.register_directive(directive, Note) | |
docstring = "" | |
for line in fileinput.input(): | |
docstring += line | |
docstring = inspect.cleandoc(docstring) | |
if html: | |
html_output = docutils.core.publish_string( | |
docstring, | |
writer_name='html5', | |
settings_overrides={ | |
'report_level': 2, | |
'halt_level': 5, | |
} | |
) | |
print(html_output.decode()) | |
else: | |
doctree = docutils.core.publish_doctree( | |
docstring, | |
settings_overrides={ | |
'report_level': 2, | |
'halt_level': 5, | |
} | |
) | |
print(doctree.pformat()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment