clickdoctools.py
This file
Path
docs/clickdoctools.py
256 lines · 7.0 KiB · Python
Last changed by
Split up click into a packageArmin Ronacherbefore adoption0ed40c8
History of this fileTake 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 _echo(self, rv):30 mark = False31 if rv.endswith('\xff'):32 rv = rv[:-1]33 mark = True34 self._output.write(rv)35 if mark:36 self._output.write('^D\n')37 return rv3839 def read(self, n=-1):40 return self._echo(self._input.read(n))4142 def readline(self, n=-1):43 return self._echo(self._input.readline(n))4445 def readlines(self):46 return [self._echo(x) for x in self._input.readlines()]4748 def __iter__(self):49 return iter(self._echo(x) for x in self._input)505152@contextlib.contextmanager53def isolation(input=None, env=None):54 if isinstance(input, unicode):55 input = input.encode('utf-8')56 input = StringIO(input or '')57 output = StringIO()58 sys.stdin = EchoingStdin(input, output)59 sys.stdin.encoding = 'utf-8'6061 def visible_input(prompt=None):62 sys.stdout.write(prompt or '')63 val = input.readline().rstrip('\r\n')64 sys.stdout.write(val + '\n')65 sys.stdout.flush()66 return val6768 def hidden_input(prompt=None):69 sys.stdout.write((prompt or '') + '\n')70 sys.stdout.flush()71 return input.readline().rstrip('\r\n')7273 sys.stdout = output74 sys.stderr = output75 old_visible_prompt_func = click.helpers.visible_prompt_func76 old_hidden_prompt_func = click.helpers.hidden_prompt_func77 click.helpers.visible_prompt_func = visible_input78 click.helpers.hidden_prompt_func = hidden_input7980 old_env = {}81 try:82 if env:83 for key, value in env.iteritems():84 old_env[key] = os.environ.get(value)85 os.environ[key] = value86 yield output87 finally:88 for key, value in old_env.iteritems():89 if value is None:90 try:91 del os.environ[key]92 except Exception:93 pass94 else:95 os.environ[key] = value96 sys.stdout = sys.__stdout__97 sys.stderr = sys.__stderr__98 click.helpers.visible_prompt_func = old_visible_prompt_func99 click.helpers.hidden_prompt_func = old_hidden_prompt_func100101102@contextlib.contextmanager103def isolated_filesystem():104 cwd = os.getcwd()105 t = tempfile.mkdtemp()106 os.chdir(t)107 try:108 yield109 finally:110 os.chdir(cwd)111 try:112 shutil.rmtree(t)113 except (OSError, IOError):114 pass115116117class ExampleRunner(object):118119 def __init__(self):120 self.namespace = {121 'click': click,122 '__file__': 'dummy.py',123 }124125 def declare(self, source):126 code = compile(source, '<docs>', 'exec')127 eval(code, self.namespace)128129 def run(self, source):130 code = compile(source, '<docs>', 'exec')131 buffer = []132133 def invoke(cmd, args=None, prog_name=None, prog_prefix='python ',134 input=None, terminate_input=False, env=None,135 auto_envvar_prefix=None):136 if env:137 for key, value in sorted(env.items()):138 if ' ' in value:139 value = '"%s"' % value140 buffer.append('$ export %s=%s' % (key, value))141 args = args or []142 if prog_name is None:143 prog_name = cmd.name.replace('_', '-') + '.py'144 buffer.append(('$ %s%s %s' % (145 prog_prefix,146 prog_name,147 ' '.join(('"%s"' % x) if ' ' in x else x for x in args)148 )).rstrip())149 if isinstance(input, (tuple, list)):150 input = '\n'.join(input) + '\n'151 if terminate_input:152 input += '\xff'153 with isolation(input=input, env=env) as output:154 try:155 cmd.main(args=args, prog_name=prog_name,156 auto_envvar_prefix=auto_envvar_prefix)157 except SystemExit:158 pass159 buffer.extend(output.getvalue().splitlines())160161 def println(text=''):162 buffer.append(text)163164 eval(code, self.namespace, {165 'invoke': invoke,166 'println': println,167 'isolated_filesystem': isolated_filesystem,168 })169 return buffer170171 def close(self):172 pass173174175def parse_rst(state, content_offset, doc):176 node = nodes.section()177 # hack around title style bookkeeping178 surrounding_title_styles = state.memo.title_styles179 surrounding_section_level = state.memo.section_level180 state.memo.title_styles = []181 state.memo.section_level = 0182 state.nested_parse(doc, content_offset, node, match_titles=1)183 state.memo.title_styles = surrounding_title_styles184 state.memo.section_level = surrounding_section_level185 return node.children186187188def get_example_runner(document):189 runner = getattr(document, 'click_example_runner', None)190 if runner is None:191 runner = document.click_example_runner = ExampleRunner()192 return runner193194195class ExampleDirective(Directive):196 has_content = True197 required_arguments = 0198 optional_arguments = 0199 final_argument_whitespace = False200201 def run(self):202 doc = ViewList()203 runner = get_example_runner(self.state.document)204 try:205 runner.declare('\n'.join(self.content))206 except:207 runner.close()208 raise209 doc.append('.. sourcecode:: python', '')210 doc.append('', '')211 for line in self.content:212 doc.append(' ' + line, '')213 return parse_rst(self.state, self.content_offset, doc)214215216class RunExampleDirective(Directive):217 has_content = True218 required_arguments = 0219 optional_arguments = 0220 final_argument_whitespace = False221222 def run(self):223 doc = ViewList()224 runner = get_example_runner(self.state.document)225 try:226 rv = runner.run('\n'.join(self.content))227 except:228 runner.close()229 raise230 doc.append('.. sourcecode:: text', '')231 doc.append('', '')232 for line in rv:233 doc.append(' ' + line, '')234 return parse_rst(self.state, self.content_offset, doc)235236237class ClickDomain(Domain):238 name = 'click'239 label = 'Click'240 directives = {241 'example': ExampleDirective,242 'run': RunExampleDirective,243 }244245246def delete_example_runner_state(app, doctree):247 runner = getattr(doctree, 'click_example_runner', None)248 if runner is not None:249 runner.close()250 del doctree.click_example_runner251252253def setup(app):254 app.add_domain(ClickDomain)255256 app.connect('doctree-read', delete_example_runner_state)