Skip to content
Myr

clickdoctools.py

This file

Path

docs/clickdoctools.py

251 lines · 6.8 KiB · Python

Last changed by

Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670

History of this file

Take it

1import os2import sys3import click4import shutil5import tempfile6import contextlib78try:9    from StringIO import StringIO10except ImportError:11    from io import StringIO1213from docutils import nodes14from docutils.statemachine import ViewList1516from sphinx.domains import Domain17from sphinx.util.compat import Directive181920class EchoingStdin(object):2122    def __init__(self, input, output):23        self._input = input24        self._output = output2526    def __getattr__(self, x):27        return getattr(self._input, x)2829    def read(self, n=-1):30        rv = self._input.read(n)31        self._output.write(rv)32        return rv3334    def readline(self, n=-1):35        rv = self._input.readline(n)36        self._output.write(rv)37        return rv3839    def readlines(self):40        rv = self._input.readlines()41        for line in rv:42            self._output.write(rv)43        return rv4445    def __iter__(self):46        for x in self._input:47            self._output.write(x)48            yield x495051@contextlib.contextmanager52def isolation(input=None, env=None):53    if click.PY2 and isinstance(input, unicode):54        input = input.encode('utf-8')55    input = StringIO(input or '')56    output = StringIO()57    sys.stdin = EchoingStdin(input, output)58    sys.stdin.encoding = 'utf-8'5960    def visible_input(prompt=None):61        sys.stdout.write(prompt or '')62        val = input.readline().rstrip('\r\n')63        sys.stdout.write(val + '\n')64        sys.stdout.flush()65        return val6667    def hidden_input(prompt=None):68        sys.stdout.write((prompt or '') + '\n')69        sys.stdout.flush()70        return input.readline().rstrip('\r\n')7172    sys.stdout = output73    sys.stderr = output74    old_visible_prompt_func = click.visible_prompt_func75    old_hidden_prompt_func = click.hidden_prompt_func76    click.visible_prompt_func = visible_input77    click.hidden_prompt_func = hidden_input7879    old_env = {}80    try:81        if env:82            for key, value in env.iteritems():83                old_env[key] = os.environ.get(value)84                os.environ[key] = value85        yield output86    finally:87        for key, value in old_env.iteritems():88            if value is None:89                try:90                    del os.environ[key]91                except Exception:92                    pass93            else:94                os.environ[key] = value95        sys.stdout = sys.__stdout__96        sys.stderr = sys.__stderr__97        click.visible_prompt_func = old_visible_prompt_func98        click.hidden_prompt_func = old_hidden_prompt_func99100101@contextlib.contextmanager102def isolated_filesystem():103    cwd = os.getcwd()104    t = tempfile.mkdtemp()105    os.chdir(t)106    try:107        yield108    finally:109        os.chdir(cwd)110        try:111            shutil.rmtree(t)112        except (OSError, IOError):113            pass114115116class ExampleRunner(object):117118    def __init__(self):119        self.namespace = {120            'click': click,121        }122123    def declare(self, source):124        code = compile(source, '<docs>', 'exec')125        eval(code, self.namespace)126127    def run(self, source):128        code = compile(source, '<docs>', 'exec')129        buffer = []130131        def invoke(cmd, args=None, prog_name=None, prog_prefix='python ',132                   input=None, env=None, auto_envvar_prefix=None):133            if env:134                for key, value in sorted(env.items()):135                    if ' ' in value:136                        value = '"%s"' % value137                    buffer.append('$ export %s=%s' % (key, value))138            args = args or []139            if prog_name is None:140                prog_name = cmd.name.replace('_', '-') + '.py'141            buffer.append(('$ %s%s %s' % (142                prog_prefix,143                prog_name,144                ' '.join(('"%s"' % x) if ' ' in x else x for x in args)145            )).rstrip())146            if isinstance(input, (tuple, list)):147                input = '\n'.join(input) + '\n'148            with isolation(input=input, env=env) as output:149                try:150                    cmd.main(args=args, prog_name=prog_name,151                             auto_envvar_prefix=auto_envvar_prefix)152                except SystemExit:153                    pass154                buffer.extend(output.getvalue().splitlines())155156        def println(text=''):157            buffer.append(text)158159        eval(code, self.namespace, {160            'invoke': invoke,161            'println': println,162            'isolated_filesystem': isolated_filesystem,163        })164        return buffer165166    def close(self):167        pass168169170def parse_rst(state, content_offset, doc):171    node = nodes.section()172    # hack around title style bookkeeping173    surrounding_title_styles = state.memo.title_styles174    surrounding_section_level = state.memo.section_level175    state.memo.title_styles = []176    state.memo.section_level = 0177    state.nested_parse(doc, content_offset, node, match_titles=1)178    state.memo.title_styles = surrounding_title_styles179    state.memo.section_level = surrounding_section_level180    return node.children181182183def get_example_runner(document):184    runner = getattr(document, 'click_example_runner', None)185    if runner is None:186        runner = document.click_example_runner = ExampleRunner()187    return runner188189190class ExampleDirective(Directive):191    has_content = True192    required_arguments = 0193    optional_arguments = 0194    final_argument_whitespace = False195196    def run(self):197        doc = ViewList()198        runner = get_example_runner(self.state.document)199        try:200            runner.declare('\n'.join(self.content))201        except:202            runner.close()203            raise204        doc.append('.. sourcecode:: python', '')205        doc.append('', '')206        for line in self.content:207            doc.append(' ' + line, '')208        return parse_rst(self.state, self.content_offset, doc)209210211class RunExampleDirective(Directive):212    has_content = True213    required_arguments = 0214    optional_arguments = 0215    final_argument_whitespace = False216217    def run(self):218        doc = ViewList()219        runner = get_example_runner(self.state.document)220        try:221            rv = runner.run('\n'.join(self.content))222        except:223            runner.close()224            raise225        doc.append('.. sourcecode:: text', '')226        doc.append('', '')227        for line in rv:228            doc.append(' ' + line, '')229        return parse_rst(self.state, self.content_offset, doc)230231232class ClickDomain(Domain):233    name = 'click'234    label = 'Click'235    directives = {236        'example':  ExampleDirective,237        'run':      RunExampleDirective,238    }239240241def delete_example_runner_state(app, doctree):242    runner = getattr(doctree, 'click_example_runner', None)243    if runner is not None:244        runner.close()245        del doctree.click_example_runner246247248def setup(app):249    app.add_domain(ClickDomain)250251    app.connect('doctree-read', delete_example_runner_state)