clickdoctools.py
This file
Path
docs/clickdoctools.py
282 lines · 7.6 KiB · Python
Last changed by
Fix test for delayed progress bar displayJan Christoph Bischkobefore adoption82f9c62
History of this fileTake it
The walk stopped after 200 commits: lines older than b8ca3f5 point at it.
Started changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
lines 1–6why, one step back1import os2import sys3import click4import shutil5import tempfile6import contextlibAdded example on ignoring of unknown options.Armin Ronacherbefore adoption4851f7c
line 7why, one step back7import subprocessStarted changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
lines 8–17why, one step back89try:10 from StringIO import StringIO11except ImportError:12 from io import StringIO1314from docutils import nodes15from docutils.statemachine import ViewList1617from sphinx.domains import DomainFix test for delayed progress bar displayJan Christoph Bischkobefore adoption82f9c62
line 18why, one step back18from docutils.parsers.rst import DirectiveStarted changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
line 19why, one step back19Fix test for delayed progress bar displayJan Christoph Bischkobefore adoption82f9c62
line 20why, one step back20PY2 = sys.version_info[0] == 2Started changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
line 21why, one step back21Fix test for delayed progress bar displayJan Christoph Bischkobefore adoption82f9c62
lines 22–27why, one step back22if PY2:23 text_type = unicode24else:25 text_type = str26 27Started changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
lines 28–60why, one step back28class EchoingStdin(object):2930 def __init__(self, input, output):31 self._input = input32 self._output = output3334 def __getattr__(self, x):35 return getattr(self._input, x)3637 def _echo(self, rv):38 mark = False39 if rv.endswith('\xff'):40 rv = rv[:-1]41 mark = True42 self._output.write(rv)43 if mark:44 self._output.write('^D\n')45 return rv4647 def read(self, n=-1):48 return self._echo(self._input.read(n))4950 def readline(self, n=-1):51 return self._echo(self._input.readline(n))5253 def readlines(self):54 return [self._echo(x) for x in self._input.readlines()]5556 def __iter__(self):57 return iter(self._echo(x) for x in self._input)585960@contextlib.contextmanagerAdded example on ignoring of unknown options.Armin Ronacherbefore adoption4851f7c
lines 61–78why, one step back61def fake_modules():62 old_call = subprocess.call63 def dummy_call(*args, **kwargs):64 with tempfile.TemporaryFile('wb+') as f:65 kwargs['stdout'] = f66 kwargs['stderr'] = f67 rv = subprocess.Popen(*args, **kwargs).wait()68 f.seek(0)69 click.echo(f.read().decode('utf-8', 'replace').rstrip())70 return rv71 subprocess.call = dummy_call72 try:73 yield74 finally:75 subprocess.call = old_call767778@contextlib.contextmanagerStarted changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
line 79why, one step back79def isolation(input=None, env=None):Fix test for delayed progress bar displayJan Christoph Bischkobefore adoption82f9c62
line 80why, one step back80 if isinstance(input, text_type):Started changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
lines 81–151why, one step back81 input = input.encode('utf-8')82 input = StringIO(input or '')83 output = StringIO()84 sys.stdin = EchoingStdin(input, output)85 sys.stdin.encoding = 'utf-8'8687 def visible_input(prompt=None):88 sys.stdout.write(prompt or '')89 val = input.readline().rstrip('\r\n')90 sys.stdout.write(val + '\n')91 sys.stdout.flush()92 return val9394 def hidden_input(prompt=None):95 sys.stdout.write((prompt or '') + '\n')96 sys.stdout.flush()97 return input.readline().rstrip('\r\n')9899 sys.stdout = output100 sys.stderr = output101 old_visible_prompt_func = click.termui.visible_prompt_func102 old_hidden_prompt_func = click.termui.hidden_prompt_func103 click.termui.visible_prompt_func = visible_input104 click.termui.hidden_prompt_func = hidden_input105106 old_env = {}107 try:108 if env:109 for key, value in env.iteritems():110 old_env[key] = os.environ.get(value)111 os.environ[key] = value112 yield output113 finally:114 for key, value in old_env.iteritems():115 if value is None:116 try:117 del os.environ[key]118 except Exception:119 pass120 else:121 os.environ[key] = value122 sys.stdout = sys.__stdout__123 sys.stderr = sys.__stderr__124 click.termui.visible_prompt_func = old_visible_prompt_func125 click.termui.hidden_prompt_func = old_hidden_prompt_func126127128@contextlib.contextmanager129def isolated_filesystem():130 cwd = os.getcwd()131 t = tempfile.mkdtemp()132 os.chdir(t)133 try:134 yield135 finally:136 os.chdir(cwd)137 try:138 shutil.rmtree(t)139 except (OSError, IOError):140 pass141142143class ExampleRunner(object):144145 def __init__(self):146 self.namespace = {147 'click': click,148 '__file__': 'dummy.py',149 }150151 def declare(self, source):Added example on ignoring of unknown options.Armin Ronacherbefore adoption4851f7c
lines 152–154why, one step back152 with fake_modules():153 code = compile(source, '<docs>', 'exec')154 eval(code, self.namespace)Started changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
lines 155–159why, one step back155156 def run(self, source):157 code = compile(source, '<docs>', 'exec')158 buffer = []159Rewrote the setuptools documentation.Armin Ronacherbefore adoption61b6ffa
line 160why, one step back160 def invoke(cmd, args=None, prog_name=None,Started changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
lines 161–169why, one step back161 input=None, terminate_input=False, env=None,162 **extra):163 if env:164 for key, value in sorted(env.items()):165 if ' ' in value:166 value = '"%s"' % value167 buffer.append('$ export %s=%s' % (key, value))168 args = args or []169 if prog_name is None:Rewrote the setuptools documentation.Armin Ronacherbefore adoption61b6ffa
lines 170–171why, one step back170 prog_name = cmd.name.replace('_', '-')171 buffer.append(('$ %s %s' % (Started changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
lines 172–180why, one step back172 prog_name,173 ' '.join(('"%s"' % x) if ' ' in x else x for x in args)174 )).rstrip())175 if isinstance(input, (tuple, list)):176 input = '\n'.join(input) + '\n'177 if terminate_input:178 input += '\xff'179 with isolation(input=input, env=env) as output:180 try:Rewrote the setuptools documentation.Armin Ronacherbefore adoption61b6ffa
lines 181–182why, one step back181 cmd.main(args=args, prog_name=prog_name.split()[-1],182 **extra)Started changelog section for 3.0Armin Ronacherbefore adoptionb8ca3f5
lines 183–282why, one step back183 except SystemExit:184 pass185 buffer.extend(output.getvalue().splitlines())186187 def println(text=''):188 buffer.append(text)189190 eval(code, self.namespace, {191 'invoke': invoke,192 'println': println,193 'isolated_filesystem': isolated_filesystem,194 })195 return buffer196197 def close(self):198 pass199200201def parse_rst(state, content_offset, doc):202 node = nodes.section()203 # hack around title style bookkeeping204 surrounding_title_styles = state.memo.title_styles205 surrounding_section_level = state.memo.section_level206 state.memo.title_styles = []207 state.memo.section_level = 0208 state.nested_parse(doc, content_offset, node, match_titles=1)209 state.memo.title_styles = surrounding_title_styles210 state.memo.section_level = surrounding_section_level211 return node.children212213214def get_example_runner(document):215 runner = getattr(document, 'click_example_runner', None)216 if runner is None:217 runner = document.click_example_runner = ExampleRunner()218 return runner219220221class ExampleDirective(Directive):222 has_content = True223 required_arguments = 0224 optional_arguments = 0225 final_argument_whitespace = False226227 def run(self):228 doc = ViewList()229 runner = get_example_runner(self.state.document)230 try:231 runner.declare('\n'.join(self.content))232 except:233 runner.close()234 raise235 doc.append('.. sourcecode:: python', '')236 doc.append('', '')237 for line in self.content:238 doc.append(' ' + line, '')239 return parse_rst(self.state, self.content_offset, doc)240241242class RunExampleDirective(Directive):243 has_content = True244 required_arguments = 0245 optional_arguments = 0246 final_argument_whitespace = False247248 def run(self):249 doc = ViewList()250 runner = get_example_runner(self.state.document)251 try:252 rv = runner.run('\n'.join(self.content))253 except:254 runner.close()255 raise256 doc.append('.. sourcecode:: text', '')257 doc.append('', '')258 for line in rv:259 doc.append(' ' + line, '')260 return parse_rst(self.state, self.content_offset, doc)261262263class ClickDomain(Domain):264 name = 'click'265 label = 'Click'266 directives = {267 'example': ExampleDirective,268 'run': RunExampleDirective,269 }270271272def delete_example_runner_state(app, doctree):273 runner = getattr(doctree, 'click_example_runner', None)274 if runner is not None:275 runner.close()276 del doctree.click_example_runner277278279def setup(app):280 app.add_domain(ClickDomain)281282 app.connect('doctree-read', delete_example_runner_state)