xonsh/docs/extensions/cmdhelp.py

68 lines
2 KiB
Python
Raw Permalink Normal View History

2016-06-18 17:32:37 -04:00
"""This module adds a reST directive to sphinx that generates alias
2016-02-05 00:42:05 -05:00
documentation. For example::
.. command-help:: xonsh.aliases.source_foreign
2016-06-18 17:32:37 -04:00
.. command-help:: xonsh.aliases.source_foreign -h
2016-02-05 00:42:05 -05:00
2016-06-18 17:32:37 -04:00
will create help for aliases.
2016-02-05 00:42:05 -05:00
"""
import importlib
2016-02-05 00:42:05 -05:00
import io
import textwrap
from docutils import nodes
2020-08-26 10:10:59 -05:00
2016-02-05 00:42:05 -05:00
try:
2016-06-18 17:32:37 -04:00
from docutils.utils.error_reporting import ErrorString # the new way
2016-02-05 00:42:05 -05:00
except ImportError:
2020-08-26 10:10:59 -05:00
from docutils.error_reporting import ErrorString # the old way
from docutils.parsers.rst import Directive
2016-02-05 00:42:05 -05:00
from docutils.statemachine import ViewList
from sphinx.util.nodes import nested_parse_with_titles
from xonsh.tools import redirect_stdout, redirect_stderr
class CommandHelp(Directive):
2016-06-18 17:32:37 -04:00
"""The command-help directive, which is based on constructing a list of
2016-02-05 00:42:05 -05:00
of string lines of restructured text and then parsing it into its own node.
Note that this will add the '--help' flag automatically.
"""
2020-08-26 10:10:59 -05:00
2016-02-05 00:42:05 -05:00
required_arguments = 1
optional_arguments = 1
final_argument_whitespace = True
option_spec = {}
has_content = False
def run(self):
arguments = self.arguments
2020-08-26 10:10:59 -05:00
lines = [".. code-block:: none", ""]
m, f = arguments[0].rsplit(".", 1)
2016-02-05 00:42:05 -05:00
mod = importlib.import_module(m)
func = getattr(mod, f)
2020-08-26 10:10:59 -05:00
args = ["--help"] if len(arguments) == 1 else arguments[1:]
2016-02-05 00:42:05 -05:00
stdout = io.StringIO()
stderr = io.StringIO()
with redirect_stdout(stdout), redirect_stderr(stderr):
2016-02-05 01:25:59 -05:00
try:
func(args)
except SystemExit:
pass
2016-02-05 00:42:05 -05:00
stdout.seek(0)
s = stdout.read()
2020-08-26 10:10:59 -05:00
lines += textwrap.indent(s, " ").splitlines()
2016-02-05 00:42:05 -05:00
# hook to docutils
src, lineno = self.state_machine.get_source_and_line(self.lineno)
vl = ViewList(lines, source=src)
node = nodes.paragraph()
nested_parse_with_titles(self.state, vl, node)
return node.children
def setup(app):
2020-08-26 10:10:59 -05:00
app.add_directive("command-help", CommandHelp)