author | Andrew Halberstadt <ahalberstadt@mozilla.com> |
Tue, 23 Jun 2020 12:43:14 +0000 | |
changeset 536889 | b8c61efea3cec1cc928eb7a67e2714a277793494 |
parent 536888 | 6d5f6fbef8d48cada57aeaf7155610dcdcb981c9 |
child 536890 | 38c7488100c697a5c39c9766283f2537962180a0 |
push id | 37533 |
push user | dluca@mozilla.com |
push date | Tue, 23 Jun 2020 21:38:40 +0000 |
treeherder | mozilla-central@d48aa0f0aa0b [default view] [failures only] |
perfherder | [talos] [build metrics] [platform microbench] (compared to previous push) |
reviewers | rstewart |
bugs | 1646427 |
milestone | 79.0a1 |
first release with | nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
|
last release without | nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
|
deleted file mode 100644 --- a/third_party/python/Click/docs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ -# Minimal makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -SPHINXPROJ = Jinja -SOURCEDIR = . -BUILDDIR = _build - -# Put it first so that "make" without argument is like "make help". -help: - @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) - -.PHONY: help Makefile - -# Catch-all target: route all unknown targets to Sphinx using the new -# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). -%: Makefile - @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
deleted file mode 100644 index b883cfaa17f0ac31dd52effb9aaf6fe58feede06..0000000000000000000000000000000000000000 GIT binary patch literal 0 Hc$@<O00001
deleted file mode 100644 index 4c2bc07a8dfbb1ff2ac81b1b3447249539713a3c..0000000000000000000000000000000000000000 GIT binary patch literal 0 Hc$@<O00001
deleted file mode 100644 index a8874506885e8a101d24789ce7033634d895eb77..0000000000000000000000000000000000000000 GIT binary patch literal 0 Hc$@<O00001
deleted file mode 100644 --- a/third_party/python/Click/docs/advanced.rst +++ /dev/null @@ -1,379 +0,0 @@ -Advanced Patterns -================= - -.. currentmodule:: click - -In addition to common functionality that is implemented in the library -itself, there are countless patterns that can be implemented by extending -Click. This page should give some insight into what can be accomplished. - -.. _aliases: - -Command Aliases ---------------- - -Many tools support aliases for commands. For instance, you can configure -``git`` to accept ``git ci`` as alias for ``git commit``. Other tools -also support auto-discovery for aliases by automatically shortening them. - -Click does not support this out of the box, but it's very easy to customize -the :class:`Group` or any other :class:`MultiCommand` to provide this -functionality. - -As explained in :ref:`custom-multi-commands`, a multi command can provide -two methods: :meth:`~MultiCommand.list_commands` and -:meth:`~MultiCommand.get_command`. In this particular case, you only need -to override the latter as you generally don't want to enumerate the -aliases on the help page in order to avoid confusion. - -This following example implements a subclass of :class:`Group` that -accepts a prefix for a command. If there were a command called ``push``, -it would accept ``pus`` as an alias (so long as it was unique): - -.. click:example:: - - class AliasedGroup(click.Group): - - def get_command(self, ctx, cmd_name): - rv = click.Group.get_command(self, ctx, cmd_name) - if rv is not None: - return rv - matches = [x for x in self.list_commands(ctx) - if x.startswith(cmd_name)] - if not matches: - return None - elif len(matches) == 1: - return click.Group.get_command(self, ctx, matches[0]) - ctx.fail('Too many matches: %s' % ', '.join(sorted(matches))) - -And it can then be used like this: - -.. click:example:: - - @click.command(cls=AliasedGroup) - def cli(): - pass - - @cli.command() - def push(): - pass - - @cli.command() - def pop(): - pass - -Parameter Modifications ------------------------ - -Parameters (options and arguments) are forwarded to the command callbacks -as you have seen. One common way to prevent a parameter from being passed -to the callback is the `expose_value` argument to a parameter which hides -the parameter entirely. The way this works is that the :class:`Context` -object has a :attr:`~Context.params` attribute which is a dictionary of -all parameters. Whatever is in that dictionary is being passed to the -callbacks. - -This can be used to make up addition parameters. Generally this pattern -is not recommended but in some cases it can be useful. At the very least -it's good to know that the system works this way. - -.. click:example:: - - import urllib - - def open_url(ctx, param, value): - if value is not None: - ctx.params['fp'] = urllib.urlopen(value) - return value - - @click.command() - @click.option('--url', callback=open_url) - def cli(url, fp=None): - if fp is not None: - click.echo('%s: %s' % (url, fp.code)) - -In this case the callback returns the URL unchanged but also passes a -second ``fp`` value to the callback. What's more recommended is to pass -the information in a wrapper however: - -.. click:example:: - - import urllib - - class URL(object): - - def __init__(self, url, fp): - self.url = url - self.fp = fp - - def open_url(ctx, param, value): - if value is not None: - return URL(value, urllib.urlopen(value)) - - @click.command() - @click.option('--url', callback=open_url) - def cli(url): - if url is not None: - click.echo('%s: %s' % (url.url, url.fp.code)) - - -Token Normalization -------------------- - -.. versionadded:: 2.0 - -Starting with Click 2.0, it's possible to provide a function that is used -for normalizing tokens. Tokens are option names, choice values, or command -values. This can be used to implement case insensitive options, for -instance. - -In order to use this feature, the context needs to be passed a function that -performs the normalization of the token. For instance, you could have a -function that converts the token to lowercase: - -.. click:example:: - - CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower()) - - @click.command(context_settings=CONTEXT_SETTINGS) - @click.option('--name', default='Pete') - def cli(name): - click.echo('Name: %s' % name) - -And how it works on the command line: - -.. click:run:: - - invoke(cli, prog_name='cli', args=['--NAME=Pete']) - -Invoking Other Commands ------------------------ - -Sometimes, it might be interesting to invoke one command from another -command. This is a pattern that is generally discouraged with Click, but -possible nonetheless. For this, you can use the :func:`Context.invoke` -or :func:`Context.forward` methods. - -They work similarly, but the difference is that :func:`Context.invoke` merely -invokes another command with the arguments you provide as a caller, -whereas :func:`Context.forward` fills in the arguments from the current -command. Both accept the command as the first argument and everything else -is passed onwards as you would expect. - -Example: - -.. click:example:: - - cli = click.Group() - - @cli.command() - @click.option('--count', default=1) - def test(count): - click.echo('Count: %d' % count) - - @cli.command() - @click.option('--count', default=1) - @click.pass_context - def dist(ctx, count): - ctx.forward(test) - ctx.invoke(test, count=42) - -And what it looks like: - -.. click:run:: - - invoke(cli, prog_name='cli', args=['dist']) - - -.. _callback-evaluation-order: - -Callback Evaluation Order -------------------------- - -Click works a bit differently than some other command line parsers in that -it attempts to reconcile the order of arguments as defined by the -programmer with the order of arguments as defined by the user before -invoking any callbacks. - -This is an important concept to understand when porting complex -patterns to Click from optparse or other systems. A parameter -callback invocation in optparse happens as part of the parsing step, -whereas a callback invocation in Click happens after the parsing. - -The main difference is that in optparse, callbacks are invoked with the raw -value as it happens, whereas a callback in Click is invoked after the -value has been fully converted. - -Generally, the order of invocation is driven by the order in which the user -provides the arguments to the script; if there is an option called ``--foo`` -and an option called ``--bar`` and the user calls it as ``--bar ---foo``, then the callback for ``bar`` will fire before the one for ``foo``. - -There are three exceptions to this rule which are important to know: - -Eagerness: - An option can be set to be "eager". All eager parameters are - evaluated before all non-eager parameters, but again in the order as - they were provided on the command line by the user. - - This is important for parameters that execute and exit like ``--help`` - and ``--version``. Both are eager parameters, but whatever parameter - comes first on the command line will win and exit the program. - -Repeated parameters: - If an option or argument is split up on the command line into multiple - places because it is repeated -- for instance, ``--exclude foo --include - baz --exclude bar`` -- the callback will fire based on the position of - the first option. In this case, the callback will fire for - ``exclude`` and it will be passed both options (``foo`` and - ``bar``), then the callback for ``include`` will fire with ``baz`` - only. - - Note that even if a parameter does not allow multiple versions, Click - will still accept the position of the first, but it will ignore every - value except the last. The reason for this is to allow composability - through shell aliases that set defaults. - -Missing parameters: - If a parameter is not defined on the command line, the callback will - still fire. This is different from how it works in optparse where - undefined values do not fire the callback. Missing parameters fire - their callbacks at the very end which makes it possible for them to - default to values from a parameter that came before. - -Most of the time you do not need to be concerned about any of this, -but it is important to know how it works for some advanced cases. - -.. _forwarding-unknown-options: - -Forwarding Unknown Options --------------------------- - -In some situations it is interesting to be able to accept all unknown -options for further manual processing. Click can generally do that as of -Click 4.0, but it has some limitations that lie in the nature of the -problem. The support for this is provided through a parser flag called -``ignore_unknown_options`` which will instruct the parser to collect all -unknown options and to put them to the leftover argument instead of -triggering a parsing error. - -This can generally be activated in two different ways: - -1. It can be enabled on custom :class:`Command` subclasses by changing - the :attr:`~BaseCommand.ignore_unknown_options` attribute. -2. It can be enabled by changing the attribute of the same name on the - context class (:attr:`Context.ignore_unknown_options`). This is best - changed through the ``context_settings`` dictionary on the command. - -For most situations the easiest solution is the second. Once the behavior -is changed something needs to pick up those leftover options (which at -this point are considered arguments). For this again you have two -options: - -1. You can use :func:`pass_context` to get the context passed. This will - only work if in addition to :attr:`~Context.ignore_unknown_options` - you also set :attr:`~Context.allow_extra_args` as otherwise the - command will abort with an error that there are leftover arguments. - If you go with this solution, the extra arguments will be collected in - :attr:`Context.args`. -2. You can attach a :func:`argument` with ``nargs`` set to `-1` which - will eat up all leftover arguments. In this case it's recommended to - set the `type` to :data:`UNPROCESSED` to avoid any string processing - on those arguments as otherwise they are forced into unicode strings - automatically which is often not what you want. - -In the end you end up with something like this: - -.. click:example:: - - import sys - from subprocess import call - - @click.command(context_settings=dict( - ignore_unknown_options=True, - )) - @click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode') - @click.argument('timeit_args', nargs=-1, type=click.UNPROCESSED) - def cli(verbose, timeit_args): - """A fake wrapper around Python's timeit.""" - cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args) - if verbose: - click.echo('Invoking: %s' % ' '.join(cmdline)) - call(cmdline) - -And what it looks like: - -.. click:run:: - - invoke(cli, prog_name='cli', args=['--help']) - println() - invoke(cli, prog_name='cli', args=['-n', '100', 'a = 1; b = 2; a * b']) - println() - invoke(cli, prog_name='cli', args=['-v', 'a = 1; b = 2; a * b']) - -As you can see the verbosity flag is handled by Click, everything else -ends up in the `timeit_args` variable for further processing which then -for instance, allows invoking a subprocess. There are a few things that -are important to know about how this ignoring of unhandled flag happens: - -* Unknown long options are generally ignored and not processed at all. - So for instance if ``--foo=bar`` or ``--foo bar`` are passed they - generally end up like that. Note that because the parser cannot know - if an option will accept an argument or not, the ``bar`` part might be - handled as an argument. -* Unknown short options might be partially handled and reassembled if - necessary. For instance in the above example there is an option - called ``-v`` which enables verbose mode. If the command would be - ignored with ``-va`` then the ``-v`` part would be handled by Click - (as it is known) and ``-a`` would end up in the leftover parameters - for further processing. -* Depending on what you plan on doing you might have some success by - disabling interspersed arguments - (:attr:`~Context.allow_interspersed_args`) which instructs the parser - to not allow arguments and options to be mixed. Depending on your - situation this might improve your results. - -Generally though the combinated handling of options and arguments from -your own commands and commands from another application are discouraged -and if you can avoid it, you should. It's a much better idea to have -everything below a subcommand be forwarded to another application than to -handle some arguments yourself. - - -Global Context Access ---------------------- - -.. versionadded:: 5.0 - -Starting with Click 5.0 it is possible to access the current context from -anywhere within the same thread through the use of the -:func:`get_current_context` function which returns it. This is primarily -useful for accessing the context bound object as well as some flags that -are stored on it to customize the runtime behavior. For instance the -:func:`echo` function does this to infer the default value of the `color` -flag. - -Example usage:: - - def get_current_command_name(): - return click.get_current_context().info_name - -It should be noted that this only works within the current thread. If you -spawn additional threads then those threads will not have the ability to -refer to the current context. If you want to give another thread the -ability to refer to this context you need to use the context within the -thread as a context manager:: - - def spawn_thread(ctx, func): - def wrapper(): - with ctx: - func() - t = threading.Thread(target=wrapper) - t.start() - return t - -Now the thread function can access the context like the main thread would -do. However if you do use this for threading you need to be very careful -as the vast majority of the context is not thread safe! You are only -allowed to read from the context, but not to perform any modifications on -it.
deleted file mode 100644 --- a/third_party/python/Click/docs/api.rst +++ /dev/null @@ -1,181 +0,0 @@ -API -=== - -.. module:: click - -This part of the documentation lists the full API reference of all public -classes and functions. - -Decorators ----------- - -.. autofunction:: command - -.. autofunction:: group - -.. autofunction:: argument - -.. autofunction:: option - -.. autofunction:: password_option - -.. autofunction:: confirmation_option - -.. autofunction:: version_option - -.. autofunction:: help_option - -.. autofunction:: pass_context - -.. autofunction:: pass_obj - -.. autofunction:: make_pass_decorator - -Utilities ---------- - -.. autofunction:: echo - -.. autofunction:: echo_via_pager - -.. autofunction:: prompt - -.. autofunction:: confirm - -.. autofunction:: progressbar - -.. autofunction:: clear - -.. autofunction:: style - -.. autofunction:: unstyle - -.. autofunction:: secho - -.. autofunction:: edit - -.. autofunction:: launch - -.. autofunction:: getchar - -.. autofunction:: pause - -.. autofunction:: get_terminal_size - -.. autofunction:: get_binary_stream - -.. autofunction:: get_text_stream - -.. autofunction:: open_file - -.. autofunction:: get_app_dir - -.. autofunction:: format_filename - -Commands --------- - -.. autoclass:: BaseCommand - :members: - -.. autoclass:: Command - :members: - -.. autoclass:: MultiCommand - :members: - -.. autoclass:: Group - :members: - -.. autoclass:: CommandCollection - :members: - -Parameters ----------- - -.. autoclass:: Parameter - :members: - -.. autoclass:: Option - -.. autoclass:: Argument - -Context -------- - -.. autoclass:: Context - :members: - -.. autofunction:: get_current_context - -Types ------ - -.. autodata:: STRING - -.. autodata:: INT - -.. autodata:: FLOAT - -.. autodata:: BOOL - -.. autodata:: UUID - -.. autodata:: UNPROCESSED - -.. autoclass:: File - -.. autoclass:: Path - -.. autoclass:: Choice - -.. autoclass:: IntRange - -.. autoclass:: Tuple - -.. autoclass:: ParamType - :members: - -Exceptions ----------- - -.. autoexception:: ClickException - -.. autoexception:: Abort - -.. autoexception:: UsageError - -.. autoexception:: BadParameter - -.. autoexception:: FileError - -.. autoexception:: NoSuchOption - -.. autoexception:: BadOptionUsage - -.. autoexception:: BadArgumentUsage - -Formatting ----------- - -.. autoclass:: HelpFormatter - :members: - -.. autofunction:: wrap_text - -Parsing -------- - -.. autoclass:: OptionParser - :members: - -Testing -------- - -.. currentmodule:: click.testing - -.. autoclass:: CliRunner - :members: - -.. autoclass:: Result - :members:
deleted file mode 100644 --- a/third_party/python/Click/docs/arguments.rst +++ /dev/null @@ -1,263 +0,0 @@ -.. _arguments: - -Arguments -========= - -.. currentmodule:: click - -Arguments work similarly to :ref:`options <options>` but are positional. -They also only support a subset of the features of options due to their -syntactical nature. Click will also not attempt to document arguments for -you and wants you to document them manually in order to avoid ugly help -pages. - -Basic Arguments ---------------- - -The most basic option is a simple string argument of one value. If no -type is provided, the type of the default value is used, and if no default -value is provided, the type is assumed to be :data:`STRING`. - -Example: - -.. click:example:: - - @click.command() - @click.argument('filename') - def touch(filename): - click.echo(filename) - -And what it looks like: - -.. click:run:: - - invoke(touch, args=['foo.txt']) - -Variadic Arguments ------------------- - -The second most common version is variadic arguments where a specific (or -unlimited) number of arguments is accepted. This can be controlled with -the ``nargs`` parameter. If it is set to ``-1``, then an unlimited number -of arguments is accepted. - -The value is then passed as a tuple. Note that only one argument can be -set to ``nargs=-1``, as it will eat up all arguments. - -Example: - -.. click:example:: - - @click.command() - @click.argument('src', nargs=-1) - @click.argument('dst', nargs=1) - def copy(src, dst): - for fn in src: - click.echo('move %s to folder %s' % (fn, dst)) - -And what it looks like: - -.. click:run:: - - invoke(copy, args=['foo.txt', 'bar.txt', 'my_folder']) - -Note that this is not how you would write this application. The reason -for this is that in this particular example the arguments are defined as -strings. Filenames, however, are not strings! They might be on certain -operating systems, but not necessarily on all. For better ways to write -this, see the next sections. - -.. admonition:: Note on Non-Empty Variadic Arguments - - If you come from ``argparse``, you might be missing support for setting - ``nargs`` to ``+`` to indicate that at least one argument is required. - - This is supported by setting ``required=True``. However, this should - not be used if you can avoid it as we believe scripts should gracefully - degrade into becoming noops if a variadic argument is empty. The - reason for this is that very often, scripts are invoked with wildcard - inputs from the command line and they should not error out if the - wildcard is empty. - -.. _file-args: - -File Arguments --------------- - -Since all the examples have already worked with filenames, it makes sense -to explain how to deal with files properly. Command line tools are more -fun if they work with files the Unix way, which is to accept ``-`` as a -special file that refers to stdin/stdout. - -Click supports this through the :class:`click.File` type which -intelligently handles files for you. It also deals with Unicode and bytes -correctly for all versions of Python so your script stays very portable. - -Example: - -.. click:example:: - - @click.command() - @click.argument('input', type=click.File('rb')) - @click.argument('output', type=click.File('wb')) - def inout(input, output): - while True: - chunk = input.read(1024) - if not chunk: - break - output.write(chunk) - -And what it does: - -.. click:run:: - - with isolated_filesystem(): - invoke(inout, args=['-', 'hello.txt'], input=['hello'], - terminate_input=True) - invoke(inout, args=['hello.txt', '-']) - -File Path Arguments -------------------- - -In the previous example, the files were opened immediately. But what if -we just want the filename? The naïve way is to use the default string -argument type. However, remember that Click is Unicode-based, so the string -will always be a Unicode value. Unfortunately, filenames can be Unicode or -bytes depending on which operating system is being used. As such, the type -is insufficient. - -Instead, you should be using the :class:`Path` type, which automatically -handles this ambiguity. Not only will it return either bytes or Unicode -depending on what makes more sense, but it will also be able to do some -basic checks for you such as existence checks. - -Example: - -.. click:example:: - - @click.command() - @click.argument('f', type=click.Path(exists=True)) - def touch(f): - click.echo(click.format_filename(f)) - -And what it does: - -.. click:run:: - - with isolated_filesystem(): - with open('hello.txt', 'w') as f: - f.write('Hello World!\n') - invoke(touch, args=['hello.txt']) - println() - invoke(touch, args=['missing.txt']) - - -File Opening Safety -------------------- - -The :class:`FileType` type has one problem it needs to deal with, and that -is to decide when to open a file. The default behavior is to be -"intelligent" about it. What this means is that it will open stdin/stdout -and files opened for reading immediately. This will give the user direct -feedback when a file cannot be opened, but it will only open files -for writing the first time an IO operation is performed by automatically -wrapping the file in a special wrapper. - -This behavior can be forced by passing ``lazy=True`` or ``lazy=False`` to -the constructor. If the file is opened lazily, it will fail its first IO -operation by raising an :exc:`FileError`. - -Since files opened for writing will typically immediately empty the file, -the lazy mode should only be disabled if the developer is absolutely sure -that this is intended behavior. - -Forcing lazy mode is also very useful to avoid resource handling -confusion. If a file is opened in lazy mode, it will receive a -``close_intelligently`` method that can help figure out if the file -needs closing or not. This is not needed for parameters, but is -necessary for manually prompting with the :func:`prompt` function as you -do not know if a stream like stdout was opened (which was already open -before) or a real file that needs closing. - -Starting with Click 2.0, it is also possible to open files in atomic mode by -passing ``atomic=True``. In atomic mode, all writes go into a separate -file in the same folder, and upon completion, the file will be moved over to -the original location. This is useful if a file regularly read by other -users is modified. - -Environment Variables ---------------------- - -Like options, arguments can also grab values from an environment variable. -Unlike options, however, this is only supported for explicitly named -environment variables. - -Example usage: - -.. click:example:: - - @click.command() - @click.argument('src', envvar='SRC', type=click.File('r')) - def echo(src): - click.echo(src.read()) - -And from the command line: - -.. click:run:: - - with isolated_filesystem(): - with open('hello.txt', 'w') as f: - f.write('Hello World!') - invoke(echo, env={'SRC': 'hello.txt'}) - -In that case, it can also be a list of different environment variables -where the first one is picked. - -Generally, this feature is not recommended because it can cause the user -a lot of confusion. - -Option-Like Arguments ---------------------- - -Sometimes, you want to process arguments that look like options. For -instance, imagine you have a file named ``-foo.txt``. If you pass this as -an argument in this manner, Click will treat it as an option. - -To solve this, Click does what any POSIX style command line script does, -and that is to accept the string ``--`` as a separator for options and -arguments. After the ``--`` marker, all further parameters are accepted as -arguments. - -Example usage: - -.. click:example:: - - @click.command() - @click.argument('files', nargs=-1, type=click.Path()) - def touch(files): - for filename in files: - click.echo(filename) - -And from the command line: - -.. click:run:: - - invoke(touch, ['--', '-foo.txt', 'bar.txt']) - -If you don't like the ``--`` marker, you can set ignore_unknown_options to -True to avoid checking unknown options: - -.. click:example:: - - @click.command(context_settings={"ignore_unknown_options": True}) - @click.argument('files', nargs=-1, type=click.Path()) - def touch(files): - for filename in files: - click.echo(filename) - -And from the command line: - -.. click:run:: - - invoke(touch, ['-foo.txt', 'bar.txt']) -
deleted file mode 100644 --- a/third_party/python/Click/docs/bashcomplete.rst +++ /dev/null @@ -1,131 +0,0 @@ -Bash Complete -============= - -.. versionadded:: 2.0 - -As of Click 2.0, there is built-in support for Bash completion for -any Click script. There are certain restrictions on when this completion -is available, but for the most part it should just work. - -Limitations ------------ - -Bash completion is only available if a script has been installed properly, -and not executed through the ``python`` command. For information about -how to do that, see :ref:`setuptools-integration`. Click currently -only supports completion for Bash and Zsh. - -What it Completes ------------------ - -Generally, the Bash completion support will complete subcommands, options -and any option or argument values where the type is click.Choice. -Subcommands and choices are always listed whereas options only if at -least a dash has been provided. Example:: - - $ repo <TAB><TAB> - clone commit copy delete setuser - $ repo clone -<TAB><TAB> - --deep --help --rev --shallow -r - -Additionally, custom suggestions can be provided for arguments and options with -the ``autocompletion`` parameter. ``autocompletion`` should a callback function -that returns a list of strings. This is useful when the suggestions need to be -dynamically generated at bash completion time. The callback function will be -passed 3 keyword arguments: - -- ``ctx`` - The current click context. -- ``args`` - The list of arguments passed in. -- ``incomplete`` - The partial word that is being completed, as a string. May - be an empty string ``''`` if no characters have been entered yet. - -Here is an example of using a callback function to generate dynamic suggestions: - -.. click:example:: - - import os - - def get_env_vars(ctx, args, incomplete): - return [k for k in os.environ.keys() if incomplete in k] - - @click.command() - @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars) - def cmd1(envvar): - click.echo('Environment variable: %s' % envvar) - click.echo('Value: %s' % os.environ[envvar]) - - -Completion help strings (ZSH only) ----------------------------------- - -ZSH supports showing documentation strings for completions. These are taken -from the help parameters of options and subcommands. For dynamically generated -completions a help string can be provided by returning a tuple instead of a -string. The first element of the tuple is the completion and the second is the -help string to display. - -Here is an example of using a callback function to generate dynamic suggestions with help strings: - -.. click:example:: - - import os - - def get_colors(ctx, args, incomplete): - colors = [('red', 'help string for the color red'), - ('blue', 'help string for the color blue'), - ('green', 'help string for the color green')] - return [c for c in colors if incomplete in c[0]] - - @click.command() - @click.argument("color", type=click.STRING, autocompletion=get_colors) - def cmd1(color): - click.echo('Chosen color is %s' % color) - - -Activation ----------- - -In order to activate Bash completion, you need to inform Bash that -completion is available for your script, and how. Any Click application -automatically provides support for that. The general way this works is -through a magic environment variable called ``_<PROG_NAME>_COMPLETE``, -where ``<PROG_NAME>`` is your application executable name in uppercase -with dashes replaced by underscores. - -If your tool is called ``foo-bar``, then the magic variable is called -``_FOO_BAR_COMPLETE``. By exporting it with the ``source`` value it will -spit out the activation script which can be trivially activated. - -For instance, to enable Bash completion for your ``foo-bar`` script, this -is what you would need to put into your ``.bashrc``:: - - eval "$(_FOO_BAR_COMPLETE=source foo-bar)" - -For zsh users add this to your ``.zshrc``:: - - eval "$(_FOO_BAR_COMPLETE=source_zsh foo-bar)" - -From this point onwards, your script will have autocompletion enabled. - -Activation Script ------------------ - -The above activation example will always invoke your application on -startup. This might be slowing down the shell activation time -significantly if you have many applications. Alternatively, you could also -ship a file with the contents of that, which is what Git and other systems -are doing. - -This can be easily accomplished:: - - _FOO_BAR_COMPLETE=source foo-bar > foo-bar-complete.sh - -For zsh: - - _FOO_BAR_COMPLETE=source_zsh foo-bar > foo-bar-complete.sh - -And then you would put this into your .bashrc or .zshrc instead:: - - . /path/to/foo-bar-complete.sh - -
deleted file mode 100644 --- a/third_party/python/Click/docs/changelog.rst +++ /dev/null @@ -1,3 +0,0 @@ -.. currentmodule:: click - -.. include:: ../CHANGES.rst
deleted file mode 100644 --- a/third_party/python/Click/docs/commands.rst +++ /dev/null @@ -1,562 +0,0 @@ -Commands and Groups -=================== - -.. currentmodule:: click - -The most important feature of Click is the concept of arbitrarily nesting -command line utilities. This is implemented through the :class:`Command` -and :class:`Group` (actually :class:`MultiCommand`). - -Callback Invocation -------------------- - -For a regular command, the callback is executed whenever the command runs. -If the script is the only command, it will always fire (unless a parameter -callback prevents it. This for instance happens if someone passes -``--help`` to the script). - -For groups and multi commands, the situation looks different. In this case, -the callback fires whenever a subcommand fires (unless this behavior is -changed). What this means in practice is that an outer command runs -when an inner command runs: - -.. click:example:: - - @click.group() - @click.option('--debug/--no-debug', default=False) - def cli(debug): - click.echo('Debug mode is %s' % ('on' if debug else 'off')) - - @cli.command() - def sync(): - click.echo('Syncing') - -Here is what this looks like: - -.. click:run:: - - invoke(cli, prog_name='tool.py') - println() - invoke(cli, prog_name='tool.py', args=['--debug', 'sync']) - -Passing Parameters ------------------- - -Click strictly separates parameters between commands and subcommands. What this -means is that options and arguments for a specific command have to be specified -*after* the command name itself, but *before* any other command names. - -This behavior is already observable with the predefined ``--help`` option. -Suppose we have a program called ``tool.py``, containing a subcommand called -``sub``. - -- ``tool.py --help`` will return the help for the whole program (listing - subcommands). - -- ``tool.py sub --help`` will return the help for the ``sub`` subcommand. - -- But ``tool.py --help sub`` will treat ``--help`` as an argument for the main - program. Click then invokes the callback for ``--help``, which prints the - help and aborts the program before click can process the subcommand. - -Nested Handling and Contexts ----------------------------- - -As you can see from the earlier example, the basic command group accepts a -debug argument which is passed to its callback, but not to the sync -command itself. The sync command only accepts its own arguments. - -This allows tools to act completely independent of each other, but how -does one command talk to a nested one? The answer to this is the -:class:`Context`. - -Each time a command is invoked, a new context is created and linked with the -parent context. Normally, you can't see these contexts, but they are -there. Contexts are passed to parameter callbacks together with the -value automatically. Commands can also ask for the context to be passed -by marking themselves with the :func:`pass_context` decorator. In that -case, the context is passed as first argument. - -The context can also carry a program specified object that can be -used for the program's purposes. What this means is that you can build a -script like this: - -.. click:example:: - - @click.group() - @click.option('--debug/--no-debug', default=False) - @click.pass_context - def cli(ctx, debug): - # ensure that ctx.obj exists and is a dict (in case `cli()` is called - # by means other than the `if` block below - ctx.ensure_object(dict) - - ctx.obj['DEBUG'] = debug - - @cli.command() - @click.pass_context - def sync(ctx): - click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off')) - - if __name__ == '__main__': - cli(obj={}) - -If the object is provided, each context will pass the object onwards to -its children, but at any level a context's object can be overridden. To -reach to a parent, ``context.parent`` can be used. - -In addition to that, instead of passing an object down, nothing stops the -application from modifying global state. For instance, you could just flip -a global ``DEBUG`` variable and be done with it. - -Decorating Commands -------------------- - -As you have seen in the earlier example, a decorator can change how a -command is invoked. What actually happens behind the scenes is that -callbacks are always invoked through the :meth:`Context.invoke` method -which automatically invokes a command correctly (by either passing the -context or not). - -This is very useful when you want to write custom decorators. For -instance, a common pattern would be to configure an object representing -state and then storing it on the context and then to use a custom -decorator to find the most recent object of this sort and pass it as first -argument. - -For instance, the :func:`pass_obj` decorator can be implemented like this: - -.. click:example:: - - from functools import update_wrapper - - def pass_obj(f): - @click.pass_context - def new_func(ctx, *args, **kwargs): - return ctx.invoke(f, ctx.obj, *args, **kwargs) - return update_wrapper(new_func, f) - -The :meth:`Context.invoke` command will automatically invoke the function -in the correct way, so the function will either be called with ``f(ctx, -obj)`` or ``f(obj)`` depending on whether or not it itself is decorated with -:func:`pass_context`. - -This is a very powerful concept that can be used to build very complex -nested applications; see :ref:`complex-guide` for more information. - - -Group Invocation Without Command --------------------------------- - -By default, a group or multi command is not invoked unless a subcommand is -passed. In fact, not providing a command automatically passes ``--help`` -by default. This behavior can be changed by passing -``invoke_without_command=True`` to a group. In that case, the callback is -always invoked instead of showing the help page. The context object also -includes information about whether or not the invocation would go to a -subcommand. - -Example: - -.. click:example:: - - @click.group(invoke_without_command=True) - @click.pass_context - def cli(ctx): - if ctx.invoked_subcommand is None: - click.echo('I was invoked without subcommand') - else: - click.echo('I am about to invoke %s' % ctx.invoked_subcommand) - - @cli.command() - def sync(): - click.echo('The subcommand') - -And how it works in practice: - -.. click:run:: - - invoke(cli, prog_name='tool', args=[]) - invoke(cli, prog_name='tool', args=['sync']) - -.. _custom-multi-commands: - -Custom Multi Commands ---------------------- - -In addition to using :func:`click.group`, you can also build your own -custom multi commands. This is useful when you want to support commands -being loaded lazily from plugins. - -A custom multi command just needs to implement a list and load method: - -.. click:example:: - - import click - import os - - plugin_folder = os.path.join(os.path.dirname(__file__), 'commands') - - class MyCLI(click.MultiCommand): - - def list_commands(self, ctx): - rv = [] - for filename in os.listdir(plugin_folder): - if filename.endswith('.py'): - rv.append(filename[:-3]) - rv.sort() - return rv - - def get_command(self, ctx, name): - ns = {} - fn = os.path.join(plugin_folder, name + '.py') - with open(fn) as f: - code = compile(f.read(), fn, 'exec') - eval(code, ns, ns) - return ns['cli'] - - cli = MyCLI(help='This tool\'s subcommands are loaded from a ' - 'plugin folder dynamically.') - - if __name__ == '__main__': - cli() - -These custom classes can also be used with decorators: - -.. click:example:: - - @click.command(cls=MyCLI) - def cli(): - pass - -Merging Multi Commands ----------------------- - -In addition to implementing custom multi commands, it can also be -interesting to merge multiple together into one script. While this is -generally not as recommended as it nests one below the other, the merging -approach can be useful in some circumstances for a nicer shell experience. - -The default implementation for such a merging system is the -:class:`CommandCollection` class. It accepts a list of other multi -commands and makes the commands available on the same level. - -Example usage: - -.. click:example:: - - import click - - @click.group() - def cli1(): - pass - - @cli1.command() - def cmd1(): - """Command on cli1""" - - @click.group() - def cli2(): - pass - - @cli2.command() - def cmd2(): - """Command on cli2""" - - cli = click.CommandCollection(sources=[cli1, cli2]) - - if __name__ == '__main__': - cli() - -And what it looks like: - -.. click:run:: - - invoke(cli, prog_name='cli', args=['--help']) - -In case a command exists in more than one source, the first source wins. - - -.. _multi-command-chaining: - -Multi Command Chaining ----------------------- - -.. versionadded:: 3.0 - -Sometimes it is useful to be allowed to invoke more than one subcommand in -one go. For instance if you have installed a setuptools package before -you might be familiar with the ``setup.py sdist bdist_wheel upload`` -command chain which invokes ``dist`` before ``bdist_wheel`` before -``upload``. Starting with Click 3.0 this is very simple to implement. -All you have to do is to pass ``chain=True`` to your multicommand: - -.. click:example:: - - @click.group(chain=True) - def cli(): - pass - - - @cli.command('sdist') - def sdist(): - click.echo('sdist called') - - - @cli.command('bdist_wheel') - def bdist_wheel(): - click.echo('bdist_wheel called') - -Now you can invoke it like this: - -.. click:run:: - - invoke(cli, prog_name='setup.py', args=['sdist', 'bdist_wheel']) - -When using multi command chaining you can only have one command (the last) -use ``nargs=-1`` on an argument. It is also not possible to nest multi -commands below chained multicommands. Other than that there are no -restrictions on how they work. They can accept options and arguments as -normal. - -Another note: the :attr:`Context.invoked_subcommand` attribute is a bit -useless for multi commands as it will give ``'*'`` as value if more than -one command is invoked. This is necessary because the handling of -subcommands happens one after another so the exact subcommands that will -be handled are not yet available when the callback fires. - -.. note:: - - It is currently not possible for chain commands to be nested. This - will be fixed in future versions of Click. - - -Multi Command Pipelines ------------------------ - -.. versionadded:: 3.0 - -A very common usecase of multi command chaining is to have one command -process the result of the previous command. There are various ways in -which this can be facilitated. The most obvious way is to store a value -on the context object and process it from function to function. This -works by decorating a function with :func:`pass_context` after which the -context object is provided and a subcommand can store its data there. - -Another way to accomplish this is to setup pipelines by returning -processing functions. Think of it like this: when a subcommand gets -invoked it processes all of its parameters and comes up with a plan of -how to do its processing. At that point it then returns a processing -function and returns. - -Where do the returned functions go? The chained multicommand can register -a callback with :meth:`MultiCommand.resultcallback` that goes over all -these functions and then invoke them. - -To make this a bit more concrete consider this example: - -.. click:example:: - - @click.group(chain=True, invoke_without_command=True) - @click.option('-i', '--input', type=click.File('r')) - def cli(input): - pass - - @cli.resultcallback() - def process_pipeline(processors, input): - iterator = (x.rstrip('\r\n') for x in input) - for processor in processors: - iterator = processor(iterator) - for item in iterator: - click.echo(item) - - @cli.command('uppercase') - def make_uppercase(): - def processor(iterator): - for line in iterator: - yield line.upper() - return processor - - @cli.command('lowercase') - def make_lowercase(): - def processor(iterator): - for line in iterator: - yield line.lower() - return processor - - @cli.command('strip') - def make_strip(): - def processor(iterator): - for line in iterator: - yield line.strip() - return processor - -That's a lot in one go, so let's go through it step by step. - -1. The first thing is to make a :func:`group` that is chainable. In - addition to that we also instruct Click to invoke even if no - subcommand is defined. If this would not be done, then invoking an - empty pipeline would produce the help page instead of running the - result callbacks. -2. The next thing we do is to register a result callback on our group. - This callback will be invoked with an argument which is the list of - all return values of all subcommands and then the same keyword - parameters as our group itself. This means we can access the input - file easily there without having to use the context object. -3. In this result callback we create an iterator of all the lines in the - input file and then pass this iterator through all the returned - callbacks from all subcommands and finally we print all lines to - stdout. - -After that point we can register as many subcommands as we want and each -subcommand can return a processor function to modify the stream of lines. - -One important thing of note is that Click shuts down the context after -each callback has been run. This means that for instance file types -cannot be accessed in the `processor` functions as the files will already -be closed there. This limitation is unlikely to change because it would -make resource handling much more complicated. For such it's recommended -to not use the file type and manually open the file through -:func:`open_file`. - -For a more complex example that also improves upon handling of the -pipelines have a look at the `imagepipe multi command chaining demo -<https://github.com/pallets/click/tree/master/examples/imagepipe>`__ in -the Click repository. It implements a pipeline based image editing tool -that has a nice internal structure for the pipelines. - - -Overriding Defaults -------------------- - -By default, the default value for a parameter is pulled from the -``default`` flag that is provided when it's defined, but that's not the -only place defaults can be loaded from. The other place is the -:attr:`Context.default_map` (a dictionary) on the context. This allows -defaults to be loaded from a configuration file to override the regular -defaults. - -This is useful if you plug in some commands from another package but -you're not satisfied with the defaults. - -The default map can be nested arbitrarily for each subcommand and -provided when the script is invoked. Alternatively, it can also be -overridden at any point by commands. For instance, a top-level command could -load the defaults from a configuration file. - -Example usage: - -.. click:example:: - - import click - - @click.group() - def cli(): - pass - - @cli.command() - @click.option('--port', default=8000) - def runserver(port): - click.echo('Serving on http://127.0.0.1:%d/' % port) - - if __name__ == '__main__': - cli(default_map={ - 'runserver': { - 'port': 5000 - } - }) - -And in action: - -.. click:run:: - - invoke(cli, prog_name='cli', args=['runserver'], default_map={ - 'runserver': { - 'port': 5000 - } - }) - -Context Defaults ----------------- - -.. versionadded:: 2.0 - -Starting with Click 2.0 you can override defaults for contexts not just -when calling your script, but also in the decorator that declares a -command. For instance given the previous example which defines a custom -``default_map`` this can also be accomplished in the decorator now. - -This example does the same as the previous example: - -.. click:example:: - - import click - - CONTEXT_SETTINGS = dict( - default_map={'runserver': {'port': 5000}} - ) - - @click.group(context_settings=CONTEXT_SETTINGS) - def cli(): - pass - - @cli.command() - @click.option('--port', default=8000) - def runserver(port): - click.echo('Serving on http://127.0.0.1:%d/' % port) - - if __name__ == '__main__': - cli() - -And again the example in action: - -.. click:run:: - - invoke(cli, prog_name='cli', args=['runserver']) - - -Command Return Values ---------------------- - -.. versionadded:: 3.0 - -One of the new introductions in Click 3.0 is the full support for return -values from command callbacks. This enables a whole range of features -that were previously hard to implement. - -In essence any command callback can now return a value. This return value -is bubbled to certain receivers. One usecase for this has already been -show in the example of :ref:`multi-command-chaining` where it has been -demonstrated that chained multi commands can have callbacks that process -all return values. - -When working with command return values in Click, this is what you need to -know: - -- The return value of a command callback is generally returned from the - :meth:`BaseCommand.invoke` method. The exception to this rule has to - do with :class:`Group`\s: - - * In a group the return value is generally the return value of the - subcommand invoked. The only exception to this rule is that the - return value is the return value of the group callback if it's - invoked without arguments and `invoke_without_command` is enabled. - * If a group is set up for chaining then the return value is a list - of all subcommands' results. - * Return values of groups can be processed through a - :attr:`MultiCommand.result_callback`. This is invoked with the - list of all return values in chain mode, or the single return - value in case of non chained commands. - -- The return value is bubbled through from the :meth:`Context.invoke` - and :meth:`Context.forward` methods. This is useful in situations - where you internally want to call into another command. - -- Click does not have any hard requirements for the return values and - does not use them itself. This allows return values to be used for - custom decorators or workflows (like in the multi command chaining - example). - -- When a Click script is invoked as command line application (through - :meth:`BaseCommand.main`) the return value is ignored unless the - `standalone_mode` is disabled in which case it's bubbled through.
deleted file mode 100644 --- a/third_party/python/Click/docs/complex.rst +++ /dev/null @@ -1,220 +0,0 @@ -.. _complex-guide: - -Complex Applications -==================== - -.. currentmodule:: click - -Click is designed to assist with the creation of complex and simple CLI tools -alike. However, the power of its design is the ability to arbitrarily nest -systems together. For instance, if you have ever used Django, you will -have realized that it provides a command line utility, but so does Celery. -When using Celery with Django, there are two tools that need to interact with -each other and be cross-configured. - -In a theoretical world of two separate Click command line utilities, they -could solve this problem by nesting one inside the other. For instance, the -web framework could also load the commands for the message queue framework. - -Basic Concepts --------------- - -To understand how this works, you need to understand two concepts: contexts -and the calling convention. - -Contexts -```````` - -Whenever a Click command is executed, a :class:`Context` object is created -which holds state for this particular invocation. It remembers parsed -parameters, what command created it, which resources need to be cleaned up -at the end of the function, and so forth. It can also optionally hold an -application-defined object. - -Context objects build a linked list until they hit the top one. Each context -is linked to a parent context. This allows a command to work below -another command and store its own information there without having to be -afraid of altering up the state of the parent command. - -Because the parent data is available, however, it is possible to navigate to -it if needed. - -Most of the time, you do not see the context object, but when writing more -complex applications it comes in handy. This brings us to the next point. - -Calling Convention -`````````````````` - -When a Click command callback is executed, it's passed all the non-hidden -parameters as keyword arguments. Notably absent is the context. However, -a callback can opt into being passed to the context object by marking itself -with :func:`pass_context`. - -So how do you invoke a command callback if you don't know if it should -receive the context or not? The answer is that the context itself -provides a helper function (:meth:`Context.invoke`) which can do this for -you. It accepts the callback as first argument and then invokes the -function correctly. - -Building a Git Clone --------------------- - -In this example, we want to build a command line tool that resembles a -version control system. Systems like Git usually provide one -over-arching command that already accepts some parameters and -configuration, and then have extra subcommands that do other things. - -The Root Command -```````````````` - -At the top level, we need a group that can hold all our commands. In this -case, we use the basic :func:`click.group` which allows us to register -other Click commands below it. - -For this command, we also want to accept some parameters that configure the -state of our tool: - -.. click:example:: - - import os - import click - - - class Repo(object): - def __init__(self, home=None, debug=False): - self.home = os.path.abspath(home or '.') - self.debug = debug - - - @click.group() - @click.option('--repo-home', envvar='REPO_HOME', default='.repo') - @click.option('--debug/--no-debug', default=False, - envvar='REPO_DEBUG') - @click.pass_context - def cli(ctx, repo_home, debug): - ctx.obj = Repo(repo_home, debug) - - -Let's understand what this does. We create a group command which can -have subcommands. When it is invoked, it will create an instance of a -``Repo`` class. This holds the state for our command line tool. In this -case, it just remembers some parameters, but at this point it could also -start loading configuration files and so on. - -This state object is then remembered by the context as :attr:`~Context.obj`. -This is a special attribute where commands are supposed to remember what -they need to pass on to their children. - -In order for this to work, we need to mark our function with -:func:`pass_context`, because otherwise, the context object would be -entirely hidden from us. - -The First Child Command -``````````````````````` - -Let's add our first child command to it, the clone command: - -.. click:example:: - - @cli.command() - @click.argument('src') - @click.argument('dest', required=False) - def clone(src, dest): - pass - -So now we have a clone command, but how do we get access to the repo? As -you can imagine, one way is to use the :func:`pass_context` function which -again will make our callback also get the context passed on which we -memorized the repo. However, there is a second version of this decorator -called :func:`pass_obj` which will just pass the stored object, (in our case -the repo): - -.. click:example:: - - @cli.command() - @click.argument('src') - @click.argument('dest', required=False) - @click.pass_obj - def clone(repo, src, dest): - pass - -Interleaved Commands -```````````````````` - -While not relevant for the particular program we want to build, there is -also quite good support for interleaving systems. Imagine for instance that -there was a super cool plugin for our version control system that needed a -lot of configuration and wanted to store its own configuration as -:attr:`~Context.obj`. If we would then attach another command below that, -we would all of a sudden get the plugin configuration instead of our repo -object. - -One obvious way to remedy this is to store a reference to the repo in the -plugin, but then a command needs to be aware that it's attached below such a -plugin. - -There is a much better system that can be built by taking advantage of the -linked nature of contexts. We know that the plugin context is linked to the -context that created our repo. Because of that, we can start a search for -the last level where the object stored by the context was a repo. - -Built-in support for this is provided by the :func:`make_pass_decorator` -factory, which will create decorators for us that find objects (it -internally calls into :meth:`Context.find_object`). In our case, we -know that we want to find the closest ``Repo`` object, so let's make a -decorator for this: - -.. click:example:: - - pass_repo = click.make_pass_decorator(Repo) - -If we now use ``pass_repo`` instead of ``pass_obj``, we will always get a -repo instead of something else: - -.. click:example:: - - @cli.command() - @click.argument('src') - @click.argument('dest', required=False) - @pass_repo - def clone(repo, src, dest): - pass - -Ensuring Object Creation -```````````````````````` - -The above example only works if there was an outer command that created a -``Repo`` object and stored it in the context. For some more advanced use -cases, this might become a problem. The default behavior of -:func:`make_pass_decorator` is to call :meth:`Context.find_object` -which will find the object. If it can't find the object, -:meth:`make_pass_decorator` will raise an error. -The alternative behavior is to use :meth:`Context.ensure_object` -which will find the object, and if it cannot find it, will create one and -store it in the innermost context. This behavior can also be enabled for -:func:`make_pass_decorator` by passing ``ensure=True``: - -.. click:example:: - - pass_repo = click.make_pass_decorator(Repo, ensure=True) - -In this case, the innermost context gets an object created if it is -missing. This might replace objects being placed there earlier. In this -case, the command stays executable, even if the outer command does not run. -For this to work, the object type needs to have a constructor that accepts -no arguments. - -As such it runs standalone: - -.. click:example:: - - @click.command() - @pass_repo - def cp(repo): - click.echo(isinstance(repo, Repo)) - -As you can see: - -.. click:run:: - - invoke(cp, [])
deleted file mode 100644 --- a/third_party/python/Click/docs/conf.py +++ /dev/null @@ -1,46 +0,0 @@ -from pallets_sphinx_themes import ProjectLink, get_version - -# Project -------------------------------------------------------------- - -project = "Click" -copyright = "2014 Pallets Team" -author = "Pallets Team" -release, version = get_version("Click", version_length=1) - -# General -------------------------------------------------------------- - -master_doc = "index" -extensions = ["sphinx.ext.autodoc", "sphinx.ext.intersphinx", "pallets_sphinx_themes"] -intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)} - -# HTML ----------------------------------------------------------------- - -html_theme = "click" -html_theme_options = {"index_sidebar_logo": False} -html_context = { - "project_links": [ - ProjectLink("Donate to Pallets", "https://palletsprojects.com/donate"), - ProjectLink("Click Website", "https://palletsprojects.com/p/click/"), - ProjectLink("PyPI releases", "https://pypi.org/project/Click/"), - ProjectLink("Source Code", "https://github.com/pallets/click/"), - ProjectLink("Issue Tracker", "https://github.com/pallets/click/issues/"), - ] -} -html_sidebars = { - "index": ["project.html", "versions.html", "searchbox.html"], - "**": ["localtoc.html", "relations.html", "versions.html", "searchbox.html"], -} -singlehtml_sidebars = {"index": ["project.html", "versions.html", "localtoc.html"]} -html_static_path = ["_static"] -html_favicon = "_static/click-icon.png" -html_logo = "_static/click-logo-sidebar.png" -html_title = "Click Documentation ({})".format(version) -html_show_sourcelink = False -html_domain_indices = False -html_experimental_html5_writer = True - -# LaTeX ---------------------------------------------------------------- - -latex_documents = [ - (master_doc, "Click-{}.tex".format(version), html_title, author, "manual") -]
deleted file mode 100644 --- a/third_party/python/Click/docs/contrib.rst +++ /dev/null @@ -1,25 +0,0 @@ -.. _contrib: - -============= -click-contrib -============= - -As the userbase of Click grows, more and more major feature requests pop up in -Click's bugtracker. As reasonable as it may be for those features to be bundled -with Click instead of being a standalone project, many of those requested -features are either highly experimental or have unproven practical use, while -potentially being a burden to maintain. - -This is why click-contrib_ exists. The GitHub organization is a collection of -possibly experimental third-party packages whose featureset does not belong -into Click, but also a playground for major features that may be added to Click -in the future. It is also meant to coordinate and concentrate effort on writing -third-party extensions for Click, and to ease the effort of searching for such -extensions. In that sense it could be described as a low-maintenance -alternative to extension repositories of other frameworks. - -Please note that the quality and stability of those packages may be different -than what you expect from Click itself. While published under a common -organization, they are still projects separate from Click. - -.. _click-contrib: https://github.com/click-contrib/
deleted file mode 100644 --- a/third_party/python/Click/docs/documentation.rst +++ /dev/null @@ -1,197 +0,0 @@ -Documenting Scripts -=================== - -.. currentmodule:: click - -Click makes it very easy to document your command line tools. First of -all, it automatically generates help pages for you. While these are -currently not customizable in terms of their layout, all of the text -can be changed. - -Help Texts ----------- - -Commands and options accept help arguments. In the case of commands, the -docstring of the function is automatically used if provided. - -Simple example: - -.. click:example:: - - @click.command() - @click.option('--count', default=1, help='number of greetings') - @click.argument('name') - def hello(count, name): - """This script prints hello NAME COUNT times.""" - for x in range(count): - click.echo('Hello %s!' % name) - -And what it looks like: - -.. click:run:: - - invoke(hello, args=['--help']) - -Arguments cannot be documented this way. This is to follow the general -convention of Unix tools of using arguments for only the most necessary -things and to document them in the introduction text by referring to them -by name. - -Preventing Rewrapping ---------------------- - -The default behavior of Click is to rewrap text based on the width of the -terminal. In some circumstances, this can become a problem. The main issue -is when showing code examples, where newlines are significant. - -Rewrapping can be disabled on a per-paragraph basis by adding a line with -solely the ``\b`` escape marker in it. This line will be removed from the -help text and rewrapping will be disabled. - -Example: - -.. click:example:: - - @click.command() - def cli(): - """First paragraph. - - This is a very long second paragraph and as you - can see wrapped very early in the source text - but will be rewrapped to the terminal width in - the final output. - - \b - This is - a paragraph - without rewrapping. - - And this is a paragraph - that will be rewrapped again. - """ - -And what it looks like: - -.. click:run:: - - invoke(cli, args=['--help']) - -.. _doc-meta-variables: - -Truncating Help Texts ---------------------- - -Click gets command help text from function docstrings. However if you -already use docstrings to document function arguments you may not want -to see :param: and :return: lines in your help text. - -You can use the ``\f`` escape marker to have Click truncate the help text -after the marker. - -Example: - -.. click:example:: - - @click.command() - @click.pass_context - def cli(ctx): - """First paragraph. - - This is a very long second - paragraph and not correctly - wrapped but it will be rewrapped. - \f - - :param click.core.Context ctx: Click context. - """ - -And what it looks like: - -.. click:run:: - - invoke(cli, args=['--help']) - - -Meta Variables --------------- - -Options and parameters accept a ``metavar`` argument that can change the -meta variable in the help page. The default version is the parameter name -in uppercase with underscores, but can be annotated differently if -desired. This can be customized at all levels: - -.. click:example:: - - @click.command(options_metavar='<options>') - @click.option('--count', default=1, help='number of greetings', - metavar='<int>') - @click.argument('name', metavar='<name>') - def hello(count, name): - """This script prints hello <name> <int> times.""" - for x in range(count): - click.echo('Hello %s!' % name) - -Example: - -.. click:run:: - - invoke(hello, args=['--help']) - - -Command Short Help ------------------- - -For commands, a short help snippet is generated. By default, it's the first -sentence of the help message of the command, unless it's too long. This can -also be overridden: - -.. click:example:: - - @click.group() - def cli(): - """A simple command line tool.""" - - @cli.command('init', short_help='init the repo') - def init(): - """Initializes the repository.""" - - @cli.command('delete', short_help='delete the repo') - def delete(): - """Deletes the repository.""" - -And what it looks like: - -.. click:run:: - - invoke(cli, prog_name='repo.py') - - -Help Parameter Customization ----------------------------- - -.. versionadded:: 2.0 - -The help parameter is implemented in Click in a very special manner. -Unlike regular parameters it's automatically added by Click for any -command and it performs automatic conflict resolution. By default it's -called ``--help``, but this can be changed. If a command itself implements -a parameter with the same name, the default help parameter stops accepting -it. There is a context setting that can be used to override the names of -the help parameters called :attr:`~Context.help_option_names`. - -This example changes the default parameters to ``-h`` and ``--help`` -instead of just ``--help``: - -.. click:example:: - - CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) - - @click.command(context_settings=CONTEXT_SETTINGS) - def cli(): - pass - -And what it looks like: - -.. click:run:: - - invoke(cli, ['-h'])
deleted file mode 100644 --- a/third_party/python/Click/docs/exceptions.rst +++ /dev/null @@ -1,73 +0,0 @@ -Exception Handling -================== - -.. currentmodule:: click - -Click internally uses exceptions to signal various error conditions that -the user of the application might have caused. Primarily this is things -like incorrect usage. - -Where are Errors Handled? -------------------------- - -Click's main error handling is happening in :meth:`BaseCommand.main`. In -there it handles all subclasses of :exc:`ClickException` as well as the -standard :exc:`EOFError` and :exc:`KeyboardInterrupt` exceptions. The -latter are internally translated into a :exc:`Abort`. - -The logic applied is the following: - -1. If an :exc:`EOFError` or :exc:`KeyboardInterrupt` happens, reraise it - as :exc:`Abort`. -2. If an :exc:`ClickException` is raised, invoke the - :meth:`ClickException.show` method on it to display it and then exit - the program with :attr:`ClickException.exit_code`. -3. If an :exc:`Abort` exception is raised print the string ``Aborted!`` - to standard error and exit the program with exit code ``1``. -4. if it goes through well, exit the program with exit code ``0``. - -What if I don't want that? --------------------------- - -Generally you always have the option to invoke the :meth:`invoke` method -yourself. For instance if you have a :class:`Command` you can invoke it -manually like this:: - - ctx = command.make_context('command-name', ['args', 'go', 'here']) - with ctx: - result = command.invoke(ctx) - -In this case exceptions will not be handled at all and bubbled up as you -would expect. - -Starting with Click 3.0 you can also use the :meth:`Command.main` method -but disable the standalone mode which will do two things: disable -exception handling and disable the implicit :meth:`sys.exit` at the end. - -So you can do something like this:: - - command.main(['command-name', 'args', 'go', 'here'], - standalone_mode=False) - -Which Exceptions Exist? ------------------------ - -Click has two exception bases: :exc:`ClickException` which is raised for -all exceptions that Click wants to signal to the user and :exc:`Abort` -which is used to instruct Click to abort the execution. - -A :exc:`ClickException` has a :meth:`~ClickException.show` method which -can render an error message to stderr or the given file object. If you -want to use the exception yourself for doing something check the API docs -about what else they provide. - -The following common subclasses exist: - -* :exc:`UsageError` to inform the user that something went wrong. -* :exc:`BadParameter` to inform the user that something went wrong with - a specific parameter. These are often handled internally in Click and - augmented with extra information if possible. For instance if those - are raised from a callback Click will automatically augment it with - the parameter name if possible. -* :exc:`FileError` this is an error that is raised by the - :exc:`FileType` if Click encounters issues opening the file.
deleted file mode 100644 --- a/third_party/python/Click/docs/index.rst +++ /dev/null @@ -1,107 +0,0 @@ -.. rst-class:: hide-header - -Welcome to Click -================ - -.. image:: _static/click-logo.png - :align: center - :scale: 50% - :target: https://palletsprojects.com/p/click/ - -Click is a Python package for creating beautiful command line interfaces -in a composable way with as little code as necessary. It's the "Command -Line Interface Creation Kit". It's highly configurable but comes with -sensible defaults out of the box. - -It aims to make the process of writing command line tools quick and fun -while also preventing any frustration caused by the inability to implement -an intended CLI API. - -Click in three points: - -- arbitrary nesting of commands -- automatic help page generation -- supports lazy loading of subcommands at runtime - -What does it look like? Here is an example of a simple Click program: - -.. click:example:: - - import click - - @click.command() - @click.option('--count', default=1, help='Number of greetings.') - @click.option('--name', prompt='Your name', - help='The person to greet.') - def hello(count, name): - """Simple program that greets NAME for a total of COUNT times.""" - for x in range(count): - click.echo('Hello %s!' % name) - - if __name__ == '__main__': - hello() - -And what it looks like when run: - -.. click:run:: - - invoke(hello, ['--count=3'], prog_name='python hello.py', input='John\n') - -It automatically generates nicely formatted help pages: - -.. click:run:: - - invoke(hello, ['--help'], prog_name='python hello.py') - -You can get the library directly from PyPI:: - - pip install click - -Documentation -------------- - -This part of the documentation guides you through all of the library's -usage patterns. - -.. toctree:: - :maxdepth: 2 - - why - quickstart - setuptools - parameters - options - arguments - commands - prompts - documentation - complex - advanced - testing - utils - bashcomplete - exceptions - python3 - wincmd - -API Reference -------------- - -If you are looking for information on a specific function, class, or -method, this part of the documentation is for you. - -.. toctree:: - :maxdepth: 2 - - api - -Miscellaneous Pages -------------------- - -.. toctree:: - :maxdepth: 2 - - contrib - changelog - upgrading - license
deleted file mode 100644 --- a/third_party/python/Click/docs/license.rst +++ /dev/null @@ -1,14 +0,0 @@ -License -======= - -Click is licensed under a three-clause BSD License. It basically means: -do whatever you want with it as long as the copyright in Click sticks -around, the conditions are not modified and the disclaimer is present. -Furthermore, you must not use the names of the authors to promote derivatives -of the software without written consent. - -License Text ------------- - -.. include:: ../LICENSE.rst -
deleted file mode 100644 --- a/third_party/python/Click/docs/make.bat +++ /dev/null @@ -1,36 +0,0 @@ -@ECHO OFF - -pushd %~dp0 - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set SOURCEDIR=. -set BUILDDIR=_build -set SPHINXPROJ=Jinja - -if "%1" == "" goto help - -%SPHINXBUILD% >NUL 2>NUL -if errorlevel 9009 ( - echo. - echo.The 'sphinx-build' command was not found. Make sure you have Sphinx - echo.installed, then set the SPHINXBUILD environment variable to point - echo.to the full path of the 'sphinx-build' executable. Alternatively you - echo.may add the Sphinx directory to PATH. - echo. - echo.If you don't have Sphinx installed, grab it from - echo.http://sphinx-doc.org/ - exit /b 1 -) - -%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% -goto end - -:help -%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% - -:end -popd
deleted file mode 100644 --- a/third_party/python/Click/docs/options.rst +++ /dev/null @@ -1,796 +0,0 @@ -.. _options: - -Options -======= - -.. currentmodule:: click - -Adding options to commands can be accomplished by the :func:`option` -decorator. Since options can come in various different versions, there -are a ton of parameters to configure their behavior. Options in click are -distinct from :ref:`positional arguments <arguments>`. - -Name Your Options ------------------ - -The naming rules can be found in :ref:`parameter_names`. In short, you -can refer the option **implicitly** by the longest dash-prefixed argument: - -.. click:example:: - - @click.command() - @click.option('-s', '--string-to-echo') - def echo(string_to_echo): - click.echo(string_to_echo) - -Or, **explicitly**, by giving one non-dash-prefixed argument: - -.. click:example:: - - @click.command() - @click.option('-s', '--string-to-echo', 'string') - def echo(string): - click.echo(string) - -Basic Value Options -------------------- - -The most basic option is a value option. These options accept one -argument which is a value. If no type is provided, the type of the default -value is used. If no default value is provided, the type is assumed to be -:data:`STRING`. Unless a name is explicitly specified, the name of the -parameter is the first long option defined; otherwise the first short one is -used. By default, options are not required, however to make an option required, -simply pass in `required=True` as an argument to the decorator. - -.. click:example:: - - @click.command() - @click.option('--n', default=1) - def dots(n): - click.echo('.' * n) - -.. click:example:: - - # How to make an option required - @click.command() - @click.option('--n', required=True, type=int) - def dots(n): - click.echo('.' * n) - -.. click:example:: - - # How to use a Python reserved word such as `from` as a parameter - @click.command() - @click.option('--from', '-f', 'from_') - @click.option('--to', '-t') - def reserved_param_name(from_, to): - click.echo('from %s to %s' % (from_, to)) - -And on the command line: - -.. click:run:: - - invoke(dots, args=['--n=2']) - -In this case the option is of type :data:`INT` because the default value -is an integer. - -To show the default values when showing command help, use ``show_default=True`` - -.. click:example:: - - @click.command() - @click.option('--n', default=1, show_default=True) - def dots(n): - click.echo('.' * n) - -.. click:run:: - - invoke(dots, args=['--help']) - -Multi Value Options -------------------- - -Sometimes, you have options that take more than one argument. For options, -only a fixed number of arguments is supported. This can be configured by -the ``nargs`` parameter. The values are then stored as a tuple. - -.. click:example:: - - @click.command() - @click.option('--pos', nargs=2, type=float) - def findme(pos): - click.echo('%s / %s' % pos) - -And on the command line: - -.. click:run:: - - invoke(findme, args=['--pos', '2.0', '3.0']) - -.. _tuple-type: - -Tuples as Multi Value Options ------------------------------ - -.. versionadded:: 4.0 - -As you can see that by using `nargs` set to a specific number each item in -the resulting tuple is of the same type. This might not be what you want. -Commonly you might want to use different types for different indexes in -the tuple. For this you can directly specify a tuple as type: - -.. click:example:: - - @click.command() - @click.option('--item', type=(str, int)) - def putitem(item): - click.echo('name=%s id=%d' % item) - -And on the command line: - -.. click:run:: - - invoke(putitem, args=['--item', 'peter', '1338']) - -By using a tuple literal as type, `nargs` gets automatically set to the -length of the tuple and the :class:`click.Tuple` type is automatically -used. The above example is thus equivalent to this: - -.. click:example:: - - @click.command() - @click.option('--item', nargs=2, type=click.Tuple([str, int])) - def putitem(item): - click.echo('name=%s id=%d' % item) - -Multiple Options ----------------- - -Similarly to ``nargs``, there is also the case of wanting to support a -parameter being provided multiple times to and have all values recorded -- -not just the last one. For instance, ``git commit -m foo -m bar`` would -record two lines for the commit message: ``foo`` and ``bar``. This can be -accomplished with the ``multiple`` flag: - -Example: - -.. click:example:: - - @click.command() - @click.option('--message', '-m', multiple=True) - def commit(message): - click.echo('\n'.join(message)) - -And on the command line: - -.. click:run:: - - invoke(commit, args=['-m', 'foo', '-m', 'bar']) - -Counting --------- - -In some very rare circumstances, it is interesting to use the repetition -of options to count an integer up. This can be used for verbosity flags, -for instance: - -.. click:example:: - - @click.command() - @click.option('-v', '--verbose', count=True) - def log(verbose): - click.echo('Verbosity: %s' % verbose) - -And on the command line: - -.. click:run:: - - invoke(log, args=['-vvv']) - -Boolean Flags -------------- - -Boolean flags are options that can be enabled or disabled. This can be -accomplished by defining two flags in one go separated by a slash (``/``) -for enabling or disabling the option. (If a slash is in an option string, -Click automatically knows that it's a boolean flag and will pass -``is_flag=True`` implicitly.) Click always wants you to provide an enable -and disable flag so that you can change the default later. - -Example: - -.. click:example:: - - import sys - - @click.command() - @click.option('--shout/--no-shout', default=False) - def info(shout): - rv = sys.platform - if shout: - rv = rv.upper() + '!!!!111' - click.echo(rv) - -And on the command line: - -.. click:run:: - - invoke(info, args=['--shout']) - invoke(info, args=['--no-shout']) - -If you really don't want an off-switch, you can just define one and -manually inform Click that something is a flag: - -.. click:example:: - - import sys - - @click.command() - @click.option('--shout', is_flag=True) - def info(shout): - rv = sys.platform - if shout: - rv = rv.upper() + '!!!!111' - click.echo(rv) - -And on the command line: - -.. click:run:: - - invoke(info, args=['--shout']) - -Note that if a slash is contained in your option already (for instance, if -you use Windows-style parameters where ``/`` is the prefix character), you -can alternatively split the parameters through ``;`` instead: - -.. click:example:: - - @click.command() - @click.option('/debug;/no-debug') - def log(debug): - click.echo('debug=%s' % debug) - - if __name__ == '__main__': - log() - -.. versionchanged:: 6.0 - -If you want to define an alias for the second option only, then you will -need to use leading whitespace to disambiguate the format string: - -Example: - -.. click:example:: - - import sys - - @click.command() - @click.option('--shout/--no-shout', ' /-S', default=False) - def info(shout): - rv = sys.platform - if shout: - rv = rv.upper() + '!!!!111' - click.echo(rv) - -.. click:run:: - - invoke(info, args=['--help']) - -Feature Switches ----------------- - -In addition to boolean flags, there are also feature switches. These are -implemented by setting multiple options to the same parameter name and -defining a flag value. Note that by providing the ``flag_value`` parameter, -Click will implicitly set ``is_flag=True``. - -To set a default flag, assign a value of `True` to the flag that should be -the default. - -.. click:example:: - - import sys - - @click.command() - @click.option('--upper', 'transformation', flag_value='upper', - default=True) - @click.option('--lower', 'transformation', flag_value='lower') - def info(transformation): - click.echo(getattr(sys.platform, transformation)()) - -And on the command line: - -.. click:run:: - - invoke(info, args=['--upper']) - invoke(info, args=['--lower']) - invoke(info) - -.. _choice-opts: - -Choice Options --------------- - -Sometimes, you want to have a parameter be a choice of a list of values. -In that case you can use :class:`Choice` type. It can be instantiated -with a list of valid values. - -Example: - -.. click:example:: - - @click.command() - @click.option('--hash-type', type=click.Choice(['md5', 'sha1'])) - def digest(hash_type): - click.echo(hash_type) - -What it looks like: - -.. click:run:: - - invoke(digest, args=['--hash-type=md5']) - println() - invoke(digest, args=['--hash-type=foo']) - println() - invoke(digest, args=['--help']) - -.. note:: - - You should only pass the choices as list or tuple. Other iterables (like - generators) may lead to surprising results. - -.. _option-prompting: - -Prompting ---------- - -In some cases, you want parameters that can be provided from the command line, -but if not provided, ask for user input instead. This can be implemented with -Click by defining a prompt string. - -Example: - -.. click:example:: - - @click.command() - @click.option('--name', prompt=True) - def hello(name): - click.echo('Hello %s!' % name) - -And what it looks like: - -.. click:run:: - - invoke(hello, args=['--name=John']) - invoke(hello, input=['John']) - -If you are not happy with the default prompt string, you can ask for -a different one: - -.. click:example:: - - @click.command() - @click.option('--name', prompt='Your name please') - def hello(name): - click.echo('Hello %s!' % name) - -What it looks like: - -.. click:run:: - - invoke(hello, input=['John']) - -Password Prompts ----------------- - -Click also supports hidden prompts and asking for confirmation. This is -useful for password input: - -.. click:example:: - - @click.command() - @click.option('--password', prompt=True, hide_input=True, - confirmation_prompt=True) - def encrypt(password): - click.echo('Encrypting password to %s' % password.encode('rot13')) - -What it looks like: - -.. click:run:: - - invoke(encrypt, input=['secret', 'secret']) - -Because this combination of parameters is quite common, this can also be -replaced with the :func:`password_option` decorator: - -.. click:example:: - - @click.command() - @click.password_option() - def encrypt(password): - click.echo('Encrypting password to %s' % password.encode('rot13')) - -Dynamic Defaults for Prompts ----------------------------- - -The ``auto_envvar_prefix`` and ``default_map`` options for the context -allow the program to read option values from the environment or a -configuration file. However, this overrides the prompting mechanism, so -that the user does not get the option to change the value interactively. - -If you want to let the user configure the default value, but still be -prompted if the option isn't specified on the command line, you can do so -by supplying a callable as the default value. For example, to get a default -from the environment: - -.. click:example:: - - @click.command() - @click.option('--username', prompt=True, - default=lambda: os.environ.get('USER', '')) - def hello(username): - print("Hello,", username) - -To describe what the default value will be, set it in ``show_default``. - -.. click:example:: - - @click.command() - @click.option('--username', prompt=True, - default=lambda: os.environ.get('USER', ''), - show_default='current user') - def hello(username): - print("Hello,", username) - -.. click:run:: - - invoke(hello, args=['--help']) - -Callbacks and Eager Options ---------------------------- - -Sometimes, you want a parameter to completely change the execution flow. -For instance, this is the case when you want to have a ``--version`` -parameter that prints out the version and then exits the application. - -Note: an actual implementation of a ``--version`` parameter that is -reusable is available in Click as :func:`click.version_option`. The code -here is merely an example of how to implement such a flag. - -In such cases, you need two concepts: eager parameters and a callback. An -eager parameter is a parameter that is handled before others, and a -callback is what executes after the parameter is handled. The eagerness -is necessary so that an earlier required parameter does not produce an -error message. For instance, if ``--version`` was not eager and a -parameter ``--foo`` was required and defined before, you would need to -specify it for ``--version`` to work. For more information, see -:ref:`callback-evaluation-order`. - -A callback is a function that is invoked with two parameters: the current -:class:`Context` and the value. The context provides some useful features -such as quitting the application and gives access to other already -processed parameters. - -Here an example for a ``--version`` flag: - -.. click:example:: - - def print_version(ctx, param, value): - if not value or ctx.resilient_parsing: - return - click.echo('Version 1.0') - ctx.exit() - - @click.command() - @click.option('--version', is_flag=True, callback=print_version, - expose_value=False, is_eager=True) - def hello(): - click.echo('Hello World!') - -The `expose_value` parameter prevents the pretty pointless ``version`` -parameter from being passed to the callback. If that was not specified, a -boolean would be passed to the `hello` script. The `resilient_parsing` -flag is applied to the context if Click wants to parse the command line -without any destructive behavior that would change the execution flow. In -this case, because we would exit the program, we instead do nothing. - -What it looks like: - -.. click:run:: - - invoke(hello) - invoke(hello, args=['--version']) - -.. admonition:: Callback Signature Changes - - In Click 2.0 the signature for callbacks changed. For more - information about these changes see :ref:`upgrade-to-2.0`. - -Yes Parameters --------------- - -For dangerous operations, it's very useful to be able to ask a user for -confirmation. This can be done by adding a boolean ``--yes`` flag and -asking for confirmation if the user did not provide it and to fail in a -callback: - -.. click:example:: - - def abort_if_false(ctx, param, value): - if not value: - ctx.abort() - - @click.command() - @click.option('--yes', is_flag=True, callback=abort_if_false, - expose_value=False, - prompt='Are you sure you want to drop the db?') - def dropdb(): - click.echo('Dropped all tables!') - -And what it looks like on the command line: - -.. click:run:: - - invoke(dropdb, input=['n']) - invoke(dropdb, args=['--yes']) - -Because this combination of parameters is quite common, this can also be -replaced with the :func:`confirmation_option` decorator: - -.. click:example:: - - @click.command() - @click.confirmation_option(prompt='Are you sure you want to drop the db?') - def dropdb(): - click.echo('Dropped all tables!') - -.. admonition:: Callback Signature Changes - - In Click 2.0 the signature for callbacks changed. For more - information about these changes see :ref:`upgrade-to-2.0`. - -Values from Environment Variables ---------------------------------- - -A very useful feature of Click is the ability to accept parameters from -environment variables in addition to regular parameters. This allows -tools to be automated much easier. For instance, you might want to pass -a configuration file with a ``--config`` parameter but also support exporting -a ``TOOL_CONFIG=hello.cfg`` key-value pair for a nicer development -experience. - -This is supported by Click in two ways. One is to automatically build -environment variables which is supported for options only. To enable this -feature, the ``auto_envvar_prefix`` parameter needs to be passed to the -script that is invoked. Each command and parameter is then added as an -uppercase underscore-separated variable. If you have a subcommand -called ``foo`` taking an option called ``bar`` and the prefix is -``MY_TOOL``, then the variable is ``MY_TOOL_FOO_BAR``. - -Example usage: - -.. click:example:: - - @click.command() - @click.option('--username') - def greet(username): - click.echo('Hello %s!' % username) - - if __name__ == '__main__': - greet(auto_envvar_prefix='GREETER') - -And from the command line: - -.. click:run:: - - invoke(greet, env={'GREETER_USERNAME': 'john'}, - auto_envvar_prefix='GREETER') - -When using ``auto_envvar_prefix`` with command groups, the command name needs -to be included in the environment variable, between the prefix and the parameter name, *i.e.* *PREFIX_COMMAND_VARIABLE*. - -Example: - -.. click:example:: - - @click.group() - @click.option('--debug/--no-debug') - def cli(debug): - click.echo('Debug mode is %s' % ('on' if debug else 'off')) - - @cli.command() - @click.option('--username') - def greet(username): - click.echo('Hello %s!' % username) - - if __name__ == '__main__': - cli(auto_envvar_prefix='GREETER') - -.. click:run:: - - invoke(cli, args=['greet',], - env={'GREETER_GREET_USERNAME': 'John', 'GREETER_DEBUG': 'false'}, - auto_envvar_prefix='GREETER') - - -The second option is to manually pull values in from specific environment -variables by defining the name of the environment variable on the option. - -Example usage: - -.. click:example:: - - @click.command() - @click.option('--username', envvar='USERNAME') - def greet(username): - click.echo('Hello %s!' % username) - - if __name__ == '__main__': - greet() - -And from the command line: - -.. click:run:: - - invoke(greet, env={'USERNAME': 'john'}) - -In that case it can also be a list of different environment variables -where the first one is picked. - -Multiple Values from Environment Values ---------------------------------------- - -As options can accept multiple values, pulling in such values from -environment variables (which are strings) is a bit more complex. The way -Click solves this is by leaving it up to the type to customize this -behavior. For both ``multiple`` and ``nargs`` with values other than -``1``, Click will invoke the :meth:`ParamType.split_envvar_value` method to -perform the splitting. - -The default implementation for all types is to split on whitespace. The -exceptions to this rule are the :class:`File` and :class:`Path` types -which both split according to the operating system's path splitting rules. -On Unix systems like Linux and OS X, the splitting happens for those on -every colon (``:``), and for Windows, on every semicolon (``;``). - -Example usage: - -.. click:example:: - - @click.command() - @click.option('paths', '--path', envvar='PATHS', multiple=True, - type=click.Path()) - def perform(paths): - for path in paths: - click.echo(path) - - if __name__ == '__main__': - perform() - -And from the command line: - -.. click:run:: - - import os - invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep}) - -Other Prefix Characters ------------------------ - -Click can deal with alternative prefix characters other than ``-`` for -options. This is for instance useful if you want to handle slashes as -parameters ``/`` or something similar. Note that this is strongly -discouraged in general because Click wants developers to stay close to -POSIX semantics. However in certain situations this can be useful: - -.. click:example:: - - @click.command() - @click.option('+w/-w') - def chmod(w): - click.echo('writable=%s' % w) - - if __name__ == '__main__': - chmod() - -And from the command line: - -.. click:run:: - - invoke(chmod, args=['+w']) - invoke(chmod, args=['-w']) - -Note that if you are using ``/`` as prefix character and you want to use a -boolean flag you need to separate it with ``;`` instead of ``/``: - -.. click:example:: - - @click.command() - @click.option('/debug;/no-debug') - def log(debug): - click.echo('debug=%s' % debug) - - if __name__ == '__main__': - log() - -.. _ranges: - -Range Options -------------- - -A special mention should go to the :class:`IntRange` type, which works very -similarly to the :data:`INT` type, but restricts the value to fall into a -specific range (inclusive on both edges). It has two modes: - -- the default mode (non-clamping mode) where a value that falls outside - of the range will cause an error. -- an optional clamping mode where a value that falls outside of the - range will be clamped. This means that a range of ``0-5`` would - return ``5`` for the value ``10`` or ``0`` for the value ``-1`` (for - example). - -Example: - -.. click:example:: - - @click.command() - @click.option('--count', type=click.IntRange(0, 20, clamp=True)) - @click.option('--digit', type=click.IntRange(0, 10)) - def repeat(count, digit): - click.echo(str(digit) * count) - - if __name__ == '__main__': - repeat() - -And from the command line: - -.. click:run:: - - invoke(repeat, args=['--count=1000', '--digit=5']) - invoke(repeat, args=['--count=1000', '--digit=12']) - -If you pass ``None`` for any of the edges, it means that the range is open -at that side. - -Callbacks for Validation ------------------------- - -.. versionchanged:: 2.0 - -If you want to apply custom validation logic, you can do this in the -parameter callbacks. These callbacks can both modify values as well as -raise errors if the validation does not work. - -In Click 1.0, you can only raise the :exc:`UsageError` but starting with -Click 2.0, you can also raise the :exc:`BadParameter` error, which has the -added advantage that it will automatically format the error message to -also contain the parameter name. - -Example: - -.. click:example:: - - def validate_rolls(ctx, param, value): - try: - rolls, dice = map(int, value.split('d', 2)) - return (dice, rolls) - except ValueError: - raise click.BadParameter('rolls need to be in format NdM') - - @click.command() - @click.option('--rolls', callback=validate_rolls, default='1d6') - def roll(rolls): - click.echo('Rolling a %d-sided dice %d time(s)' % rolls) - - if __name__ == '__main__': - roll() - -And what it looks like: - -.. click:run:: - - invoke(roll, args=['--rolls=42']) - println() - invoke(roll, args=['--rolls=2d12'])
deleted file mode 100644 --- a/third_party/python/Click/docs/parameters.rst +++ /dev/null @@ -1,139 +0,0 @@ -Parameters -========== - -.. currentmodule:: click - -Click supports two types of parameters for scripts: options and arguments. -There is generally some confusion among authors of command line scripts of -when to use which, so here is a quick overview of the differences. As its -name indicates, an option is optional. While arguments can be optional -within reason, they are much more restricted in how optional they can be. - -To help you decide between options and arguments, the recommendation is -to use arguments exclusively for things like going to subcommands or input -filenames / URLs, and have everything else be an option instead. - -Differences ------------ - -Arguments can do less than options. The following features are only -available for options: - -* automatic prompting for missing input -* act as flags (boolean or otherwise) -* option values can be pulled from environment variables, arguments can not -* options are fully documented in the help page, arguments are not - (this is intentional as arguments might be too specific to be - automatically documented) - -On the other hand arguments, unlike options, can accept an arbitrary number -of arguments. Options can strictly ever only accept a fixed number of -arguments (defaults to 1). - -Parameter Types ---------------- - -Parameters can be of different types. Types can be implemented with -different behavior and some are supported out of the box: - -``str`` / :data:`click.STRING`: - The default parameter type which indicates unicode strings. - -``int`` / :data:`click.INT`: - A parameter that only accepts integers. - -``float`` / :data:`click.FLOAT`: - A parameter that only accepts floating point values. - -``bool`` / :data:`click.BOOL`: - A parameter that accepts boolean values. This is automatically used - for boolean flags. If used with string values ``1``, ``yes``, ``y``, ``t`` - and ``true`` convert to `True` and ``0``, ``no``, ``n``, ``f`` and ``false`` - convert to `False`. - -:data:`click.UUID`: - A parameter that accepts UUID values. This is not automatically - guessed but represented as :class:`uuid.UUID`. - -.. autoclass:: File - :noindex: - -.. autoclass:: Path - :noindex: - -.. autoclass:: Choice - :noindex: - -.. autoclass:: IntRange - :noindex: - -.. autoclass:: FloatRange - :noindex: - -.. autoclass:: DateTime - :noindex: - -Custom parameter types can be implemented by subclassing -:class:`click.ParamType`. For simple cases, passing a Python function that -fails with a `ValueError` is also supported, though discouraged. - -.. _parameter_names: - -Parameter Names ---------------- - -Parameters (both options and arguments) accept a number of positional arguments -which are passed to the command function as parameters. Each string with a -single dash is added as a short argument; each string starting with a double -dash as a long one. - -If a string is added without any dashes, it becomes the internal parameter name -which is also used as variable name. - -If all names for a parameter contain dashes, the internal name is generated -automatically by taking the longest argument and converting all dashes to -underscores. - -The internal name is converted to lowercase. - -Examples: - -* For an option with ``('-f', '--foo-bar')``, the parameter name is `foo_bar`. -* For an option with ``('-x',)``, the parameter is `x`. -* For an option with ``('-f', '--filename', 'dest')``, the parameter name is `dest`. -* For an option with ``('--CamelCaseOption',)``, the parameter is `camelcaseoption`. -* For an arguments with ``(`foogle`)``, the parameter name is `foogle`. To - provide a different human readable name for use in help text, see the section - about :ref:`doc-meta-variables`. - -Implementing Custom Types -------------------------- - -To implement a custom type, you need to subclass the :class:`ParamType` -class. Types can be invoked with or without context and parameter object, -which is why they need to be able to deal with this. - -The following code implements an integer type that accepts hex and octal -numbers in addition to normal integers, and converts them into regular -integers:: - - import click - - class BasedIntParamType(click.ParamType): - name = 'integer' - - def convert(self, value, param, ctx): - try: - if value[:2].lower() == '0x': - return int(value[2:], 16) - elif value[:1] == '0': - return int(value, 8) - return int(value, 10) - except ValueError: - self.fail('%s is not a valid integer' % value, param, ctx) - - BASED_INT = BasedIntParamType() - -As you can see, a subclass needs to implement the :meth:`ParamType.convert` -method and optionally provide the :attr:`ParamType.name` attribute. The -latter can be used for documentation purposes.
deleted file mode 100644 --- a/third_party/python/Click/docs/prompts.rst +++ /dev/null @@ -1,48 +0,0 @@ -User Input Prompts -================== - -.. currentmodule:: click - -Click supports prompts in two different places. The first is automated -prompts when the parameter handling happens, and the second is to ask for -prompts at a later point independently. - -This can be accomplished with the :func:`prompt` function, which asks for -valid input according to a type, or the :func:`confirm` function, which asks -for confirmation (yes/no). - -Option Prompts --------------- - -Option prompts are integrated into the option interface. See -:ref:`option-prompting` for more information. Internally, it -automatically calls either :func:`prompt` or :func:`confirm` as necessary. - -Input Prompts -------------- - -To manually ask for user input, you can use the :func:`prompt` function. -By default, it accepts any Unicode string, but you can ask for any other -type. For instance, you can ask for a valid integer:: - - value = click.prompt('Please enter a valid integer', type=int) - -Additionally, the type will be determined automatically if a default value is -provided. For instance, the following will only accept floats:: - - value = click.prompt('Please enter a number', default=42.0) - -Confirmation Prompts --------------------- - -To ask if a user wants to continue with an action, the :func:`confirm` -function comes in handy. By default, it returns the result of the prompt -as a boolean value:: - - if click.confirm('Do you want to continue?'): - click.echo('Well done!') - -There is also the option to make the function automatically abort the -execution of the program if it does not return ``True``:: - - click.confirm('Do you want to continue?', abort=True)
deleted file mode 100644 --- a/third_party/python/Click/docs/python3.rst +++ /dev/null @@ -1,183 +0,0 @@ -Python 3 Support -================ - -.. currentmodule:: click - -Click supports Python 3, but like all other command line utility libraries, -it suffers from the Unicode text model in Python 3. All examples in the -documentation were written so that they could run on both Python 2.x and -Python 3.4 or higher. - -At the moment, it is strongly recommended to use Python 2 for Click -utilities unless Python 3 is a hard requirement. - -.. _python3-limitations: - -Python 3 Limitations --------------------- - -At the moment, Click suffers from a few problems with Python 3: - -* The command line in Unix traditionally is in bytes, not Unicode. While - there are encoding hints for all of this, there are generally some - situations where this can break. The most common one is SSH - connections to machines with different locales. - - Misconfigured environments can currently cause a wide range of Unicode - problems in Python 3 due to the lack of support for roundtripping - surrogate escapes. This will not be fixed in Click itself! - - For more information see :ref:`python3-surrogates`. - -* Standard input and output in Python 3 is opened in Unicode mode by - default. Click has to reopen the stream in binary mode in certain - situations. Because there is no standardized way to do this, this - might not always work. Primarily this can become a problem when - testing command-line applications. - - This is not supported:: - - sys.stdin = io.StringIO('Input here') - sys.stdout = io.StringIO() - - Instead you need to do this:: - - input = 'Input here' - in_stream = io.BytesIO(input.encode('utf-8')) - sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8') - out_stream = io.BytesIO() - sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8') - - Remember that in that case, you need to use ``out_stream.getvalue()`` - and not ``sys.stdout.getvalue()`` if you want to access the buffer - contents as the wrapper will not forward that method. - -Python 2 and 3 Differences --------------------------- - -Click attempts to minimize the differences between Python 2 and Python 3 -by following best practices for both languages. - -In Python 2, the following is true: - -* ``sys.stdin``, ``sys.stdout``, and ``sys.stderr`` are opened in binary - mode, but under some circumstances they support Unicode output. Click - attempts to not subvert this but provides support for forcing streams - to be Unicode-based. -* ``sys.argv`` is always byte-based. Click will pass bytes to all - input types and convert as necessary. The :class:`STRING` type - automatically will decode properly the input value into a string by - trying the most appropriate encodings. -* When dealing with files, Click will never go through the Unicode APIs - and will instead use the operating system's byte APIs to open the - files. - -In Python 3, the following is true: - -* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default - text-based. When Click needs a binary stream, it attempts to discover - the underlying binary stream. See :ref:`python3-limitations` for how - this works. -* ``sys.argv`` is always Unicode-based. This also means that the native - type for input values to the types in Click is Unicode, and not bytes. - - This causes problems if the terminal is incorrectly set and Python - does not figure out the encoding. In that case, the Unicode string - will contain error bytes encoded as surrogate escapes. -* When dealing with files, Click will always use the Unicode file system - API calls by using the operating system's reported or guessed - filesystem encoding. Surrogates are supported for filenames, so it - should be possible to open files through the :class:`File` type even - if the environment is misconfigured. - -.. _python3-surrogates: - -Python 3 Surrogate Handling ---------------------------- - -Click in Python 3 does all the Unicode handling in the standard library -and is subject to its behavior. In Python 2, Click does all the Unicode -handling itself, which means there are differences in error behavior. - -The most glaring difference is that in Python 2, Unicode will "just work", -while in Python 3, it requires extra care. The reason for this is that in -Python 3, the encoding detection is done in the interpreter, and on Linux -and certain other operating systems, its encoding handling is problematic. - -The biggest source of frustration is that Click scripts invoked by -init systems (sysvinit, upstart, systemd, etc.), deployment tools (salt, -puppet), or cron jobs (cron) will refuse to work unless a Unicode locale is -exported. - -If Click encounters such an environment it will prevent further execution -to force you to set a locale. This is done because Click cannot know -about the state of the system once it's invoked and restore the values -before Python's Unicode handling kicked in. - -If you see something like this error in Python 3:: - - Traceback (most recent call last): - ... - RuntimeError: Click will abort further execution because Python 3 was - configured to use ASCII as encoding for the environment. Either switch - to Python 2 or consult the Python 3 section of the docs for - mitigation steps. - -You are dealing with an environment where Python 3 thinks you are -restricted to ASCII data. The solution to these problems is different -depending on which locale your computer is running in. - -For instance, if you have a German Linux machine, you can fix the problem -by exporting the locale to ``de_DE.utf-8``:: - - export LC_ALL=de_DE.utf-8 - export LANG=de_DE.utf-8 - -If you are on a US machine, ``en_US.utf-8`` is the encoding of choice. On -some newer Linux systems, you could also try ``C.UTF-8`` as the locale:: - - export LC_ALL=C.UTF-8 - export LANG=C.UTF-8 - -On some systems it was reported that `UTF-8` has to be written as `UTF8` -and vice versa. To see which locales are supported you can invoke -``locale -a``:: - - locale -a - -You need to do this before you invoke your Python script. If you are -curious about the reasons for this, you can join the discussions in the -Python 3 bug tracker: - -* `ASCII is a bad filesystem default encoding - <http://bugs.python.org/issue13643#msg149941>`_ -* `Use surrogateescape as default error handler - <http://bugs.python.org/issue19977>`_ -* `Python 3 raises Unicode errors in the C locale - <http://bugs.python.org/issue19846>`_ -* `LC_CTYPE=C: pydoc leaves terminal in an unusable state - <http://bugs.python.org/issue21398>`_ (this is relevant to Click - because the pager support is provided by the stdlib pydoc module) - -Unicode Literals ----------------- - -Starting with Click 5.0 there will be a warning for the use of the -``unicode_literals`` future import in Python 2. This has been done due to -the negative consequences of this import with regards to unintentionally -causing bugs due to introducing Unicode data to APIs that are incapable of -handling them. For some examples of this issue, see the discussion on -this github issue: `python-future#22 -<https://github.com/PythonCharmers/python-future/issues/22>`_. - -If you use ``unicode_literals`` in any file that defines a Click command -or that invokes a click command you will be given a warning. You are