Skip to content
Myr

Merge pull request #113 from iKevinY/doc-fixes

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Documentation & docstring fixes

authored by Armin Ronacher · committed by Armin Ronacher · parents e4dca8a, 30b66d9 · Browse files · 22 files+163 added−167 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

22 files+163 added−167 removed

  • tests:+2 added−2 removed
  • other:+161 added−165 removed

22 files+163 added−167 removed

modified:click/__init__.py+3 added-3 removed
1 unmodified line
2"""3 click4 ~~~~~56 click is a simple Python module that wraps the stdlib's optparse to make7 writing command line scripts fun. Unlike other modules it's based around6 Click is a simple Python module that wraps the stdlib's optparse to make7 writing command line scripts fun. Unlike other modules, it's based around8 a simple API that does not come with too much magic and is composable.910 In case optparse ever goes away from the stdlib it will be shipped by10 In case optparse ever gets removed from the stdlib, it will be shipped by11 this module.1213 :copyright: (c) 2014 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.
71 unmodified lines
modified:click/_compat.py+33 added-36 removed
41 unmodified lines
42 def __init__(self, stream, encoding, errors, **extra):43 io.TextIOWrapper.__init__(self, _FixupStream(stream),44 encoding, errors, **extra)4546 # The io module is already a place where Python 2 got the47 # python 3 text behavior forced on, so we need to unbreak48 # it to look like python 2 stuff.46 # The io module is a place where the Python 3 text behavior47 # was forced upon Python 2, so we need to unbreak48 # it to look like Python 2.49 if PY2:50 def write(self, x):51 if isinstance(x, str) or is_bytes(x):52 try:
15 unmodified lines
686970class _FixupStream(object):71 """The new io interface needs more from streams than streams72 traditionally implement. As such this fixup stuff is necessary in72 traditionally implement. As such, this fix-up code is necessary in73 some circumstances.74 """7576 def __init__(self, stream):
5 unmodified lines
82 def read1(self, size):83 f = getattr(self._stream, 'read1', None)84 if f is not None:85 return f(size)86 # Only python 2 we dispatch to readline instead of read as we86 # We only dispatch to readline instead of read in Python 2 as we87 # do not want cause problems with the different implementation88 # of line buffering.89 if PY2:90 return self._stream.readline(size)
45 unmodified lines
136 return isinstance(x, (buffer, bytearray))137138 _identifier_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9_]*$')139140 # For Windows we need to force stdout/stdin/stderr to binary if it's140 # For Windows, we need to force stdout/stdin/stderr to binary if it's141 # fetched for that. This obviously is not the most correct way to do142 # it as it changes global state. Unfortunately there does not seem to142 # it as it changes global state. Unfortunately, there does not seem to143 # be a clear better way to do it as just reopening the file in binary144 # mode does not change anything.145 #146 # An option would be to do what python 3 does and to open the file as147 # binary only, patch it back to the system and then use a wrapper146 # An option would be to do what Python 3 does and to open the file as147 # binary only, patch it back to the system, and then use a wrapper148 # stream that converts newlines. It's not quite clear what's the149 # correct option here.150 if sys.platform == 'win32':151 import msvcrt
50 unmodified lines
202 return isinstance(stream.read(0), bytes)203 except Exception:204 return default205 # This happens in some cases where the stream was already206 # closed. In this case we assume the defalt.206 # closed. In this case, we assume the default.207208 def _is_binary_writer(stream, default=False):209 try:210 stream.write(b'')
7 unmodified lines
218 return True219220 def _find_binary_reader(stream):221 # We need to figure out if the given stream is already binary.222 # This can happen because the official docs recommend detatching222 # This can happen because the official docs recommend detaching223 # the streams to get binary streams. Some code might do this, so224 # we need to deal with this case explicitly.225 is_binary = _is_binary_reader(stream, False)226227 if is_binary:225 if _is_binary_reader(stream, False):226 return stream227228 buf = getattr(stream, 'buffer', None)229231 # Same situation here, this time we assume that the buffer is230 # Same situation here; this time we assume that the buffer is231 # actually binary in case it's closed.232 if buf is not None and _is_binary_reader(buf, True):233 return buf234
6 unmodified lines
241 return stream242243 buf = getattr(stream, 'buffer', None)244246 # Same situation here, this time we assume that the buffer is245 # Same situation here; this time we assume that the buffer is246 # actually binary in case it's closed.247 if buf is not None and _is_binary_writer(buf, True):248 return buf249250 def _stream_is_misconfigured(stream):252 """A stream is misconfigured if it's encoding is ASCII."""251 """A stream is misconfigured if its encoding is ASCII."""252 return is_ascii_encoding(getattr(stream, 'encoding', None))253254 def _is_compatible_text_stream(stream, encoding, errors):255 stream_encoding = getattr(stream, 'encoding', None)
2 unmodified lines
258 # Perfect match.259 if stream_encoding == encoding and stream_errors == errors:260 return True261263 # Otherwise it's only a compatible stream if we did not ask for262 # Otherwise, it's only a compatible stream if we did not ask for263 # an encoding.264 if encoding is None:265 return stream_encoding is not None266
2 unmodified lines
269 def _force_correct_text_reader(text_reader, encoding, errors):270 if _is_binary_reader(text_reader, False):271 binary_reader = text_reader272 else:274 # If there is no target encoding set we need to verify that the275 # reader is actually not misconfigured.273 # If there is no target encoding set, we need to verify that the274 # reader is not actually misconfigured.275 if encoding is None and not _stream_is_misconfigured(text_reader):276 return text_reader277278 if _is_compatible_text_stream(text_reader, encoding, errors):279 return text_reader280282 # If the reader has no encoding we try to find the underlying281 # If the reader has no encoding, we try to find the underlying282 # binary reader for it. If that fails because the environment is283 # misconfigured, we silently go with the same reader because this285 # is too common to happen. In that case mojibake is better than284 # is too common to happen. In that case, mojibake is better than285 # exceptions.286 binary_reader = _find_binary_reader(text_reader)287 if binary_reader is None:288 return text_reader289291 # At this point we default the errors to replace instead of strict290 # At this point, we default the errors to replace instead of strict291 # because nobody handles those errors anyways and at this point292 # we're so fundamentally fucked that nothing can repair it.293 if errors is None:294 errors = 'replace'
2 unmodified lines
297 def _force_correct_text_writer(text_writer, encoding, errors):298 if _is_binary_writer(text_writer, False):299 binary_writer = text_writer300 else:302 # If there is no target encoding set we need to verify that the303 # writer is actually not misconfigured.301 # If there is no target encoding set, we need to verify that the302 # writer is not actually misconfigured.303 if encoding is None and not _stream_is_misconfigured(text_writer):304 return text_writer305306 if _is_compatible_text_stream(text_writer, encoding, errors):307 return text_writer308310 # If the writer has no encoding we try to find the underlying309 # If the writer has no encoding, we try to find the underlying310 # binary writer for it. If that fails because the environment is311 # misconfigured, we silently go with the same writer because this313 # is too common to happen. In that case mojibake is better than312 # is too common to happen. In that case, mojibake is better than313 # exceptions.314 binary_writer = _find_binary_writer(text_writer)315 if binary_writer is None:316 return text_writer317319 # At this point we default the errors to replace instead of strict318 # At this point, we default the errors to replace instead of strict319 # because nobody handles those errors anyways and at this point320 # we're so fundamentally fucked that nothing can repair it.321 if errors is None:322 errors = 'replace'
52 unmodified lines
375376377def open_stream(filename, mode='r', encoding=None, errors='strict',378 atomic=False):380 # standard streams first. These are simple because they don't need379 # Standard streams first. These are simple because they don't need380 # special handling for the atomic flag. It's entirely ignored.381 if filename == '-':382 if 'w' in mode:383 if 'b' in mode:
2 unmodified lines
386 if 'b' in mode:387 return get_binary_stdin(), False388 return get_text_stdin(encoding=encoding, errors=errors), False389391 # Non-atomic writes directly go out through the regular open392 # functions.390 # Non-atomic writes directly go out through the regular open functions.391 if not atomic:392 if encoding is None:393 return open(filename, mode), True394 return io.open(filename, mode, encoding=encoding, errors=errors), True395396 # Atomic writes are more complicated. They work by opening a file397 # as a proxy in the same folder and then using the fdopen400 # functionality to wrap it in a python file. Then we wrap it in an398 # functionality to wrap it in a Python file. Then we wrap it in an399 # atomic file that moves the file over on close.400 import tempfile401 fd, tmp_filename = tempfile.mkstemp(dir=os.path.dirname(filename),402 prefix='.__atomic-write')
5 unmodified lines
408409 return _AtomicFile(f, tmp_filename, filename), True410411414# Used in a destructor call, needs extra protection from interpreter415# cleanup.412# Used in a destructor call, needs extra protection from interpreter cleanup.413_rename = os.rename414415416class _AtomicFile(object):
31 unmodified lines
448auto_wrap_for_ansi = None449colorama = None450451455# If we're on windows we provide transparent integration through456# colorama. This will make ansi colors through the echo function452# If we're on Windows, we provide transparent integration through453# colorama. This will make ANSI colors through the echo function454# work automatically.455if sys.platform.startswith('win'):456 try:457 import colorama
69 unmodified lines
modified:click/_termui_impl.py+1 added-1 removed
1 unmodified line
2 click._termui_impl3 ~~~~~~~~~~~~~~~~~~45 This module contains implementations for the termui module. To keep the6 import time of click down some infrequently used functionality is placed6 import time of click down, some infrequently used functionality is placed7 in this module and only imported as needed.89 :copyright: (c) 2014 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.
477 unmodified lines
modified:click/core.py+21 added-21 removed
36 unmodified lines
37 code = getattr(callback, '__code__', None)38 args = getattr(code, 'co_argcount', 3)3940 if args < 3:41 # This will become a warning in Click 3.042 ##from warnings import warn43 ##warn(Warning('Invoked legacy parameter callback "%s". The new '44 ## 'signature for such callbacks starting with '45 ## 'Click 2.0 is (ctx, param, value).'46 ## % callback), stacklevel=3)41 # This will become a warning in click 3.0:42 ## from warnings import warn43 ## warn(Warning('Invoked legacy parameter callback "%s". The new '44 ## 'signature for such callbacks starting with '45 ## 'click 2.0 is (ctx, param, value).'46 ## % callback), stacklevel=3)47 return callback(ctx, value)48 return callback(ctx, param, value)4950
84 unmodified lines
135 self.args = []136 #: this flag indicates if a subcommand is going to be executed.137 #: a group callback can use this information to figure out if it's138 #: being executed directly or because the execution flow passes139 #: onwards to a subcommand. By default it's `None` but it can be139 #: onwards to a subcommand. By default it's `None`, but it can be140 #: the name of the subcommand to execute.141 self.invoked_subcommand = None142 if obj is None and parent is not None:143 obj = parent.obj144 #: the user object stored.145 self.obj = obj146 #: A dictionary (like object) with defaults for parameters.146 #: A dictionary (-like object) with defaults for parameters.147 self.default_map = default_map148149 if terminal_width is None and parent is not None:150 terminal_width = parent.terminal_width
31 unmodified lines
182183 def call_on_close(self, f):184 """This decorator remembers a function as callback that should be185 executed when the context tears down. This is most useful to bind186 resource handling to the script execution. For instance file objects186 resource handling to the script execution. For instance, file objects187 opened by the :class:`File` type will register their close callbacks188 here.189190 :param f: the function to execute on teardown.
126 unmodified lines
317 Most code will never use this as it does not implement a lot of useful318 functionality but it can act as the direct subclass of alternative319 parsing methods that do not depend on the click parser.320321 For instance this can be used to bridge click and other systems like321 For instance, this can be used to bridge click and other systems like322 argparse or docopt.323324 Because base commands do not implement a lot of the API that other325 parts of click take for granted they are not supported for all326 operations. For instance they cannot be used with the decorators325 parts of click take for granted, they are not supported for all326 operations. For instance, they cannot be used with the decorators327 usually and they have no built-in callback system.328329 :param name: the name of the command to use unless a group overrides it.330 """
69 unmodified lines
400 uppercase.401 :param extra: extra keyword arguments are forwarded to the context402 constructor. See :class:`Context` for more information.403 """404 # If we are on python 3 we will verify that the environment is404 # If we are in Python 3, we will verify that the environment is405 # sane at this point of reject further execution to avoid a406 # broken script.407 if not PY2:408 try:
16 unmodified lines
425 if prog_name is None:426 prog_name = make_str(os.path.basename(427 sys.argv and sys.argv[0] or __file__))428429 # Hook for the bash completion. This only activates if the bash429 # Hook for the Bash completion. This only activates if the Bash430 # completion is actually enabled, otherwise this is quite a fast431 # noop.432 _bashcomplete(self, prog_name, complete_var)433
233 unmodified lines
667 cmd_name = make_str(ctx.args[0])668 cmd = self.get_command(ctx, cmd_name)669670 # If we don't find the command we want to show an error message671 # to the user that it was not provided. However there is671 # to the user that it was not provided. However, there is672 # something else we should do: if the first argument looks like673 # an option we want to kick off parsing again for arguments to674 # resolve things like --help which now should go to the main675 # place.
116 unmodified lines
792 Some settings are supported by both options and arguments.793794 .. versionchanged:: 2.0795 Changed signature for parameter callback to also be passed the796 parameter. In click 2.0 the old callback format will still work796 parameter. In click 2.0, the old callback format will still work,797 but it will raise a warning to give you change to migrate the798 code easier.799800 :param param_decls: the parameter declarations for this option or801 argument. This is a list of flags or argument802 names.803 :param type: the type that should be used. Either a :class:`ParamType`804 or a python type. The later is converted into the former804 or a Python type. The later is converted into the former805 automatically if supported.806 :param required: controls if this is optional or not.807 :param default: the default value if omitted. This can also be a callable807 :param default: the default value if omitted. This can also be a callable,808 in which case it's invoked when the default is needed809 without any arguments.810 :param callback: a callback that should be executed after the parameter811 was matched. This is called as ``fn(ctx, param,812 value)`` and needs to return the value. Before click813 2.0 the signature was ``(ctx, value)``.813 2.0, the signature was ``(ctx, value)``.814 :param nargs: the number of arguments to match. If not ``1`` the return815 value is a tuple instead of single value.816 :param metavar: how the value is represented in the help page.817 :param expose_value: if this is `True` then the value is passed onwards
133 unmodified lines
951 return []952953954class Option(Parameter):955 """Options are usually optionaly values on the command line and955 """Options are usually optional values on the command line and956 have some extra features that arguments don't have.957958 All other parameters are passed onwards to the parameter constructor.959960 :param show_default: controls if the default value should be shown on the961 help page. Normally defaults are not shown.961 help page. Normally, defaults are not shown.962 :param prompt: if set to `True` or a non empty string then the user will963 be prompted for input if not set. If set to `True` the964 prompt will be the option name capitalized.965 :param confirmation_prompt: if set then the value will need to be confirmed
298 unmodified lines
modified:click/decorators.py+7 added-7 removed
6 unmodified lines
7from .utils import echo8910def pass_context(f):11 """Marks a callback that it wants to receive the current context11 """Marks a callback as wanting to receive the current context12 object as first argument.13 """14 f.__click_pass_context__ = True15 return f161718def pass_obj(f):19 """Similar to :func:`pass_context` but only pass the object on the19 """Similar to :func:`pass_context`, but only pass the object on the20 context onwards (:attr:`Context.obj`). This is useful if that object21 represents the state of a nested system.22 """23 @pass_context
106 unmodified lines
130131132def argument(*param_decls, **attrs):133 """Attaches an option to the command. All positional arguments are134 passed as parameter declarations to :class:`Argument`, all keyword134 passed as parameter declarations to :class:`Argument`; all keyword135 arguments are forwarded unchanged. This is equivalent to creating an136 :class:`Option` instance manually and attaching it to the137 :attr:`Command.params` list.138 """
4 unmodified lines
143144145def option(*param_decls, **attrs):146 """Attaches an option to the command. All positional arguments are147 passed as parameter declarations to :class:`Option`, all keyword147 passed as parameter declarations to :class:`Option`; all keyword148 arguments are forwarded unchanged. This is equivalent to creating an149 :class:`Option` instance manually and attaching it to the150 :attr:`Command.params` list.151 """
3 unmodified lines
155 return decorator156157158def confirmation_option(*param_decls, **attrs):159 """Shortcut for confirmation prompts that can be ignored by bypassed159 """Shortcut for confirmation prompts that can be ignored by passing160 ``--yes`` as parameter.161162 This is equivalent to decorating a function with :func:`option` with163 the following parameters::
97 unmodified lines
261262def help_option(*param_decls, **attrs):263 """Adds a ``--help`` option which immediately ends the program264 printing out the help page. This is usually unnecessary to add as265 this is added by default to all commands unless supressed.265 this is added by default to all commands unless suppressed.266267 Like :func:`version_option` this is implemented as eager option that267 Like :func:`version_option`, this is implemented as eager option that268 prints in the callback and exits.269270 All arguments are forwarded to :func:`option`.271 """
16 unmodified lines
modified:click/exceptions.py+5 added-5 removed
2 unmodified lines
3from .utils import echo456class ClickException(Exception):7 """An exception that click can handle and show to the user.."""7 """An exception that click can handle and show to the user."""89 #: The exit code for this exception10 exit_code = 111
37 unmodified lines
4950class BadParameter(UsageError):51 """An exception that formats out a standardized error message for a52 bad parameter. This is useful when thrown from a callback or type as53 click will attach contextual information to it (for instance like54 which parameter it is).53 click will attach contextual information to it (for instance, which54 parameter it is).5556 .. versionadded:: 2.05758 :param param: the parameter object that caused this error. This can59 be left and click if possible will attach this info60 itself.59 be left out, and click will attach this info itself60 if possible.61 :param param_hint: a string that shows up as parameter name. This62 can be used as alternative to `param` in cases63 where custom validation should happen. If it is64 a string it's used as such, if it's a list then
38 unmodified lines
modified:click/formatting.py+6 added-6 removed
17 unmodified lines
181920def wrap_text(text, width=78, initial_indent='', subsequent_indent='',21 preserve_paragraphs=False):22 """A helper function that intelligently wraps text. By default it22 """A helper function that intelligently wraps text. By default, it23 assumes that it operates on a single paragraph of text but if the24 `preserve_paragraphs` parameter is provided it will intelligently25 handle paragraphs (defined by two empty lines).2627 If paragraphs are handled a paragraph can be prefixed with an empty27 If paragraphs are handled, a paragraph can be prefixed with an empty28 line containing the ``\\b`` character (``\\x08``) to indicate that29 no rewrapping should happen in that block.3031 :param text: the text that should be rewrapped.
49 unmodified lines
81 return '\n\n'.join(rv)828384class HelpFormatter(object):85 """This class helps with formatting text based help pages. It's86 usually just needed for very special internal cases but it's also85 """This class helps with formatting text-based help pages. It's86 usually just needed for very special internal cases, but it's also87 exposed so that developers can write their own fancy outputs.8889 At present it always writes into memory.89 At present, it always writes into memory.9091 :param indent_increment: the additional increment for each level.92 :param width: the width for the text. This defaults to the terminal93 width clamped to a maximum of 78.
96 unmodified lines
190 self.write('\n')191192 @contextmanager193 def section(self, name):194 """Helpful context manager that writes a paragraph, a heading194 """Helpful context manager that writes a paragraph, a heading,195 and the indents.196197 :param name: the section name that is written as heading.198 """
20 unmodified lines
modified:click/parser.py+3 added-4 removed
145 unmodified lines
146147 def add_option(self, opts, dest, action=None, nargs=1, const=None,148 obj=None):149 """Adds a new option named `dest` to the parser. The destination150 is not inferred unlike with optparse and needs to be explicitly150 is not inferred (unlike with optparse) and needs to be explicitly151 provided. Action can be any of ``store``, ``store_const``,152 ``append``, ``appnd_const`` or ``count``.153154 The `obj` can be used to identify the option in the order list
48 unmodified lines
203 def _process_args_for_options(self, state):204 while state.rargs:205 arg = state.rargs.pop(0)206 arglen = len(arg)207 # Double dash es always handled explicitly regardless of what207 # Double dashes always handled explicitly regardless of what208 # prefixes are valid.209 if arg == '--':210 return211 elif arg[:1] in self._opt_prefixes and arglen > 1:
46 unmodified lines
258 self._error('no such option: %s. (Possible options: %s)'259 % (opt, ', '.join(possibilities)))260261 def _process_long_opt(self, arg, state):262 # Value explicitly attached to arg? Pretend it's the next263 # argument.262 # Value explicitly attached to arg? Pretend it's the next argument.263 if '=' in arg:264 opt, next_arg = arg.split('=', 1)265 state.rargs.insert(0, next_arg)266 had_explicit_value = True
71 unmodified lines
modified:click/termui.py+18 added-18 removed
34 unmodified lines
35 value_proc=None, prompt_suffix=': ', show_default=True):36 """Prompts a user for input. This is a convenience function that can37 be used to prompt a user for input later.3839 If the user aborts the input by sending a interrupt signal this39 If the user aborts the input by sending a interrupt signal, this40 function will catch it and raise a :exc:`Abort` exception.4142 :param text: the text to show for the prompt.43 :param default: the default value to use if no input happens. If this
147 unmodified lines
191 info_sep=' ', width=36, file=None):192 """This function creates an iterable context manager that can be used193 to iterate over something while showing a progress bar. It will194 either iterate over the `iterable` or `length` items (that are counted195 up). While iteration happens this function will print a rendered195 up). While iteration happens, this function will print a rendered196 progress bar to the given `file` (defaults to stdout) and will attempt197 to calculate remaining time and more. By default this progress bar197 to calculate remaining time and more. By default, this progress bar198 will not be rendered if the file is not a terminal.199200 The context manager creates the progress bar. When the context201 manager is entered the progress bar is already displayed. With every202 iteration over the progress bar the iterable passed to the bar is203 advanced and the bar is updated. When the context manager exits202 iteration over the progress bar, the iterable passed to the bar is203 advanced and the bar is updated. When the context manager exits,204 a newline is printed and the progress bar is finalized on screen.205206 No printing must happen or the progress bar will be unintentionally207 destroyed.
169 unmodified lines
377 extension='.txt', filename=None):378 r"""Edits the given text in the defined editor. If an editor is given379 (should be the full path to the executable but the regular operating380 system search path is used for finding the executable) it overrides381 the detected editor. Optionally some environment variables can be382 used. If the editor is closed without changes `None` is returned. In381 the detected editor. Optionally, some environment variables can be382 used. If the editor is closed without changes, `None` is returned. In383 case a file is edited directly the return value is always `None` and384 `require_save` and `extension` are ignored.385386 If the editor cannot be opened a :exc:`UsageError` is raised.387388 Note for Windows: to simplify cross platform usage the newlines are389 automatically converted from POSIX to Windows and reverse. As such the390 message here will have ``\n`` as newline markers.388 Note for Windows: to simplify cross-platform usage, the newlines are389 automatically converted from POSIX to Windows and vice versa. As such,390 the message here will have ``\n`` as newline markers.391392 :param text: the text to edit.393 :param editor: optionally the editor to use. Defaults to automatic394 detection.
16 unmodified lines
411412413def launch(url, wait=False, locate=False):414 """This function launches the given URL (or filename) in the default415 viewer application for this file type. If this is an executable it415 viewer application for this file type. If this is an executable, it416 might launch the executable in a new session. The return value is417 the exit code of the launched application. Usually ``0`` indicates417 the exit code of the launched application. Usually, ``0`` indicates418 success.419420 Examples::421
1 unmodified line
423 click.launch('/my/downloaded/file', locate=True)424425 .. versionadded:: 2.0426427 :param url: url or filename of the thing to launch.427 :param url: URL or filename of the thing to launch.428 :param wait: waits for the program to stop.429 :param locate: if this is set to `True` then instead of launching the430 application associated with the URL it will attempt to431 launch a file manager with the file located. This432 might have weird effects if the url does not point to432 might have weird effects if the URL does not point to433 the filesystem.434 """435 from ._termui_impl import open_url436 return open_url(url, wait=wait, locate=locate)
16 unmodified lines
453 is piped into the standard input.454455 .. versionadded:: 2.0456457 :param echo: if set to `True` the character read will also show up on458 the terminal. The default is not not show it.457 :param echo: if set to `True`, the character read will also show up on458 the terminal. The default is to not show it.459 """460 f = _getchar461 if f is None:462 from ._termui_impl import getchar as f
2 unmodified lines
465466def pause(info='Press any key to continue ...'):467 """This command stops execution and waits for the user to press any468 key to continue. This is similar to the Windows batch "pause"469 command. If the program is not run through a terminal this command470 will do nothing instead.469 command. If the program is not run through a terminal, this command470 will instead do nothing.471472 .. versionadded:: 2.0473474 :param info: the info string to print before pausing.
13 unmodified lines
modified:click/testing.py+7 added-7 removed
87 unmodified lines
88 )899091class CliRunner(object):92 """The CLI runner provides functionality to invoke a Click command line92 """The CLI runner provides functionality to invoke a click command line93 script for unittesting purposes in a isolated environment. This only94 works in single-threaded systems without any concurrency as it changes94 works in single-threaded systems without any concurrency as it changes the95 global interpreter state.9697 :param charset: the character set for the input and output data. This is98 utf-8 by default and should not be changed currently as99 the reporting to click only works on Python 2 properly.98 UTF-8 by default and should not be changed currently as99 the reporting to click only works in Python 2 properly.100 :param env: a dictionary with environment variables for overriding.101 :param echo_stdin: if this is set to `True`, then reading from stdin writes102 to stdout. This is useful for showing examples in103 some circumstances. Note that regular prompts
22 unmodified lines
126 return rv127128 @contextlib.contextmanager129 def isolation(self, input=None, env=None):130 """A context manager that set up the isolation for invoking of a131 command line tool. This sets up stdin with the given input data,130 """A context manager that sets up the isolation for invoking of a131 command line tool. This sets up stdin with the given input data132 and `os.environ` with the overrides from the given dictionary.133 This also rebinds some internals in Click to be mocked (like the133 This also rebinds some internals in click to be mocked (like the134 prompt functionality).135136 This is automatically done in the :meth:`invoke` method.137
131 unmodified lines
modified:click/types.py+9 added-9 removed
14 unmodified lines
15 * it needs to pass through None unchanged16 * it needs to convert from a string17 * it needs to convert its result type through unchanged18 (eg: needs to be idempotent)19 * it needs to be able to deal with param and context being none.19 * it needs to be able to deal with param and context being `None`.20 This can be the case when the object is used with prompt21 inputs.22 """23
3 unmodified lines
27 #: if a list of this type is expected and the value is pulled from a28 #: string environment variable, this is what splits it up. `None`29 #: means any whitespace. For all parameters the general rule is that30 #: whitespace splits them up. The exception are paths and files which31 #: are split by ``os.path.pathsep`` by default (":" on unix and ";" on31 #: are split by ``os.path.pathsep`` by default (":" on Unix and ";" on32 #: Windows).33 envvar_list_splitter = None3435 def __call__(self, value, param=None, ctx=None):
12 unmodified lines
48 def split_envvar_value(self, rv):49 """Given a value from an environment variable this splits it up50 into small chunks depending on the defined envvar list splitter.5152 If the splitter is set to `None` which means that whitespace splits,53 then leading and trailing whitespace is ignored. Otherwise leading52 If the splitter is set to `None`, which means that whitespace splits,53 then leading and trailing whitespace is ignored. Otherwise, leading54 and trailing splitters usually lead to empty items being included.55 """56 return (rv or '').split(self.envvar_list_splitter)57
168 unmodified lines
226227 Files can be opened for reading or writing. The special value ``-``228 indicates stdin or stdout depending on the mode.229230 By default the file is opened for reading text data but it can also be230 By default, the file is opened for reading text data, but it can also be231 opened in binary mode or for writing. The encoding parameter can be used232 to force a specific encoding.233234 The `lazy` flag controls if the file should be opened immediately or235 upon first IO. The default is to be non lazy for standard input and236 output streams as well as files opened for reading, lazy otherwise.237238 Starting with click 2.0 files can also be opened atomically in which238 Starting with click 2.0, files can also be opened atomically in which239 case all writes go into a separate file in the same folder and upon240 completion the file will be moved over to the original location. This241 is useful if a file regularly read by other users is modified.242
35 unmodified lines
278279 f, should_close = open_stream(value, self.mode,280 self.encoding, self.errors,281 atomic=self.atomic)282 # If a context is provided we automatically close the file282 # If a context is provided, we automatically close the file283 # at the end of the context execution (or flush out). If a284 # context does not exist it's the caller's responsibility to284 # context does not exist, it's the caller's responsibility to285 # properly close the file. This for instance happens when the286 # type is used with prompts.287 if ctx is not None:288 if should_close:
10 unmodified lines
299300class Path(ParamType):301 """The path type is similar to the :class:`File` type but it performs302 different checks. First of all, instead of returning a open file303 handle it returns just the filename. Secondly it can perform various303 handle it returns just the filename. Secondly, it can perform various304 basic checks about what the file or directory should be.305306 :param exists: if set to true, the file or directory needs to exist for307 this value to be valid. If this is not required and a
124 unmodified lines
modified:click/utils.py+14 added-14 removed
17 unmodified lines
18 return '-'.join(name.split()).lower()192021def unpack_args(args, nargs_spec):22 """Given an iterable of arguments and an iterable of nargs specifications22 """Given an iterable of arguments and an iterable of nargs specifications,23 it returns a tuple with all the unpacked arguments at the first index24 and all remaining arguments as the second.2526 The nargs specification is the number of arguments that should be consumed
28 unmodified lines
55 if nargs == 1:56 rv.append(_fetch(args))57 elif nargs > 1:58 x = [_fetch(args) for _ in range(nargs)]59 # If we're reversed we're pulling in the arguments in reverse59 # If we're reversed, we're pulling in the arguments in reverse,60 # so we need to turn them around.61 if spos is not None:62 x.reverse()63 rv.append(tuple(x))
2 unmodified lines
66 raise TypeError('Cannot have two nargs < 0')67 spos = len(rv)68 rv.append(None)6970 # spos is the position of the wildcard (star). If it's not None70 # spos is the position of the wildcard (star). If it's not `None`,71 # we fill it with the remainder.72 if spos is not None:73 rv[spos] = tuple(args)74 args = []
119 unmodified lines
194195196def echo(message=None, file=None, nl=True):197 """Prints a message plus a newline to the given file or stdout. On198 first sight this looks like the print function but it has improved199 support for handling unicode and binary data that does not fail no198 first sight, this looks like the print function, but it has improved199 support for handling Unicode and binary data that does not fail no200 matter how badly configured the system is.201202 Primarily it means that you can print binary data as well as unicode202 Primarily it means that you can print binary data as well as Unicode203 data on both 2.x and 3.x to the given file in the most appropriate way204 possible. This is a very carefree function as in that it will try its205 best to not fail.206207 In addition to that if `colorama`_ is installed the echo function will207 In addition to that, if `colorama`_ is installed, the echo function will208 also support clever handling of ANSI codes. Essentially it will then209 do the following:210211 - add transparent handling of ANSI color codes on Windows.
16 unmodified lines
228 # Convert non bytes/text into the native string type.229 if message is not None and not isinstance(message, echo_native_types):230 message = text_type(message)231232 # If there is a message, and we're on python 3, and the value looks233 # like bytes we manually need to find the binary stream and write the232 # If there is a message, and we're in Python 3, and the value looks233 # like bytes, we manually need to find the binary stream and write the234 # message in there. This is done separately so that most stream235 # types will work as you would expect. Eg: you can write to StringIO236 # for other cases.237 if message and not PY2 and is_bytes(message):
5 unmodified lines
243 binary_file.write(b'\n')244 binary_file.flush()245 return246247 # ANSI style support. If there is no message or we are dealing with247 # ANSI-style support. If there is no message or we are dealing with248 # bytes nothing is happening. If we are connected to a file we want249 # to strip colors. If we have support for wrapping streams (windows250 # through colorama) we want to do that.251 if message and not is_bytes(message):
45 unmodified lines
297def format_filename(filename, shorten=False):298 """Formats a filename for user display. The main purpose of this299 function is to ensure that the filename can be displayed at all. This300 will decode the filename to unicode if necessary in a way that it will301 not fail. Optionally it can shorten the filename to not include the301 not fail. Optionally, it can shorten the filename to not include the302 full path to the filename.303304 :param filename: formats a filename for UI display. This will also convert305 the filename into unicode without failing.
8 unmodified lines
314def get_app_dir(app_name, roaming=True, force_posix=False):315 r"""Returns the config folder for the application. The default behavior316 is to return whatever is most appropriate for the operating system.317318 To give you an idea, for an app called ``"Foo Bar"`` something like318 To give you an idea, for an app called ``"Foo Bar"``, something like319 the following folders could be returned:320321 Mac OS X:322 ``~/Library/Application Support/Foo Bar``
15 unmodified lines
338 .. versionadded:: 2.0339340 :param app_name: the application name. This should be properly capitalized341 and can contain whitespace.342 :param roaming: controls if the folder should be roaming or not on windows.342 :param roaming: controls if the folder should be roaming or not on Windows.343 Has no affect otherwise.344 :param force_posix: if this is set to `True` then on any posix system the344 :param force_posix: if this is set to `True` then on any POSIX system the345 folder will be stored in the home folder with a leading346 dot instead of the XDG config home or darwin's347 application support folder.348 """
14 unmodified lines
modified:docs/api.rst+1 added-1 removed
1 unmodified line
2===34.. module:: click56This part of the documentation shows the full API reference of all public6This part of the documentation lists the full API reference of all public7classes and functions.89Decorators10----------
157 unmodified lines
modified:docs/complex.rst+10 added-10 removed
30 unmodified lines
31at the end of the function, and so forth. It can also optionally hold an32application-defined object.3334Context objects build a linked list until they hit the top one. Each context35is linked to the parent context. This allows a command to work below35is linked to a parent context. This allows a command to work below36another command and store its own information there without having to be37afraid of altering up the state of the parent command.3839Because the parent data is available, however, it is possible to navigate to
6 unmodified lines
46``````````````````4748When a click command callback is executed, it's passed all the non-hidden49parameters as keyword arguments. Notably absent is the context. However,50a callback can opt into being passed the context object by marking itself50a callback can opt into being passed to the context object by marking itself51with :func:`pass_context`.5253So how do you invoke a command callback if you don't know if it should54receive the context or not? The answer is that the context itself
39 unmodified lines
94 def cli(ctx, repo_home, debug):95 ctx.obj = Repo(repo_home, debug)969798So let's understand what this does. We create a group command which can98Let's understand what this does. We create a group command which can99have subcommands. When it is invoked, it will create an instance of a100``Repo`` class. This holds the state for our command line tool. In this101case, it just remembers some parameters, but at this point it could also102start loading configuration files and so on.103104This state object is then remembered as :attr:`~Context.obj` on the105context. This is a special attribute where commands are supposed to106remember what they need to pass on to their children.104This state object is then remembered by the context as :attr:`~Context.obj`.105This is a special attribute where commands are supposed to remember what106they need to pass on to their children.107108In order for this to work, we need to mark our function with109:func:`pass_context`, because otherwise the context object would be109:func:`pass_context`, because otherwise, the context object would be110entirely hidden from us.111112The First Child Command113```````````````````````
41 unmodified lines
155156There is a much better system that can built by taking advantage of the linked157nature of contexts. We know that the plugin context is linked to the context158that created our repo. Because of that, we can start a search for the last159level where the object stored on the context was a repo.159level where the object stored by the context was a repo.160161Built-in support for this is provided by the :func:`make_pass_decorator`162factory, which will create decorators for us that find objects (it163internally calls into :meth:`Context.find_object`). In our case, we
19 unmodified lines
183Ensuring Object Creation184````````````````````````185186The above example only works if there was an outer command that created a187``Repo`` object and stored it on the context. For some more advanced use187``Repo`` object and stored it in the context. For some more advanced use188cases, this might become a problem. The default behavior of189:func:`make_pass_decorator` is to call :meth:`Context.find_object`190which will find the object. If it can't find the object, it will raise an191error. The alternative behavior is to use :meth:`Context.ensure_object`192which will find the object, and if it cannot find it, will create one and193store it on the innermost context. This behavior can also be enabled for193store it in the innermost context. This behavior can also be enabled for194:func:`make_pass_decorator` by passing ``ensure=True``:195196.. click:example::197
22 unmodified lines
modified:docs/options.rst+2 added-2 removed
329 unmodified lines
330331The `expose_value` parameter prevents the pretty pointless ``version``332parameter from being passed to the callback. If that was not specified, a333boolean would be passed to the `hello` script. The `resilient_parsing`334flag is set on the context if click wants to parse the command line334flag is applied to the context if click wants to parse the command line335without and destructive behavior that would change the execution flow. In336this case, because we would exit the program, we instead do nothing.337338What it looks like:
124 unmodified lines
463464The default implementation for all types is to split on whitespace. The465exceptions to this rule are the :class:`File` and :class:`Path` types466which both split according to the operating system's path splitting rules.467On UNIX systems like Linux and OS X, the splitting happens for those on467On Unix systems like Linux and OS X, the splitting happens for those on468every colon (``:``), and for Windows, on every semicolon (``;``).469470Example usage:471
137 unmodified lines
modified:docs/python3.rst+9 added-9 removed
22 unmodified lines
23 some situations where this can break. The most common one is SSH24 connections to machines with different locales.2526 Misconfigured environments can currently cause a wide range of Unicode27 problems on Python 3 due to the lack of support for roundtripping27 problems in Python 3 due to the lack of support for roundtripping28 surrogate escapes. This will not be fixed in click itself!2930 For more information see :ref:`python3-surrogates`.3132* Standard input and output on Python 3 is opened in Unicode mode by32* Standard input and output in Python 3 is opened in Unicode mode by33 default. Click has to reopen the stream in binary mode in certain34 situations. Because there is no standardized way to do this, this35 might not always work. Primarily this can become a problem when36 testing command-line applications.
20 unmodified lines
5758Click attempts to minimize the differences between Python 2 and Python 359by following the best practices for both languages.6061On Python 2, the following is true:61in Python 2, the following is true:6263* ``sys.stdin``, ``sys.stdout``, and ``sys.stderr`` are opened in binary64 mode, but under some circumstances they support Unicode output. Click65 attempts to not subvert this but provides support for forcing streams
5 unmodified lines
71* When dealing with files, click will never go through the Unicode APIs72 and will instead use the operating system's byte APIs to open the73 files.7475On Python 3, the following is true:75in Python 3, the following is true:7677* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default78 text-based. When click needs a binary stream, it attempts to discover79 the underlying binary stream. See :ref:`python3-limitations` for how
14 unmodified lines
9495Python 3 Surrogate Handling96---------------------------9798Click on Python 3 does all the Unicode handling in the standard library99and is subject to its behavior. On Python 2, click does all the Unicode98Click in Python 3 does all the Unicode handling in the standard library99and is subject to its behavior. In Python 2, click does all the Unicode100handling itself, which means there are differences in error behavior.101102The most glaring difference is that on Python 2, Unicode will "just work",103while on Python 3, it requires extra care. The reason for this is that on102The most glaring difference is that in Python 2, Unicode will "just work",103while in Python 3, it requires extra care. The reason for this is that on104Python 3, the encoding detection is done in the interpreter and on Linux105and certain other operating systems its encoding handling is problematic.106107The biggest source of frustration is that click scripts invoked by
5 unmodified lines
113to force you to set a locale. This is done because click cannot know114about the state of the system once it's invoked and restore the values115before Python's Unicode handling kicked in.116117If you see something like this error on Python 3::117If you see something like this error in Python 3::118119 Traceback (most recent call last):120 ...121 RuntimeError: Click will abort further execution because Python 3 was
33 unmodified lines
modified:docs/setuptools.rst+2 added-2 removed
2 unmodified lines
3Usage with Setuptools4=====================56When writing command line utilities, it's recommended to write them as7modules that are distributed with setuptools instead of using UNIX7modules that are distributed with setuptools instead of using Unix8shebangs. There are many reasons for this.910The first one is that setuptools automatically generates executable11wrappers for Windows so your command line utilities work on Windows too.1213The second reason is that setuptools scripts work with virtualenv on UNIX13The second reason is that setuptools scripts work with virtualenv on Unix14without the virtualenv having to be activated. This is a very useful15concept which allows you to bundle your scripts with all requirements into16a virtualenv.17
64 unmodified lines
modified:docs/utils.rst+6 added-6 removed
11 unmodified lines
12------------------1314The most obvious helper is the :func:`echo` function, which in many ways15works like the Python print statement or function. The main difference is16that it works the same on Python 2 and 3, it intelligently detects17misconfigured output streams, and will never fail (except on Python 3; for16that it works the same in Python 2 and 3, it intelligently detects17misconfigured output streams, and will never fail (except in Python 3; for18more information see :ref:`python3-limitations`).1920Example::21
1 unmodified line
2324 click.echo('Hello World!')2526Most importantly, it can print both Unicode and binary data, unlike the27builtin ``print`` function on Python 3, which cannot output any bytes. It27builtin ``print`` function in Python 3, which cannot output any bytes. It28will, however, emit a trailing newline by default which needs to be29supressed by passing ``nl=False``::3031 click.echo(b'\xe2\x98\x83', nl=False)
188 unmodified lines
220Printing Filenames221------------------222223Because filenames might not be Unicode, formatting them can be a bit224tricky. Generally, this is easier on Python 2 than on 3, as you can just225write the bytes to stdout with the print function, but on Python 3, you will224tricky. Generally, this is easier in Python 2 than on 3, as you can just225write the bytes to stdout with the print function, but in Python 3, you will226always need to operate in Unicode.227228The way this works with click is through the :func:`format_filename`229function. It does a best-effort conversion of the filename to Unicode and
18 unmodified lines
248:func:`get_text_stream` functions, which produce consistent results with249different Python versions and for a wide variety pf terminal configurations.250251The end result is that these functions will always return a functional252stream object (except in very odd cases on Python 3; see252stream object (except in very odd cases in Python 3; see253:ref:`python3-limitations`).254255Example::256
80 unmodified lines
modified:docs/why.rst+2 added-2 removed
6 unmodified lines
7This question is easy to answer: because there is not a single command8line utility for Python out there which ticks the following boxes:910* is lazily composable without restrictions11* fully follows the UNIX command line conventions11* fully follows the Unix command line conventions12* supports loading values from environment variables out of the box13* supports for prompting of custom values14* is fully nestable and composable15* works the same on Python 2 and 315* works the same in Python 2 and 316* supports file handling out of the box17* comes with useful common helpers (getting terminal dimensions,18 ANSI colors, fetching direct keyboard input, screen clearing,19 finding config paths, launching apps and editors, etc.)
133 unmodified lines
modified:examples/inout/inout.py+1 added-1 removed
3 unmodified lines
4@click.command()5@click.argument('input', type=click.File('rb'), nargs=-1)6@click.argument('output', type=click.File('wb'))7def cli(input, output):8 """This script works similar to the unix `cat` command but it writes8 """This script works similar to the Unix `cat` command but it writes9 into a specific file (which could be the standard output as denoted by10 the ``-`` sign).1112 \b
18 unmodified lines
modified:tests/test_utils.py+2 added-2 removed
10 unmodified lines
11 click.echo('\x1b[31mx\x1b[39m', nl=False)12 bytes = out.getvalue()13 assert bytes == b'\xe2\x98\x83\nDD\n42ax'1415 # If we are on python 2 we expect that writing bytes into a string io16 # does not do anything crazy. On Python 315 # If we are in Python 2, we expect that writing bytes into a string io16 # does not do anything crazy. In Python 317 if sys.version_info[0] == 2:18 import StringIO19 sys.stdout = x = StringIO.StringIO()20 try:
93 unmodified lines
modified:CHANGES+1 added-1 removed
43 unmodified lines
44-----------4546(bugfix release, released on May 23rd 2014)4748- fixed a bug that caused text files on Python 2 to not accept48- fixed a bug that caused text files in Python 2 to not accept49 native strings.5051Version 1.052-----------
4 unmodified lines