Skip to content
Myr

clickdoctools.py

This file

Path

docs/clickdoctools.py

252 lines · 6.8 KiB · Python

Last changed by

More automated docsArmin Ronacherbefore adoption8254b79

History of this file

Take it

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

lines 1–120why, one step back
1import os
2import 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,

More automated docsArmin Ronacherbefore adoption8254b79

line 121why, one step back
121 '__file__': 'dummy.py',

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

lines 122–252why, one step back
122 }
123124 def declare(self, source):125 code = compile(source, '<docs>', 'exec')126 eval(code, self.namespace)127128 def run(self, source):129 code = compile(source, '<docs>', 'exec')130 buffer = []131132 def invoke(cmd, args=None, prog_name=None, prog_prefix='python ',133 input=None, env=None, auto_envvar_prefix=None):134 if env:135 for key, value in sorted(env.items()):136 if ' ' in value:137 value = '"%s"' % value138 buffer.append('$ export %s=%s' % (key, value))139 args = args or []140 if prog_name is None:141 prog_name = cmd.name.replace('_', '-') + '.py'142 buffer.append(('$ %s%s %s' % (143 prog_prefix,144 prog_name,145 ' '.join(('"%s"' % x) if ' ' in x else x for x in args)146 )).rstrip())147 if isinstance(input, (tuple, list)):148 input = '\n'.join(input) + '\n'149 with isolation(input=input, env=env) as output:150 try:151 cmd.main(args=args, prog_name=prog_name,152 auto_envvar_prefix=auto_envvar_prefix)153 except SystemExit:154 pass155 buffer.extend(output.getvalue().splitlines())156157 def println(text=''):158 buffer.append(text)159160 eval(code, self.namespace, {161 'invoke': invoke,162 'println': println,163 'isolated_filesystem': isolated_filesystem,164 })165 return buffer166167 def close(self):168 pass169170171def parse_rst(state, content_offset, doc):172 node = nodes.section()173 # hack around title style bookkeeping174 surrounding_title_styles = state.memo.title_styles175 surrounding_section_level = state.memo.section_level176 state.memo.title_styles = []177 state.memo.section_level = 0178 state.nested_parse(doc, content_offset, node, match_titles=1)179 state.memo.title_styles = surrounding_title_styles180 state.memo.section_level = surrounding_section_level181 return node.children182183184def get_example_runner(document):185 runner = getattr(document, 'click_example_runner', None)186 if runner is None:187 runner = document.click_example_runner = ExampleRunner()188 return runner189190191class ExampleDirective(Directive):192 has_content = True193 required_arguments = 0194 optional_arguments = 0195 final_argument_whitespace = False196197 def run(self):198 doc = ViewList()199 runner = get_example_runner(self.state.document)200 try:201 runner.declare('\n'.join(self.content))202 except:203 runner.close()204 raise205 doc.append('.. sourcecode:: python', '')206 doc.append('', '')207 for line in self.content:208 doc.append(' ' + line, '')209 return parse_rst(self.state, self.content_offset, doc)210211212class RunExampleDirective(Directive):213 has_content = True214 required_arguments = 0215 optional_arguments = 0216 final_argument_whitespace = False217218 def run(self):219 doc = ViewList()220 runner = get_example_runner(self.state.document)221 try:222 rv = runner.run('\n'.join(self.content))223 except:224 runner.close()225 raise226 doc.append('.. sourcecode:: text', '')227 doc.append('', '')228 for line in rv:229 doc.append(' ' + line, '')230 return parse_rst(self.state, self.content_offset, doc)231232233class ClickDomain(Domain):234 name = 'click'235 label = 'Click'236 directives = {237 'example': ExampleDirective,238 'run': RunExampleDirective,239 }240241242def delete_example_runner_state(app, doctree):243 runner = getattr(doctree, 'click_example_runner', None)244 if runner is not None:245 runner.close()246 del doctree.click_example_runner247248249def setup(app):250 app.add_domain(ClickDomain)251252 app.connect('doctree-read', delete_example_runner_state)