Skip to content
Myr

clickdoctools.py

This file

Path

docs/clickdoctools.py

275 lines · 7.5 KiB · Python

Last changed by

Added example on ignoring of unknown options.Armin Ronacherbefore adoption4851f7c

History of this file

Take it

The walk stopped after 200 commits: lines older than 469ba25 point at it.

Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25

lines 1–6why, one step back
1import os
2import sys3import click4import shutil5import tempfile6import contextlib

Added example on ignoring of unknown options.Armin Ronacherbefore adoption4851f7c

line 7why, one step back
7import subprocess

Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25

lines 8–53why, one step back
8
9try:10 from StringIO import StringIO11except ImportError:12 from io import StringIO1314from docutils import nodes15from docutils.statemachine import ViewList1617from sphinx.domains import Domain18from sphinx.util.compat import Directive192021class EchoingStdin(object):2223 def __init__(self, input, output):24 self._input = input25 self._output = output2627 def __getattr__(self, x):28 return getattr(self._input, x)2930 def _echo(self, rv):31 mark = False32 if rv.endswith('\xff'):33 rv = rv[:-1]34 mark = True35 self._output.write(rv)36 if mark:37 self._output.write('^D\n')38 return rv3940 def read(self, n=-1):41 return self._echo(self._input.read(n))4243 def readline(self, n=-1):44 return self._echo(self._input.readline(n))4546 def readlines(self):47 return [self._echo(x) for x in self._input.readlines()]4849 def __iter__(self):50 return iter(self._echo(x) for x in self._input)515253@contextlib.contextmanager

Added example on ignoring of unknown options.Armin Ronacherbefore adoption4851f7c

lines 54–71why, one step back
54def fake_modules():
55 old_call = subprocess.call56 def dummy_call(*args, **kwargs):57 with tempfile.TemporaryFile('wb+') as f:58 kwargs['stdout'] = f59 kwargs['stderr'] = f60 rv = subprocess.Popen(*args, **kwargs).wait()61 f.seek(0)62 click.echo(f.read().decode('utf-8', 'replace').rstrip())63 return rv64 subprocess.call = dummy_call65 try:66 yield67 finally:68 subprocess.call = old_call697071@contextlib.contextmanager

Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25

lines 72–144why, one step back
72def isolation(input=None, env=None):
73 if isinstance(input, unicode):74 input = input.encode('utf-8')75 input = StringIO(input or '')76 output = StringIO()77 sys.stdin = EchoingStdin(input, output)78 sys.stdin.encoding = 'utf-8'7980 def visible_input(prompt=None):81 sys.stdout.write(prompt or '')82 val = input.readline().rstrip('\r\n')83 sys.stdout.write(val + '\n')84 sys.stdout.flush()85 return val8687 def hidden_input(prompt=None):88 sys.stdout.write((prompt or '') + '\n')89 sys.stdout.flush()90 return input.readline().rstrip('\r\n')9192 sys.stdout = output93 sys.stderr = output94 old_visible_prompt_func = click.termui.visible_prompt_func95 old_hidden_prompt_func = click.termui.hidden_prompt_func96 click.termui.visible_prompt_func = visible_input97 click.termui.hidden_prompt_func = hidden_input9899 old_env = {}100 try:101 if env:102 for key, value in env.iteritems():103 old_env[key] = os.environ.get(value)104 os.environ[key] = value105 yield output106 finally:107 for key, value in old_env.iteritems():108 if value is None:109 try:110 del os.environ[key]111 except Exception:112 pass113 else:114 os.environ[key] = value115 sys.stdout = sys.__stdout__116 sys.stderr = sys.__stderr__117 click.termui.visible_prompt_func = old_visible_prompt_func118 click.termui.hidden_prompt_func = old_hidden_prompt_func119120121@contextlib.contextmanager122def isolated_filesystem():123 cwd = os.getcwd()124 t = tempfile.mkdtemp()125 os.chdir(t)126 try:127 yield128 finally:129 os.chdir(cwd)130 try:131 shutil.rmtree(t)132 except (OSError, IOError):133 pass134135136class ExampleRunner(object):137138 def __init__(self):139 self.namespace = {140 'click': click,141 '__file__': 'dummy.py',142 }143144 def declare(self, source):

Added example on ignoring of unknown options.Armin Ronacherbefore adoption4851f7c

lines 145–147why, one step back
145 with fake_modules():
146 code = compile(source, '<docs>', 'exec')147 eval(code, self.namespace)

Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25

lines 148–152why, one step back
148
149 def run(self, source):150 code = compile(source, '<docs>', 'exec')151 buffer = []152

Rewrote the setuptools documentation.Armin Ronacherbefore adoption61b6ffa

line 153why, one step back
153 def invoke(cmd, args=None, prog_name=None,

Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25

lines 154–162why, one step back
154 input=None, terminate_input=False, env=None,
155 **extra):156 if env:157 for key, value in sorted(env.items()):158 if ' ' in value:159 value = '"%s"' % value160 buffer.append('$ export %s=%s' % (key, value))161 args = args or []162 if prog_name is None:

Rewrote the setuptools documentation.Armin Ronacherbefore adoption61b6ffa

lines 163–164why, one step back
163 prog_name = cmd.name.replace('_', '-')
164 buffer.append(('$ %s %s' % (

Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25

lines 165–173why, one step back
165 prog_name,
166 ' '.join(('"%s"' % x) if ' ' in x else x for x in args)167 )).rstrip())168 if isinstance(input, (tuple, list)):169 input = '\n'.join(input) + '\n'170 if terminate_input:171 input += '\xff'172 with isolation(input=input, env=env) as output:173 try:

Rewrote the setuptools documentation.Armin Ronacherbefore adoption61b6ffa

lines 174–175why, one step back
174 cmd.main(args=args, prog_name=prog_name.split()[-1],
175 **extra)

Implemented atomic file opening support.Armin Ronacherbefore adoption469ba25

lines 176–275why, one step back
176 except SystemExit:
177 pass178 buffer.extend(output.getvalue().splitlines())179180 def println(text=''):181 buffer.append(text)182183 eval(code, self.namespace, {184 'invoke': invoke,185 'println': println,186 'isolated_filesystem': isolated_filesystem,187 })188 return buffer189190 def close(self):191 pass192193194def parse_rst(state, content_offset, doc):195 node = nodes.section()196 # hack around title style bookkeeping197 surrounding_title_styles = state.memo.title_styles198 surrounding_section_level = state.memo.section_level199 state.memo.title_styles = []200 state.memo.section_level = 0201 state.nested_parse(doc, content_offset, node, match_titles=1)202 state.memo.title_styles = surrounding_title_styles203 state.memo.section_level = surrounding_section_level204 return node.children205206207def get_example_runner(document):208 runner = getattr(document, 'click_example_runner', None)209 if runner is None:210 runner = document.click_example_runner = ExampleRunner()211 return runner212213214class ExampleDirective(Directive):215 has_content = True216 required_arguments = 0217 optional_arguments = 0218 final_argument_whitespace = False219220 def run(self):221 doc = ViewList()222 runner = get_example_runner(self.state.document)223 try:224 runner.declare('\n'.join(self.content))225 except:226 runner.close()227 raise228 doc.append('.. sourcecode:: python', '')229 doc.append('', '')230 for line in self.content:231 doc.append(' ' + line, '')232 return parse_rst(self.state, self.content_offset, doc)233234235class RunExampleDirective(Directive):236 has_content = True237 required_arguments = 0238 optional_arguments = 0239 final_argument_whitespace = False240241 def run(self):242 doc = ViewList()243 runner = get_example_runner(self.state.document)244 try:245 rv = runner.run('\n'.join(self.content))246 except:247 runner.close()248 raise249 doc.append('.. sourcecode:: text', '')250 doc.append('', '')251 for line in rv:252 doc.append(' ' + line, '')253 return parse_rst(self.state, self.content_offset, doc)254255256class ClickDomain(Domain):257 name = 'click'258 label = 'Click'259 directives = {260 'example': ExampleDirective,261 'run': RunExampleDirective,262 }263264265def delete_example_runner_state(app, doctree):266 runner = getattr(doctree, 'click_example_runner', None)267 if runner is not None:268 runner.close()269 del doctree.click_example_runner270271272def setup(app):273 app.add_domain(ClickDomain)274275 app.connect('doctree-read', delete_example_runner_state)