clickdoctools.py
This file
Path
docs/clickdoctools.py
255 lines · 6.9 KiB · Python
Last changed by
Added support for default overrides. This fixes #42Armin Ronacherbefore adoptione77783d
History of this fileTake it
Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 1–28why, one step back1import 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)28Split up click into a packageArmin Ronacherbefore adoption0ed40c8
lines 29–33why, one step back29 def _echo(self, rv):30 mark = False31 if rv.endswith('\xff'):32 rv = rv[:-1]33 mark = TrueMake documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
line 34why, one step back34 self._output.write(rv)Split up click into a packageArmin Ronacherbefore adoption0ed40c8
lines 35–36why, one step back35 if mark:36 self._output.write('^D\n')Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 37–38why, one step back37 return rv38Split up click into a packageArmin Ronacherbefore adoption0ed40c8
lines 39–41why, one step back39 def read(self, n=-1):40 return self._echo(self._input.read(n))41Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
line 42why, one step back42 def readline(self, n=-1):Split up click into a packageArmin Ronacherbefore adoption0ed40c8
line 43why, one step back43 return self._echo(self._input.readline(n))Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 44–45why, one step back4445 def readlines(self):Split up click into a packageArmin Ronacherbefore adoption0ed40c8
line 46why, one step back46 return [self._echo(x) for x in self._input.readlines()]Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 47–48why, one step back4748 def __iter__(self):Split up click into a packageArmin Ronacherbefore adoption0ed40c8
line 49why, one step back49 return iter(self._echo(x) for x in self._input)Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 50–53why, one step back505152@contextlib.contextmanager53def isolation(input=None, env=None):Split up click into a packageArmin Ronacherbefore adoption0ed40c8
line 54why, one step back54 if isinstance(input, unicode):Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 55–74why, one step back55 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 = outputAdded lazy file openingArmin Ronacherbefore adoptionf270dd2
lines 75–78why, one step back75 old_visible_prompt_func = click.termui.visible_prompt_func76 old_hidden_prompt_func = click.termui.hidden_prompt_func77 click.termui.visible_prompt_func = visible_input78 click.termui.hidden_prompt_func = hidden_inputMake documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 79–97why, one step back7980 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__Added lazy file openingArmin Ronacherbefore adoptionf270dd2
lines 98–99why, one step back98 click.termui.visible_prompt_func = old_visible_prompt_func99 click.termui.hidden_prompt_func = old_hidden_prompt_funcMake documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 100–121why, one step back100101102@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,More automated docsArmin Ronacherbefore adoption8254b79
line 122why, one step back122 '__file__': 'dummy.py',Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 123–133why, one step back123 }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 ',Split up click into a packageArmin Ronacherbefore adoption0ed40c8
line 134why, one step back134 input=None, terminate_input=False, env=None,Added support for default overrides. This fixes #42Armin Ronacherbefore adoptione77783d
line 135why, one step back135 **extra):Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 136–150why, one step back136 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'Split up click into a packageArmin Ronacherbefore adoption0ed40c8
lines 151–152why, one step back151 if terminate_input:152 input += '\xff'Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 153–154why, one step back153 with isolation(input=input, env=env) as output:154 try:Added support for default overrides. This fixes #42Armin Ronacherbefore adoptione77783d
line 155why, one step back155 cmd.main(args=args, prog_name=prog_name, **extra)Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
lines 156–255why, one step back156 except SystemExit:157 pass158 buffer.extend(output.getvalue().splitlines())159160 def println(text=''):161 buffer.append(text)162163 eval(code, self.namespace, {164 'invoke': invoke,165 'println': println,166 'isolated_filesystem': isolated_filesystem,167 })168 return buffer169170 def close(self):171 pass172173174def parse_rst(state, content_offset, doc):175 node = nodes.section()176 # hack around title style bookkeeping177 surrounding_title_styles = state.memo.title_styles178 surrounding_section_level = state.memo.section_level179 state.memo.title_styles = []180 state.memo.section_level = 0181 state.nested_parse(doc, content_offset, node, match_titles=1)182 state.memo.title_styles = surrounding_title_styles183 state.memo.section_level = surrounding_section_level184 return node.children185186187def get_example_runner(document):188 runner = getattr(document, 'click_example_runner', None)189 if runner is None:190 runner = document.click_example_runner = ExampleRunner()191 return runner192193194class ExampleDirective(Directive):195 has_content = True196 required_arguments = 0197 optional_arguments = 0198 final_argument_whitespace = False199200 def run(self):201 doc = ViewList()202 runner = get_example_runner(self.state.document)203 try:204 runner.declare('\n'.join(self.content))205 except:206 runner.close()207 raise208 doc.append('.. sourcecode:: python', '')209 doc.append('', '')210 for line in self.content:211 doc.append(' ' + line, '')212 return parse_rst(self.state, self.content_offset, doc)213214215class RunExampleDirective(Directive):216 has_content = True217 required_arguments = 0218 optional_arguments = 0219 final_argument_whitespace = False220221 def run(self):222 doc = ViewList()223 runner = get_example_runner(self.state.document)224 try:225 rv = runner.run('\n'.join(self.content))226 except:227 runner.close()228 raise229 doc.append('.. sourcecode:: text', '')230 doc.append('', '')231 for line in rv:232 doc.append(' ' + line, '')233 return parse_rst(self.state, self.content_offset, doc)234235236class ClickDomain(Domain):237 name = 'click'238 label = 'Click'239 directives = {240 'example': ExampleDirective,241 'run': RunExampleDirective,242 }243244245def delete_example_runner_state(app, doctree):246 runner = getattr(doctree, 'click_example_runner', None)247 if runner is not None:248 runner.close()249 del doctree.click_example_runner250251252def setup(app):253 app.add_domain(ClickDomain)254255 app.connect('doctree-read', delete_example_runner_state)