Skip to content
Myr

Merge pull request #1532 from pallets/drop-python2

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

Drop Python 2

authored by David Lord · committed by GitHub · parents 19fdc85, a1d726b · Browse files · 61 files+849 added−1498 removed
This commit

State

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

Diff stats

61 files+849 added−1498 removed

  • tests:+102 added−164 removed
  • other:+747 added−1334 removed

61 files+849 added−1498 removed

modified:docs/advanced.rst+7 added-7 removed
44 unmodified lines
45 if not matches:46 return None47 elif len(matches) == 1:48 return click.Group.get_command(self, ctx, matches[0])49 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))49 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")5051And it can then be used like this:5253.. click:example::
37 unmodified lines
91 @click.command()92 @click.option('--url', callback=open_url)93 def cli(url, fp=None):94 if fp is not None:95 click.echo('%s: %s' % (url, fp.code))95 click.echo(f"{url}: {fp.code}")9697In this case the callback returns the URL unchanged but also passes a98second ``fp`` value to the callback. What's more recommended is to pass99the information in a wrapper however:
15 unmodified lines
115 @click.command()116 @click.option('--url', callback=open_url)117 def cli(url):118 if url is not None:119 click.echo('%s: %s' % (url.url, url.fp.code))119 click.echo(f"{url.url}: {url.fp.code}")120121122Token Normalization123-------------------
15 unmodified lines
139140 @click.command(context_settings=CONTEXT_SETTINGS)141 @click.option('--name', default='Pete')142 def cli(name):143 click.echo('Name: %s' % name)143 click.echo(f"Name: {name}")144145And how it works on the command line:146147.. click:run::
22 unmodified lines
170171 @cli.command()172 @click.option('--count', default=1)173 def test(count):174 click.echo('Count: %d' % count)174 click.echo(f'Count: {count}')175176 @cli.command()177 @click.option('--count', default=1)178 @click.pass_context
120 unmodified lines
299 def cli(verbose, timeit_args):300 """A fake wrapper around Python's timeit."""301 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)302 if verbose:303 click.echo('Invoking: %s' % ' '.join(cmdline))303 click.echo(f"Invoking: {' '.join(cmdline)}")304 call(cmdline)305306And what it looks like:307
87 unmodified lines
395 @click.argument('port', nargs=1, default=8080, envvar="PORT")396 @click.pass_context397 def cli(ctx, port):398 source = ctx.get_parameter_source("port")399 click.echo("Port came from {}".format(source))399 click.echo(f"Port came from {source}")400401.. click:run::402403 invoke(cli, prog_name='cli', args=['8080'])
5 unmodified lines
modified:docs/arguments.rst+1 added-1 removed
53 unmodified lines
54 @click.argument('dst', nargs=1)55 def copy(src, dst):56 """Move file SRC to DST."""57 for fn in src:58 click.echo('move %s to folder %s' % (fn, dst))58 click.echo(f"move {fn} to folder {dst}")5960And what it looks like:6162.. click:run::
207 unmodified lines
modified:docs/bashcomplete.rst+3 added-3 removed
48 unmodified lines
4950 @click.command()51 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)52 def cmd1(envvar):53 click.echo('Environment variable: %s' % envvar)54 click.echo('Value: %s' % os.environ[envvar])53 click.echo(f"Environment variable: {envvar}")54 click.echo(f"Value: {os.environ[envvar]}")555657Completion help strings58-----------------------
19 unmodified lines
7879 @click.command()80 @click.argument("color", type=click.STRING, autocompletion=get_colors)81 def cmd1(color):82 click.echo('Chosen color is %s' % color)82 click.echo(f"Chosen color is {color}")838485Activation86----------
77 unmodified lines
modified:docs/commands.rst+5 added-5 removed
23 unmodified lines
2425 @click.group()26 @click.option('--debug/--no-debug', default=False)27 def cli(debug):28 click.echo('Debug mode is %s' % ('on' if debug else 'off'))28 click.echo(f"Debug mode is {'on' if debug else 'off'}")2930 @cli.command() # @cli, not @click!31 def sync():32 click.echo('Syncing')
62 unmodified lines
9596 @cli.command()97 @click.pass_context98 def sync(ctx):99 click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))99 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")100101 if __name__ == '__main__':102 cli(obj={})103
61 unmodified lines
165 def cli(ctx):166 if ctx.invoked_subcommand is None:167 click.echo('I was invoked without subcommand')168 else:169 click.echo('I am about to invoke %s' % ctx.invoked_subcommand)169 click.echo(f"I am about to invoke {ctx.invoked_subcommand}")170171 @cli.command()172 def sync():173 click.echo('The subcommand')
291 unmodified lines
465466 @cli.command()467 @click.option('--port', default=8000)468 def runserver(port):469 click.echo('Serving on http://127.0.0.1:%d/' % port)469 click.echo(f"Serving on http://127.0.0.1:{port}/")470471 if __name__ == '__main__':472 cli(default_map={473 'runserver': {
37 unmodified lines
511512 @cli.command()513 @click.option('--port', default=8000)514 def runserver(port):515 click.echo('Serving on http://127.0.0.1:%d/' % port)515 click.echo(f"Serving on http://127.0.0.1:{port}/")516517 if __name__ == '__main__':518 cli()519
52 unmodified lines
modified:docs/conf.py+5 added
1from pallets_sphinx_themes import get_version2from pallets_sphinx_themes import ProjectLink34import click._compat56# compat until pallets-sphinx-themes is updated7click._compat.text_type = str89# Project --------------------------------------------------------------1011project = "Click"12copyright = "2014 Pallets"
43 unmodified lines
modified:docs/documentation.rst+2 added-2 removed
22 unmodified lines
23 @click.argument('name')24 def hello(count, name):25 """This script prints hello NAME COUNT times."""26 for x in range(count):27 click.echo('Hello %s!' % name)27 click.echo(f"Hello {name}!")2829And what it looks like:3031.. click:run::
140 unmodified lines
172 @click.argument('name', metavar='<name>')173 def hello(count, name):174 """This script prints hello <name> <int> times."""175 for x in range(count):176 click.echo('Hello %s!' % name)176 click.echo(f"Hello {name}!")177178Example:179180.. click:run::
61 unmodified lines
modified:docs/index.rst+2 added-2 removed
34 unmodified lines
35 help='The person to greet.')36 def hello(count, name):37 """Simple program that greets NAME for a total of COUNT times."""38 for x in range(count):39 click.echo('Hello %s!' % name)39 click.echo(f"Hello {name}!")4041 if __name__ == '__main__':42 hello()43
36 unmodified lines
80 testing81 utils82 bashcomplete83 exceptions84 python384 unicode-support85 wincmd8687API Reference88-------------
19 unmodified lines
modified:docs/options.rst+22 added-18 removed
83 unmodified lines
84 @click.command()85 @click.option('--from', '-f', 'from_')86 @click.option('--to', '-t')87 def reserved_param_name(from_, to):88 click.echo('from %s to %s' % (from_, to))88 click.echo(f"from {from_} to {to}")8990And on the command line:9192.. click:run::
27 unmodified lines
120121 @click.command()122 @click.option('--pos', nargs=2, type=float)123 def findme(pos):124 a, b = pos124 click.echo('%s / %s' % pos)125 click.echo(f"{a} / {b}")126127And on the command line:128129.. click:run::
16 unmodified lines
146147 @click.command()148 @click.option('--item', type=(str, int))149 def putitem(item):149 click.echo('name=%s id=%d' % item)150 name, id = item151 click.echo(f"name={name} id={id}")152153And on the command line:154155.. click:run::
8 unmodified lines
164165 @click.command()166 @click.option('--item', nargs=2, type=click.Tuple([str, int]))167 def putitem(item):166 click.echo('name=%s id=%d' % item)168 name, id = item169 click.echo(f"name={name} id={id}")170171.. _multiple-options:172173Multiple Options
40 unmodified lines
214215 @click.command()216 @click.option('-v', '--verbose', count=True)217 def log(verbose):215 click.echo('Verbosity: %s' % verbose)218 click.echo(f"Verbosity: {verbose}")219220And on the command line:221222.. click:run::
60 unmodified lines
283284 @click.command()285 @click.option('/debug;/no-debug')286 def log(debug):284 click.echo('debug=%s' % debug)287 click.echo(f"debug={debug}")288289 if __name__ == '__main__':290 log()291
112 unmodified lines
404405 @click.command()406 @click.option('--name', prompt=True)407 def hello(name):405 click.echo('Hello %s!' % name)408 click.echo(f"Hello {name}!")409410And what it looks like:411412.. click:run::
8 unmodified lines
421422 @click.command()423 @click.option('--name', prompt='Your name please')424 def hello(name):422 click.echo('Hello %s!' % name)425 click.echo(f"Hello {name}!")426427What it looks like:428429.. click:run::
15 unmodified lines
445 @click.command()446 @click.option('--password', prompt=True, hide_input=True,447 confirmation_prompt=True)448 def encrypt(password):446 click.echo('Encrypting password to %s' % password.encode('rot13'))449 click.echo(f"Encrypting password to {password.encode('rot13')}")450451What it looks like:452453.. click:run::
7 unmodified lines
461462 @click.command()463 @click.password_option()464 def encrypt(password):462 click.echo('Encrypting password to %s' % password.encode('rot13'))465 click.echo(f"Encrypting password to {password.encode('rot13')}")466467Dynamic Defaults for Prompts468----------------------------469
157 unmodified lines
627628 @click.command()629 @click.option('--username')630 def greet(username):628 click.echo('Hello %s!' % username)631 click.echo(f'Hello {username}!')632633 if __name__ == '__main__':634 greet(auto_envvar_prefix='GREETER')635
16 unmodified lines
652653 @click.group()654 @click.option('--debug/--no-debug')655 def cli(debug):653 click.echo('Debug mode is %s' % ('on' if debug else 'off'))656 click.echo(f"Debug mode is {'on' if debug else 'off'}")657658 @cli.command()659 @click.option('--username')660 def greet(username):658 click.echo('Hello %s!' % username)661 click.echo(f"Hello {username}!")662663 if __name__ == '__main__':664 cli(auto_envvar_prefix='GREETER')665
13 unmodified lines
679680 @click.command()681 @click.option('--username', envvar='USERNAME')682 def greet(username):680 click.echo('Hello %s!' % username)683 click.echo(f"Hello {username}!")684685 if __name__ == '__main__':686 greet()687
40 unmodified lines
728729.. click:run::730731 import os729 invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep})732 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})733734Other Prefix Characters735-----------------------736
7 unmodified lines
744745 @click.command()746 @click.option('+w/-w')747 def chmod(w):745 click.echo('writable=%s' % w)748 click.echo(f"writable={w}")749750 if __name__ == '__main__':751 chmod()752
11 unmodified lines
764765 @click.command()766 @click.option('/debug;/no-debug')767 def log(debug):765 click.echo('debug=%s' % debug)768 click.echo(f"debug={debug}")769770 if __name__ == '__main__':771 log()772
63 unmodified lines
836837 @click.command()838 @click.option('--rolls', callback=validate_rolls, default='1d6')839 def roll(rolls):837 click.echo('Rolling a %d-sided dice %d time(s)' % rolls)840 sides, times = rolls841 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")842843 if __name__ == '__main__':844 roll()845
7 unmodified lines
deleted:docs/python3.rst-191 removed
1Python 3 Support2================34.. currentmodule:: click56Click supports Python 3, but like all other command line utility libraries,7it suffers from the Unicode text model in Python 3. All examples in the8documentation were written so that they could run on both Python 2.x and9Python 3.4 or higher.1011.. _python3-limitations:1213Python 3 Limitations14--------------------1516At the moment, Click suffers from a few problems with Python 3:1718* The command line in Unix traditionally is in bytes, not Unicode. While19 there are encoding hints for all of this, there are generally some20 situations where this can break. The most common one is SSH21 connections to machines with different locales.2223 Misconfigured environments can currently cause a wide range of Unicode24 problems in Python 3 due to the lack of support for roundtripping25 surrogate escapes. This will not be fixed in Click itself!2627 For more information see :ref:`python3-surrogates`.2829* Standard input and output in Python 3 is opened in Unicode mode by30 default. Click has to reopen the stream in binary mode in certain31 situations. Because there is no standardized way to do this, this32 might not always work. Primarily this can become a problem when33 testing command-line applications.3435 This is not supported::3637 sys.stdin = io.StringIO('Input here')38 sys.stdout = io.StringIO()3940 Instead you need to do this::4142 input = 'Input here'43 in_stream = io.BytesIO(input.encode('utf-8'))44 sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')45 out_stream = io.BytesIO()46 sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')4748 Remember that in that case, you need to use ``out_stream.getvalue()``49 and not ``sys.stdout.getvalue()`` if you want to access the buffer50 contents as the wrapper will not forward that method.5152Python 2 and 3 Differences53--------------------------5455Click attempts to minimize the differences between Python 2 and Python 356by following best practices for both languages.5758In Python 2, the following is true:5960* ``sys.stdin``, ``sys.stdout``, and ``sys.stderr`` are opened in binary61 mode, but under some circumstances they support Unicode output. Click62 attempts to not subvert this but provides support for forcing streams63 to be Unicode-based.64* ``sys.argv`` is always byte-based. Click will pass bytes to all65 input types and convert as necessary. The :class:`STRING` type66 automatically will decode properly the input value into a string by67 trying the most appropriate encodings.68* When dealing with files, Click will never go through the Unicode APIs69 and will instead use the operating system's byte APIs to open the70 files.7172In Python 3, the following is true:7374* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default75 text-based. When Click needs a binary stream, it attempts to discover76 the underlying binary stream. See :ref:`python3-limitations` for how77 this works.78* ``sys.argv`` is always Unicode-based. This also means that the native79 type for input values to the types in Click is Unicode, and not bytes.8081 This causes problems if the terminal is incorrectly set and Python82 does not figure out the encoding. In that case, the Unicode string83 will contain error bytes encoded as surrogate escapes.84* When dealing with files, Click will always use the Unicode file system85 API calls by using the operating system's reported or guessed86 filesystem encoding. Surrogates are supported for filenames, so it87 should be possible to open files through the :class:`File` type even88 if the environment is misconfigured.8990.. _python3-surrogates:9192Python 3 Surrogate Handling93---------------------------9495Click in Python 3 does all the Unicode handling in the standard library96and is subject to its behavior. In Python 2, Click does all the Unicode97handling itself, which means there are differences in error behavior.9899The most glaring difference is that in Python 2, Unicode will "just work",100while in Python 3, it requires extra care. The reason for this is that in101Python 3, the encoding detection is done in the interpreter, and on Linux102and certain other operating systems, its encoding handling is problematic.103104The biggest source of frustration is that Click scripts invoked by105init systems (sysvinit, upstart, systemd, etc.), deployment tools (salt,106puppet), or cron jobs (cron) will refuse to work unless a Unicode locale is107exported.108109If Click encounters such an environment it will prevent further execution110to force you to set a locale. This is done because Click cannot know111about the state of the system once it's invoked and restore the values112before Python's Unicode handling kicked in.113114If you see something like this error in Python 3::115116 Traceback (most recent call last):117 ...118 RuntimeError: Click will abort further execution because Python 3 was119 configured to use ASCII as encoding for the environment. Either switch120 to Python 2 or consult the Python 3 section of the docs for121 mitigation steps.122123.. note::124125 In Python 3.7 and later you will no longer get a ``RuntimeError`` in126 many cases thanks to :pep:`538` and :pep:`540`, which changed the127 default assumption in unconfigured environments.128129You are dealing with an environment where Python 3 thinks you are130restricted to ASCII data. The solution to these problems is different131depending on which locale your computer is running in.132133For instance, if you have a German Linux machine, you can fix the problem134by exporting the locale to ``de_DE.utf-8``::135136 export LC_ALL=de_DE.utf-8137 export LANG=de_DE.utf-8138139If you are on a US machine, ``en_US.utf-8`` is the encoding of choice. On140some newer Linux systems, you could also try ``C.UTF-8`` as the locale::141142 export LC_ALL=C.UTF-8143 export LANG=C.UTF-8144145On some systems it was reported that `UTF-8` has to be written as `UTF8`146and vice versa. To see which locales are supported you can invoke147``locale -a``::148149 locale -a150151You need to do this before you invoke your Python script. If you are152curious about the reasons for this, you can join the discussions in the153Python 3 bug tracker:154155* `ASCII is a bad filesystem default encoding156 <https://bugs.python.org/issue13643#msg149941>`_157* `Use surrogateescape as default error handler158 <https://bugs.python.org/issue19977>`_159* `Python 3 raises Unicode errors in the C locale160 <https://bugs.python.org/issue19846>`_161* `LC_CTYPE=C: pydoc leaves terminal in an unusable state162 <https://bugs.python.org/issue21398>`_ (this is relevant to Click163 because the pager support is provided by the stdlib pydoc module)164165Note (Python 3.7 onwards): Even though your locale may not be properly166configured, Python 3.7 Click will not raise the above exception because Python1673.7 programs are better at choosing default locales. This doesn't change the168general issue that your locale may be misconfigured.169170Unicode Literals171----------------172173Starting with Click 5.0 there will be a warning for the use of the174``unicode_literals`` future import in Python 2. This has been done due to175the negative consequences of this import with regards to unintentionally176causing bugs due to introducing Unicode data to APIs that are incapable of177handling them. For some examples of this issue, see the discussion on178this github issue: `python-future#22179<https://github.com/PythonCharmers/python-future/issues/22>`_.180181If you use ``unicode_literals`` in any file that defines a Click command182or that invokes a click command you will be given a warning. You are183strongly encouraged to not use ``unicode_literals`` and instead use184explicit ``u`` prefixes for your Unicode strings.185186If you do want to ignore the warning and continue using187``unicode_literals`` on your own peril, you can disable the warning as188follows::189190 import click191 click.disable_unicode_literals_warning = True
modified:docs/quickstart.rst+3 added-5 removed
155 unmodified lines
156-------157158Why does this example use :func:`echo` instead of the regular159:func:`print` function? The answer to this question is that Click160attempts to support both Python 2 and Python 3 the same way and to be very160attempts to support different environments consistently and to be very161robust even when the environment is misconfigured. Click wants to be162functional at least on a basic level even if everything is completely163broken.164
3 unmodified lines
168169As an added benefit, starting with Click 2.0, the echo function also170has good support for ANSI colors. It will automatically strip ANSI codes171if the output stream is a file and if colorama is supported, ANSI colors172will also work on Windows. Note that in Python 2, the :func:`echo` function173does not parse color code information from bytearrays. See :ref:`ansi-colors`174for more information.172will also work on Windows. See :ref:`ansi-colors`.173174If you don't need this, you can also use the `print()` construct /175function.176
60 unmodified lines
237 @click.option('--count', default=1, help='number of greetings')238 @click.argument('name')239 def hello(count, name):240 for x in range(count):243 click.echo('Hello %s!' % name)241 click.echo(f"Hello {name}!")242243What it looks like:244245.. click:run::
30 unmodified lines
modified:docs/testing.rst+3 added-3 removed
28 unmodified lines
2930 @click.command()31 @click.argument('name')32 def hello(name):33 click.echo('Hello %s!' % name)33 click.echo(f'Hello {name}!')3435.. code-block:: python36 :caption: test_hello.py37
15 unmodified lines
5354 @click.group()55 @click.option('--debug/--no-debug', default=False)56 def cli(debug):57 click.echo('Debug mode is %s' % ('on' if debug else 'off'))57 click.echo(f"Debug mode is {'on' if debug else 'off'}")5859 @cli.command()60 def sync():61 click.echo('Syncing')
63 unmodified lines
125126 @click.command()127 @click.option('--foo', prompt=True)128 def prompt(foo):129 click.echo('foo=%s' % foo)129 click.echo(f"foo={foo}")130131.. code-block:: python132 :caption: test_prompt.py133
12 unmodified lines
added:docs/unicode-support.rst+112 added
1Unicode Support2===============34.. currentmodule:: click56Click has to take extra care to support Unicode text in different7environments.89* The command line in Unix is traditionally bytes, not Unicode. While10 there are encoding hints, there are some situations where this can11 break. The most common one is SSH connections to machines with12 different locales.1314 Misconfigured environments can cause a wide range of Unicode15 problems due to the lack of support for roundtripping surrogate16 escapes. This will not be fixed in Click itself!1718* Standard input and output is opened in text mode by default. Click19 has to reopen the stream in binary mode in certain situations.20 Because there is no standard way to do this, it might not always21 work. Primarily this can become a problem when testing command-line22 applications.2324 This is not supported::2526 sys.stdin = io.StringIO('Input here')27 sys.stdout = io.StringIO()2829 Instead you need to do this::3031 input = 'Input here'32 in_stream = io.BytesIO(input.encode('utf-8'))33 sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')34 out_stream = io.BytesIO()35 sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')3637 Remember in that case, you need to use ``out_stream.getvalue()``38 and not ``sys.stdout.getvalue()`` if you want to access the buffer39 contents as the wrapper will not forward that method.4041* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default42 text-based. When Click needs a binary stream, it attempts to43 discover the underlying binary stream.4445* ``sys.argv`` is always text. This means that the native type for46 input values to the types in Click is Unicode, not bytes.4748 This causes problems if the terminal is incorrectly set and Python49 does not figure out the encoding. In that case, the Unicode string50 will contain error bytes encoded as surrogate escapes.5152* When dealing with files, Click will always use the Unicode file53 system API by using the operating system's reported or guessed54 filesystem encoding. Surrogates are supported for filenames, so it55 should be possible to open files through the :class:`File` type even56 if the environment is misconfigured.575859Surrogate Handling60------------------6162Click does all the Unicode handling in the standard library and is63subject to its behavior. Unicode requires extra care. The reason for64this is that the encoding detection is done in the interpreter, and on65Linux and certain other operating systems, its encoding handling is66problematic.6768The biggest source of frustration is that Click scripts invoked by init69systems, deployment tools, or cron jobs will refuse to work unless a70Unicode locale is exported.7172If Click encounters such an environment it will prevent further73execution to force you to set a locale. This is done because Click74cannot know about the state of the system once it's invoked and restore75the values before Python's Unicode handling kicked in.7677If you see something like this error::7879 Traceback (most recent call last):80 ...81 RuntimeError: Click will abort further execution because Python was82 configured to use ASCII as encoding for the environment. Consult83 https://click.palletsprojects.com/unicode-support/ for mitigation84 steps.8586You are dealing with an environment where Python thinks you are87restricted to ASCII data. The solution to these problems is different88depending on which locale your computer is running in.8990For instance, if you have a German Linux machine, you can fix the91problem by exporting the locale to ``de_DE.utf-8``::9293 export LC_ALL=de_DE.utf-894 export LANG=de_DE.utf-89596If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.97On some newer Linux systems, you could also try ``C.UTF-8`` as the98locale::99100 export LC_ALL=C.UTF-8101 export LANG=C.UTF-8102103On some systems it was reported that ``UTF-8`` has to be written as104``UTF8`` and vice versa. To see which locales are supported you can105invoke ``locale -a``.106107You need to export the values before you invoke your Python script.108109In Python 3.7 and later you will no longer get a ``RuntimeError`` in110many cases thanks to :pep:`538` and :pep:`540`, which changed the111default assumption in unconfigured environments. This doesn't change the112general issue that your locale may be misconfigured.
modified:docs/utils.rst+17 added-28 removed
11 unmodified lines
12------------------1314The most obvious helper is the :func:`echo` function, which in many ways15works like the Python ``print`` statement or function. The main difference is16that it works the same in Python 2 and 3, it intelligently detects17misconfigured output streams, and it will never fail (except in Python 3; for18more information see :ref:`python3-limitations`).16that it works the same in many different terminal environments.1718Example::1920 import click2122 click.echo('Hello World!')2326Most importantly, it can print both Unicode and binary data, unlike the27built-in ``print`` function in Python 3, which cannot output any bytes. It28will, however, emit a trailing newline by default, which needs to be29suppressed by passing ``nl=False``::24It can output both text and binary data. It will emit a trailing newline25by default, which needs to be suppressed by passing ``nl=False``::2627 click.echo(b'\xe2\x98\x83', nl=False)2829Last but not least :func:`echo` uses click's intelligent internal output30streams to stdout and stderr which support unicode output on the Windows31console. This means for as long as you are using `click.echo` you can32output unicode characters (there are some limitations on the default font37with regards to which characters can be displayed). This functionality is38new in Click 6.0.33with regards to which characters can be displayed).3435.. versionadded:: 6.03642Click now emulates output streams on Windows to support unicode to the37Click emulates output streams on Windows to support unicode to the38Windows console through separate APIs. For more information see39:doc:`wincmd`.4041.. versionadded:: 3.04248Starting with Click 3.0 you can also easily print to standard error by49passing ``err=True``::43You can also easily print to standard error by passing ``err=True``::4445 click.echo('Hello World!', err=True)4647
3 unmodified lines
51-----------5253.. versionadded:: 2.05461Starting with Click 2.0, the :func:`echo` function gained extra62functionality to deal with ANSI colors and styles. Note that on Windows,63this functionality is only available if `colorama`_ is installed. If it64is installed, then ANSI codes are intelligently handled. Note that in Python652, the echo function doesn't parse color code information from bytearrays.55The :func:`echo` function gained extra functionality to deal with ANSI56colors and styles. Note that on Windows, this functionality is only57available if `colorama`_ is installed. If it is installed, then ANSI58codes are intelligently handled.5960Primarily this means that:6162- Click's :func:`echo` function will automatically strip ANSI color codes
41 unmodified lines
104.. click:example::105106 @click.command()107 def less():115 click.echo_via_pager('\n'.join('Line %d' % idx116 for idx in range(200)))108 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))109110If you want to use the pager for a lot of text, especially if generating everything in advance would take a lot of time, you can pass a generator (or generator function) instead of a string:111112.. click:example::113 def _generate_output():114 for idx in range(50000):123 yield "Line %d\n" % idx115 yield f"Line {idx}\n"116117 @click.command()118 def less():119 click.echo_via_pager(_generate_output())
124 unmodified lines
244Printing Filenames245------------------246247Because filenames might not be Unicode, formatting them can be a bit256tricky. Generally, this is easier in Python 2 than on 3, as you can just257write the bytes to stdout with the ``print`` function, but in Python 3, you258will always need to operate in Unicode.248tricky.249250The way this works with click is through the :func:`format_filename`251function. It does a best-effort conversion of the filename to Unicode and252will never fail. This makes it possible to use these filenames in the253context of a full Unicode string.254255Example::256267 click.echo('Path: %s' % click.format_filename(b'foo.txt'))257 click.echo(f"Path: {click.format_filename(b'foo.txt')}")258259260Standard Streams261----------------
8 unmodified lines
270:func:`get_text_stream` functions, which produce consistent results with271different Python versions and for a wide variety of terminal configurations.272273The end result is that these functions will always return a functional284stream object (except in very odd cases in Python 3; see285:ref:`python3-limitations`).274stream object (except in very odd cases; see :doc:`/unicode-support`).275276Example::277278 import click
58 unmodified lines
337 parser.read([cfg])338 rv = {}339 for section in parser.sections():340 for key, value in parser.items(section):352 rv['%s.%s' % (section, key)] = value341 rv[f"{section}.{key}"] = value342 return rv343344345Showing Progress Bars
38 unmodified lines
384 import time385386 with click.progressbar([1, 2, 3]) as bar:387 for x in bar:399 print('sleep({})...'.format(x))388 print(f"sleep({x})...")389 time.sleep(x)390391Another useful feature is to associate a label with the progress bar which392will be shown preceding the progress bar::
17 unmodified lines
modified:docs/why.rst-1 removed
10 unmodified lines
11* supports implementation of Unix/POSIX command line conventions12* supports loading values from environment variables out of the box13* support for prompting of custom values14* is fully nestable and composable15* works the same in Python 2 and 315* supports file handling out of the box16* comes with useful common helpers (getting terminal dimensions,17 ANSI colors, fetching direct keyboard input, screen clearing,18 finding config paths, launching apps and editors, etc.)
128 unmodified lines
modified:docs/wincmd.rst+1 added-17 removed
1 unmodified line
2=====================34.. versionadded:: 6.056Until Click 6.0 there are various bugs and limitations with using Click on7a Windows console. Most notably the decoding of command line arguments8was performed with the wrong encoding on Python 2 and on all versions of9Python output of unicode characters was impossible. Starting with Click106.0 we now emulate output streams on Windows to support unicode to the6Click emulates output streams on Windows to support unicode to the7Windows console through separate APIs and we perform different decoding of8parameters.910Here is a brief overview of how this works and what it means to you.
6 unmodified lines
17performed to the type expected value as late as possible. This has some18advantages as it allows us to accept the data in the most appropriate form19for the operating system and Python version.2025For instance paths are left as bytes on Python 2 unless you explicitly26tell it otherwise.2721This caused some problems on Windows where initially the wrong encoding22was used and garbage ended up in your input data. We not only fixed the23encoding part, but we also now extract unicode parameters from `sys.argv`.2432This means that on Python 2 under Windows, the arguments processed will33*most likely* be of unicode nature and not bytes. This was something that34previously did not really happen unless you explicitly passed in unicode35parameters so your custom types need to be aware of this.3625There is also another limitation with this: if `sys.argv` was modified26prior to invoking a click handler, we have to fall back to the regular27byte input in which case not all unicode values are available but only a28subset of the codepage used for parameters.
13 unmodified lines
42stream will also use ``utf-16-le`` as internal encoding. However there is43some hackery going on that the underlying raw IO buffer is still bypassing44the unicode APIs and byte output through an indirection is still possible.4558This hackery is used on both Python 2 and Python 3 as neither version of59Python has native support for cmd.exe with unicode characters. There are60some limitations you need to be aware of:6146* This unicode support is limited to ``click.echo``, ``click.prompt`` as47 well as ``click.get_text_stream``.48* Depending on if unicode values or byte strings are passed the control49 flow goes completely different places internally which can have some
15 unmodified lines
modified:examples/aliases/aliases.py+5 added-9 removed
1import configparser2import os34import click55try:6 import configparser7except ImportError:8 import ConfigParser as configparser61011class Config(object):7class Config:8 """The config in this example only holds aliases."""910 def __init__(self):11 self.path = os.getcwd()
52 unmodified lines
64 if not matches:65 return None66 elif len(matches) == 1:67 return click.Group.get_command(self, ctx, matches[0])72 ctx.fail("Too many matches: {}".format(", ".join(sorted(matches))))68 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")697071def read_config(ctx, param, value):72 """Callback that is used whenever --config is passed. We use this to
47 unmodified lines
120@cli.command()121@pass_config122def status(config):123 """Shows the status."""128 click.echo("Status for {}".format(config.path))124 click.echo(f"Status for {config.path}")125126127@cli.command()128@pass_config
5 unmodified lines
134def alias(config, alias_, cmd, config_file):135 """Adds an alias to the specified configuration file."""136 config.add_alias(alias_, cmd)137 config.write_config(config_file)142 click.echo("Added '{}' as alias for '{}'".format(alias_, cmd))138 click.echo(f"Added '{alias_}' as alias for '{cmd}'")
modified:examples/bashcompletion/bashcompletion.py+3 added-3 removed
16 unmodified lines
1718@cli.command(help="A command to print environment variables")19@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20def cmd1(envvar):21 click.echo("Environment variable: {}".format(envvar))22 click.echo("Value: {}".format(os.environ[envvar]))21 click.echo(f"Environment variable: {envvar}")22 click.echo(f"Value: {os.environ[envvar]}")232425@click.group(help="A group that holds a subcommand")26def group():
11 unmodified lines
3839@group.command(help="Choose a user")40@click.argument("user", type=click.STRING, autocompletion=list_users)41def subcmd(user):42 click.echo("Chosen user is {}".format(user))42 click.echo(f"Chosen user is {user}")434445cli.add_command(group)
modified:examples/colors/colors.py+3 added-7 removed
28 unmodified lines
2930 Give it a try!31 """32 for color in all_colors:33 click.echo(click.style("I am colored {}".format(color), fg=color))33 click.echo(click.style(f"I am colored {color}", fg=color))34 for color in all_colors:35 click.echo(36 click.style("I am colored {} and bold".format(color), fg=color, bold=True)37 )35 click.echo(click.style(f"I am colored {color} and bold", fg=color, bold=True))36 for color in all_colors:39 click.echo(40 click.style("I am reverse colored {}".format(color), fg=color, reverse=True)41 )37 click.echo(click.style(f"I am reverse colored {color}", fg=color, reverse=True))3839 click.echo(click.style("I am blinking", blink=True))40 click.echo(click.style("I am underlined", underline=True))
modified:examples/complex/complex/commands/cmd_init.py+1 added-1 removed
8 unmodified lines
9def cli(ctx, path):10 """Initializes a repository."""11 if path is None:12 path = ctx.home13 ctx.log("Initialized the repository in %s", click.format_filename(path))13 ctx.log(f"Initialized the repository in {click.format_filename(path)}")
modified:examples/complex/complex/cli.py+2 added-6 removed
5 unmodified lines
67CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX")8910class Environment(object):10class Environment:11 def __init__(self):12 self.verbose = False13 self.home = os.getcwd()14
23 unmodified lines
38 return rv3940 def get_command(self, ctx, name):41 try:42 if sys.version_info[0] == 2:43 name = name.encode("ascii", "replace")44 mod = __import__(45 "complex.commands.cmd_{}".format(name), None, None, ["cli"]46 )42 mod = __import__(f"complex.commands.cmd_{name}", None, None, ["cli"])43 except ImportError:44 return45 return mod.cli46
14 unmodified lines
modified:examples/imagepipe/imagepipe.py+21 added-27 removed
58 unmodified lines
59 """6061 @processor62 def new_func(stream, *args, **kwargs):63 for item in stream:64 yield item65 for item in f(*args, **kwargs):66 yield item63 yield from stream64 yield from f(*args, **kwargs)6566 return update_wrapper(new_func, f)6768
17 unmodified lines
86 can be specified multiple times to load more than one image.87 """88 for image in images:89 try:92 click.echo("Opening '{}'".format(image))90 click.echo(f"Opening '{image}'")91 if image == "-":92 img = Image.open(click.get_binary_stdin())93 img.filename = "-"94 else:95 img = Image.open(image)96 yield img97 except Exception as e:100 click.echo("Could not open image '{}': {}".format(image, e), err=True)98 click.echo(f"Could not open image '{image}': {e}", err=True)99100101@cli.command("save")102@click.option(
8 unmodified lines
111 """Saves all processed images to a series of files."""112 for idx, image in enumerate(images):113 try:114 fn = filename.format(idx + 1)117 click.echo("Saving '{}' as '{}'".format(image.filename, fn))115 click.echo(f"Saving '{image.filename}' as '{fn}'")116 yield image.save(fn)117 except Exception as e:120 click.echo(121 "Could not save image '{}': {}".format(image.filename, e), err=True122 )118 click.echo(f"Could not save image '{image.filename}': {e}", err=True)119120121@cli.command("display")122@processor123def display_cmd(images):124 """Opens all images in an image viewer."""125 for image in images:130 click.echo("Displaying '{}'".format(image.filename))126 click.echo(f"Displaying '{image.filename}'")127 image.show()128 yield image129130
6 unmodified lines
137 the aspect ratio.138 """139 for image in images:140 w, h = (width or image.size[0], height or image.size[1])145 click.echo("Resizing '{}' to {}x{}".format(image.filename, w, h))141 click.echo(f"Resizing '{image.filename}' to {w}x{h}")142 image.thumbnail((w, h))143 yield image144145
9 unmodified lines
155156 if border is not None:157 for idx, val in enumerate(box):158 box[idx] = max(0, val - border)163 click.echo("Cropping '{}' by {}px".format(image.filename, border))159 click.echo(f"Cropping '{image.filename}' by {border}px")160 yield copy_filename(image.crop(box), image)161 else:162 yield image163
7 unmodified lines
171 if value in ("180", "-180"):172 return (Image.ROTATE_180, 180)173 if value in ("-90", "270", "l", "left"):174 return (Image.ROTATE_270, 270)179 raise click.BadParameter("invalid rotation '{}'".format(value))175 raise click.BadParameter(f"invalid rotation '{value}'")176177178def convert_flip(ctx, param, value):179 if value is None:
2 unmodified lines
182 if value in ("lr", "leftright"):183 return (Image.FLIP_LEFT_RIGHT, "left to right")184 if value in ("tb", "topbottom", "upsidedown", "ud"):185 return (Image.FLIP_LEFT_RIGHT, "top to bottom")190 raise click.BadParameter("invalid flip '{}'".format(value))186 raise click.BadParameter(f"invalid flip '{value}'")187188189@cli.command("transpose")190@click.option(
5 unmodified lines
196 """Transposes an image by either rotating or flipping it."""197 for image in images:198 if rotate is not None:199 mode, degrees = rotate204 click.echo("Rotate '{}' by {}deg".format(image.filename, degrees))200 click.echo(f"Rotate '{image.filename}' by {degrees}deg")201 image = copy_filename(image.transpose(mode), image)202 if flip is not None:203 mode, direction = flip208 click.echo("Flip '{}' {}".format(image.filename, direction))204 click.echo(f"Flip '{image.filename}' {direction}")205 image = copy_filename(image.transpose(mode), image)206 yield image207208
3 unmodified lines
212def blur_cmd(images, radius):213 """Applies gaussian blur."""214 blur = ImageFilter.GaussianBlur(radius)215 for image in images:220 click.echo("Blurring '{}' by {}px".format(image.filename, radius))216 click.echo(f"Blurring '{image.filename}' by {radius}px")217 yield copy_filename(image.filter(blur), image)218219220@cli.command("smoothen")
8 unmodified lines
229def smoothen_cmd(images, iterations):230 """Applies a smoothening filter."""231 for image in images:232 click.echo(237 "Smoothening '{}' {} time{}".format(238 image.filename, iterations, "s" if iterations != 1 else ""239 )233 f"Smoothening {image.filename!r} {iterations}"234 f" time{'s' if iterations != 1 else ''}"235 )236 for _ in range(iterations):237 image = copy_filename(image.filter(ImageFilter.BLUR), image)238 yield image
3 unmodified lines
242@processor243def emboss_cmd(images):244 """Embosses an image."""245 for image in images:251 click.echo("Embossing '{}'".format(image.filename))246 click.echo(f"Embossing '{image.filename}'")247 yield copy_filename(image.filter(ImageFilter.EMBOSS), image)248249250@cli.command("sharpen")
3 unmodified lines
254@processor255def sharpen_cmd(images, factor):256 """Sharpens an image."""257 for image in images:263 click.echo("Sharpen '{}' by {}".format(image.filename, factor))258 click.echo(f"Sharpen '{image.filename}' by {factor}")259 enhancer = ImageEnhance.Sharpness(image)260 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)261262
13 unmodified lines
276 if image is not None:277 yield image278 return279285 click.echo("Paste '{}' on '{}'".format(to_paste.filename, image.filename))280 click.echo(f"Paste '{to_paste.filename}' on '{image.filename}'")281 mask = None282 if to_paste.mode == "RGBA" or "transparency" in to_paste.info:283 mask = to_paste284 image.paste(to_paste, (left, right), mask)290 image.filename += "+{}".format(to_paste.filename)285 image.filename += f"+{to_paste.filename}"286 yield image287293 for image in imageiter:294 yield image288 yield from imageiter
modified:examples/naval/naval.py+5 added-5 removed
19 unmodified lines
20@ship.command("new")21@click.argument("name")22def ship_new(name):23 """Creates a new ship."""24 click.echo("Created ship {}".format(name))24 click.echo(f"Created ship {name}")252627@ship.command("move")28@click.argument("ship")
1 unmodified line
30@click.argument("y", type=float)31@click.option("--speed", metavar="KN", default=10, help="Speed in knots.")32def ship_move(ship, x, y, speed):33 """Moves SHIP to the new location X,Y."""34 click.echo("Moving ship {} to {},{} with speed {}".format(ship, x, y, speed))34 click.echo(f"Moving ship {ship} to {x},{y} with speed {speed}")353637@ship.command("shoot")38@click.argument("ship")39@click.argument("x", type=float)40@click.argument("y", type=float)41def ship_shoot(ship, x, y):42 """Makes SHIP fire to X,Y."""43 click.echo("Ship {} fires to {},{}".format(ship, x, y))43 click.echo(f"Ship {ship} fires to {x},{y}")444546@cli.group("mine")47def mine():
12 unmodified lines
60)61@click.option("ty", "--drifting", flag_value="drifting", help="Drifting mine.")62def mine_set(x, y, ty):63 """Sets a mine at a specific coordinate."""64 click.echo("Set {} mine at {},{}".format(ty, x, y))64 click.echo(f"Set {ty} mine at {x},{y}")656667@mine.command("remove")68@click.argument("x", type=float)69@click.argument("y", type=float)70def mine_remove(x, y):71 """Removes a mine at a specific coordinate."""72 click.echo("Removed mine at {},{}".format(x, y))72 click.echo(f"Removed mine at {x},{y}")
modified:examples/repo/repo.py+10 added-10 removed
3 unmodified lines
45import click678class Repo(object):8class Repo:9 def __init__(self, home):10 self.home = home11 self.config = {}12 self.verbose = False1314 def set_config(self, key, value):15 self.config[key] = value16 if self.verbose:17 click.echo(" config[{}] = {}".format(key, value), file=sys.stderr)17 click.echo(f" config[{key}] = {value}", file=sys.stderr)1819 def __repr__(self):20 return "<Repo {}>".format(self.home)20 return f"<Repo {self.home}>"212223pass_repo = click.make_pass_decorator(Repo)24
52 unmodified lines
77 of SRC and create that folder.78 """79 if dest is None:80 dest = posixpath.split(src)[-1] or "."81 click.echo("Cloning repo {} to {}".format(src, os.path.abspath(dest)))81 click.echo(f"Cloning repo {src} to {os.path.basename(dest)}")82 repo.home = dest83 if shallow:84 click.echo("Making shallow checkout")85 click.echo("Checking out revision {}".format(rev))85 click.echo(f"Checking out revision {rev}")868788@cli.command()89@click.confirmation_option()
2 unmodified lines
92 """Deletes a repository.9394 This will throw away the current repository.95 """96 click.echo("Destroying repo {}".format(repo.home))96 click.echo(f"Destroying repo {repo.home}")97 click.echo("Deleted!")9899100@cli.command()
34 unmodified lines
135 if not message:136 marker = "# Files to be committed:"137 hint = ["", "", marker, "#"]138 for file in files:139 hint.append("# U {}".format(file))139 hint.append(f"# U {file}")140 message = click.edit("\n".join(hint))141 if message is None:142 click.echo("Aborted!")143 return
2 unmodified lines
146 click.echo("Aborted! Empty commit message")147 return148 else:149 msg = "\n".join(message)150 click.echo("Files to be committed: {}".format(files))151 click.echo("Commit message:\n{}".format(msg))150 click.echo(f"Files to be committed: {files}")151 click.echo(f"Commit message:\n{msg}")152153154@cli.command(short_help="Copies files.")155@click.option(
6 unmodified lines
162 """Copies one or multiple files to a new location. This copies all163 files from SRC to DST.164 """165 for fn in src:166 click.echo("Copy from {} -> {}".format(fn, dst))166 click.echo(f"Copy from {fn} -> {dst}")
modified:examples/termui/termui.py+8 added-9 removed
1# coding: utf-81import math2import random3import time4
9 unmodified lines
14@cli.command()15def colordemo():16 """Demonstrates ANSI color support."""17 for color in "red", "green", "blue":19 click.echo(click.style("I am colored {}".format(color), fg=color))20 click.echo(click.style("I am background colored {}".format(color), bg=color))18 click.echo(click.style(f"I am colored {color}", fg=color))19 click.echo(click.style(f"I am background colored {color}", bg=color))202122@cli.command()23def pager():24 """Demonstrates using the pager."""25 lines = []26 for x in range(200):28 lines.append("{}. Hello World!".format(click.style(str(x), fg="green")))27 lines.append(f"{click.style(str(x), fg='green')}. Hello World!")28 click.echo_via_pager("\n".join(lines))293031@cli.command()
22 unmodified lines
54 process_slowly(item)5556 def show_item(item):57 if item is not None:59 return "Item #{}".format(item)58 return f"Item #{item}"5960 with click.progressbar(61 filter(items),62 label="Committing transaction",
6 unmodified lines
69 with click.progressbar(70 length=count,71 label="Counting",72 bar_template="%(label)s %(bar)s | %(info)s",74 fill_char=click.style(u"█", fg="cyan"),73 fill_char=click.style("█", fg="cyan"),74 empty_char=" ",75 ) as bar:76 for item in bar:77 process_slowly(item)
14 unmodified lines
92 with click.progressbar(93 length=count,94 show_percent=False,95 label="Slowing progress bar",97 fill_char=click.style(u"█", fg="green"),96 fill_char=click.style("█", fg="green"),97 ) as bar:98 for item in steps:99 time.sleep(item)100 bar.update(item)
16 unmodified lines
117@cli.command()118def edit():119 """Opens an editor with some text in it."""120 MARKER = "# Everything below is ignored\n"122 message = click.edit("\n\n{}".format(MARKER))121 message = click.edit(f"\n\n{MARKER}")122 if message is not None:123 msg = message.split(MARKER, 1)[0].rstrip("\n")124 if not msg:125 click.echo("Empty message!")126 else:128 click.echo("Message:\n{}".format(msg))127 click.echo(f"Message:\n{msg}")128 else:129 click.echo("You did not enter anything!")130131
38 unmodified lines
modified:examples/validation/validation.py+6 added-10 removed
1from urllib import parse as urlparse23import click43try:4 from urllib import parse as urlparse5except ImportError:6 import urlparse586def validate_count(ctx, param, value):7 if value < 0 or value % 2 != 0:8 raise click.BadParameter("Should be a positive, even integer.")9 return value
6 unmodified lines
16 if not isinstance(value, tuple):17 value = urlparse.urlparse(value)18 if value.scheme not in ("http", "https"):19 self.fail(23 "invalid URL scheme ({}). Only HTTP URLs are"24 " allowed".format(value.scheme),20 f"invalid URL scheme ({value.scheme}). Only HTTP URLs are allowed",21 param,22 ctx,23 )24 return value
17 unmodified lines
42 raise click.BadParameter(43 'If a value is provided it needs to be the value "wat".',44 param_hint=["--foo"],45 )50 click.echo("count: {}".format(count))51 click.echo("foo: {}".format(foo))52 click.echo("url: {!r}".format(url))46 click.echo(f"count: {count}")47 click.echo(f"foo: {foo}")48 click.echo(f"url: {url!r}")
modified:src/click/__init__.py+1 added-5 removed
70 unmodified lines
71from .utils import get_os_args72from .utils import get_text_stream73from .utils import open_file7475# Controls if click should emit the warning about the use of unicode76# literals.77disable_unicode_literals_warning = False7879__version__ = "8.0.dev"75__version__ = "8.0.0.dev"
modified:src/click/_bashcomplete.py+3 added-7 removed
1import copy2import os3import re4from collections import abc56from .core import Argument7from .core import MultiCommand8from .core import Option9from .parser import split_arg_string10from .types import Choice11from .utils import echo1212try:13 from collections import abc14except ImportError:15 import collections as abc1613WORDBREAK = "="1415# Note, only BASH version 4.4 and later have the nosort option.16COMPLETION_SCRIPT_BASH = """
76 unmodified lines
93 script = _completion_scripts.get(shell, COMPLETION_SCRIPT_BASH)94 return (95 script96 % {101 "complete_func": "_{}_completion".format(cf_name),97 "complete_func": f"_{cf_name}_completion",98 "script_names": prog_name,99 "autocomplete_var": complete_var,100 }101 ).strip() + ";"
242 unmodified lines
344 args = cwords[1:]345346 for item in get_choices(cli, prog_name, args, incomplete):347 if item[1]:352 echo("{arg}\t{desc}".format(arg=item[0], desc=item[1]))348 echo(f"{item[0]}\t{item[1]}")349 else:350 echo(item[0])351352 return True
19 unmodified lines
modified:src/click/_compat.py+172 added-351 removed
1# flake8: noqa1import codecs2import io3import os4import re5import sys6from weakref import WeakKeyDictionary79PY2 = sys.version_info[0] == 28CYGWIN = sys.platform.startswith("cygwin")9MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)10# Determine local App Engine environment, per Google's own suggestion11APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(12 "SERVER_SOFTWARE", ""13)14WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS215DEFAULT_COLUMNS = 80181916auto_wrap_for_ansi = None17colorama = None18get_winterm_size = None19_ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")202122def get_filesystem_encoding():
40 unmodified lines
63 encoding,64 errors,65 force_readable=False,66 force_writable=False,68 **extra67 **extra,68 ):69 self._stream = stream = _FixupStream(stream, force_readable, force_writable)71 io.TextIOWrapper.__init__(self, stream, encoding, errors, **extra)70 super().__init__(stream, encoding, errors, **extra)7173 # The io module is a place where the Python 3 text behavior74 # was forced upon Python 2, so we need to unbreak75 # it to look like Python 2.76 if PY2:7778 def write(self, x):79 if isinstance(x, str) or is_bytes(x):80 try:81 self.flush()82 except Exception:83 pass84 return self.buffer.write(str(x))85 return io.TextIOWrapper.write(self, x)8687 def writelines(self, lines):88 for line in lines:89 self.write(line)9072 def __del__(self):73 try:74 self.detach()75 except Exception:
3 unmodified lines
79 # https://bitbucket.org/pypy/pypy/issue/180380 return self._stream.isatty()8182102class _FixupStream(object):83class _FixupStream:84 """The new io interface needs more from streams than streams85 traditionally implement. As such, this fix-up code is necessary in86 some circumstances.87
13 unmodified lines
101 def read1(self, size):102 f = getattr(self._stream, "read1", None)103 if f is not None:104 return f(size)124 # We only dispatch to readline instead of read in Python 2 as we125 # do not want cause problems with the different implementation126 # of line buffering.127 if PY2:128 return self._stream.readline(size)105106 return self._stream.read(size)107108 def readable(self):109 if self._force_readable:
32 unmodified lines
142 return False143 return True144145169if PY2:170 text_type = unicode171 raw_input = raw_input172 string_types = (str, unicode)173 int_types = (int, long)174 iteritems = lambda x: x.iteritems()175 range_type = xrange146def is_bytes(x):147 return isinstance(x, (bytes, memoryview, bytearray))148177 from pipes import quote as shlex_quote149179 def is_bytes(x):180 return isinstance(x, (buffer, bytearray))181182 _identifier_re = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")183184 # For Windows, we need to force stdout/stdin/stderr to binary if it's185 # fetched for that. This obviously is not the most correct way to do186 # it as it changes global state. Unfortunately, there does not seem to187 # be a clear better way to do it as just reopening the file in binary188 # mode does not change anything.189 #190 # An option would be to do what Python 3 does and to open the file as191 # binary only, patch it back to the system, and then use a wrapper192 # stream that converts newlines. It's not quite clear what's the193 # correct option here.194 #195 # This code also lives in _winconsole for the fallback to the console196 # emulation stream.197 #198 # There are also Windows environments where the `msvcrt` module is not199 # available (which is why we use try-catch instead of the WIN variable200 # here), such as the Google App Engine development server on Windows. In201 # those cases there is just nothing we can do.202 def set_binary_mode(f):203 return f204150def _is_binary_reader(stream, default=False):151 try:206 import msvcrt207 except ImportError:208 pass209 else:152 return isinstance(stream.read(0), bytes)153 except Exception:154 return default155 # This happens in some cases where the stream was already156 # closed. In this case, we assume the default.157211 def set_binary_mode(f):212 try:213 fileno = f.fileno()214 except Exception:215 pass216 else:217 msvcrt.setmode(fileno, os.O_BINARY)218 return f158159def _is_binary_writer(stream, default=False):160 try:221 import fcntl222 except ImportError:223 pass224 else:161 stream.write(b"")162 except Exception:163 try:164 stream.write("")165 return False166 except Exception:167 pass168 return default169 return True170226 def set_binary_mode(f):227 try:228 fileno = f.fileno()229 except Exception:230 pass231 else:232 flags = fcntl.fcntl(fileno, fcntl.F_GETFL)233 fcntl.fcntl(fileno, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)234 return f171236 def isidentifier(x):237 return _identifier_re.search(x) is not None172def _find_binary_reader(stream):173 # We need to figure out if the given stream is already binary.174 # This can happen because the official docs recommend detaching175 # the streams to get binary streams. Some code might do this, so176 # we need to deal with this case explicitly.177 if _is_binary_reader(stream, False):178 return stream179239 def get_binary_stdin():240 return set_binary_mode(sys.stdin)180 buf = getattr(stream, "buffer", None)181242 def get_binary_stdout():243 _wrap_std_stream("stdout")244 return set_binary_mode(sys.stdout)182 # Same situation here; this time we assume that the buffer is183 # actually binary in case it's closed.184 if buf is not None and _is_binary_reader(buf, True):185 return buf186246 def get_binary_stderr():247 _wrap_std_stream("stderr")248 return set_binary_mode(sys.stderr)187250 def get_text_stdin(encoding=None, errors=None):251 rv = _get_windows_console_stream(sys.stdin, encoding, errors)252 if rv is not None:253 return rv254 return _make_text_stream(sys.stdin, encoding, errors, force_readable=True)188def _find_binary_writer(stream):189 # We need to figure out if the given stream is already binary.190 # This can happen because the official docs recommend detaching191 # the streams to get binary streams. Some code might do this, so192 # we need to deal with this case explicitly.193 if _is_binary_writer(stream, False):194 return stream195256 def get_text_stdout(encoding=None, errors=None):257 _wrap_std_stream("stdout")258 rv = _get_windows_console_stream(sys.stdout, encoding, errors)259 if rv is not None:260 return rv261 return _make_text_stream(sys.stdout, encoding, errors, force_writable=True)196 buf = getattr(stream, "buffer", None)197263 def get_text_stderr(encoding=None, errors=None):264 _wrap_std_stream("stderr")265 rv = _get_windows_console_stream(sys.stderr, encoding, errors)266 if rv is not None:267 return rv268 return _make_text_stream(sys.stderr, encoding, errors, force_writable=True)198 # Same situation here; this time we assume that the buffer is199 # actually binary in case it's closed.200 if buf is not None and _is_binary_writer(buf, True):201 return buf202270 def filename_to_ui(value):271 if isinstance(value, bytes):272 value = value.decode(get_filesystem_encoding(), "replace")273 return value203204def _stream_is_misconfigured(stream):205 """A stream is misconfigured if its encoding is ASCII."""206 # If the stream does not have an encoding set, we assume it's set207 # to ASCII. This appears to happen in certain unittest208 # environments. It's not quite clear what the correct behavior is209 # but this at least will force Click to recover somehow.210 return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")211276else:277 import io212279 text_type = str280 raw_input = input281 string_types = (str,)282 int_types = (int,)283 range_type = range284 isidentifier = lambda x: x.isidentifier()285 iteritems = lambda x: iter(x.items())213def _is_compat_stream_attr(stream, attr, value):214 """A stream attribute is compatible if it is equal to the215 desired value or the desired value is unset and the attribute216 has a value.217 """218 stream_value = getattr(stream, attr, None)219 return stream_value == value or (value is None and stream_value is not None)220287 from shlex import quote as shlex_quote221289 def is_bytes(x):290 return isinstance(x, (bytes, memoryview, bytearray))222def _is_compatible_text_stream(stream, encoding, errors):223 """Check if a stream's encoding and errors attributes are224 compatible with the desired values.225 """226 return _is_compat_stream_attr(227 stream, "encoding", encoding228 ) and _is_compat_stream_attr(stream, "errors", errors)229292 def _is_binary_reader(stream, default=False):293 try:294 return isinstance(stream.read(0), bytes)295 except Exception:296 return default297 # This happens in some cases where the stream was already298 # closed. In this case, we assume the default.230300 def _is_binary_writer(stream, default=False):301 try:302 stream.write(b"")303 except Exception:304 try:305 stream.write("")306 return False307 except Exception:308 pass309 return default310 return True231def _force_correct_text_stream(232 text_stream,233 encoding,234 errors,235 is_binary,236 find_binary,237 force_readable=False,238 force_writable=False,239):240 if is_binary(text_stream, False):241 binary_reader = text_stream242 else:243 # If the stream looks compatible, and won't default to a244 # misconfigured ascii encoding, return it as-is.245 if _is_compatible_text_stream(text_stream, encoding, errors) and not (246 encoding is None and _stream_is_misconfigured(text_stream)247 ):248 return text_stream249312 def _find_binary_reader(stream):313 # We need to figure out if the given stream is already binary.314 # This can happen because the official docs recommend detaching315 # the streams to get binary streams. Some code might do this, so316 # we need to deal with this case explicitly.317 if _is_binary_reader(stream, False):318 return stream250 # Otherwise, get the underlying binary reader.251 binary_reader = find_binary(text_stream)252320 buf = getattr(stream, "buffer", None)253 # If that's not possible, silently use the original reader254 # and get mojibake instead of exceptions.255 if binary_reader is None:256 return text_stream257322 # Same situation here; this time we assume that the buffer is323 # actually binary in case it's closed.324 if buf is not None and _is_binary_reader(buf, True):325 return buf258 # Default errors to replace instead of strict in order to get259 # something that works.260 if errors is None:261 errors = "replace"262327 def _find_binary_writer(stream):328 # We need to figure out if the given stream is already binary.329 # This can happen because the official docs recommend detaching330 # the streams to get binary streams. Some code might do this, so331 # we need to deal with this case explicitly.332 if _is_binary_writer(stream, False):333 return stream263 # Wrap the binary stream in a text stream with the correct264 # encoding parameters.265 return _make_text_stream(266 binary_reader,267 encoding,268 errors,269 force_readable=force_readable,270 force_writable=force_writable,271 )272335 buf = getattr(stream, "buffer", None)273337 # Same situation here; this time we assume that the buffer is338 # actually binary in case it's closed.339 if buf is not None and _is_binary_writer(buf, True):340 return buf274def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):275 return _force_correct_text_stream(276 text_reader,277 encoding,278 errors,279 _is_binary_reader,280 _find_binary_reader,281 force_readable=force_readable,282 )283342 def _stream_is_misconfigured(stream):343 """A stream is misconfigured if its encoding is ASCII."""344 # If the stream does not have an encoding set, we assume it's set345 # to ASCII. This appears to happen in certain unittest346 # environments. It's not quite clear what the correct behavior is347 # but this at least will force Click to recover somehow.348 return is_ascii_encoding(getattr(stream, "encoding", None) or "ascii")284350 def _is_compat_stream_attr(stream, attr, value):351 """A stream attribute is compatible if it is equal to the352 desired value or the desired value is unset and the attribute353 has a value.354 """355 stream_value = getattr(stream, attr, None)356 return stream_value == value or (value is None and stream_value is not None)357358 def _is_compatible_text_stream(stream, encoding, errors):359 """Check if a stream's encoding and errors attributes are360 compatible with the desired values.361 """362 return _is_compat_stream_attr(363 stream, "encoding", encoding364 ) and _is_compat_stream_attr(stream, "errors", errors)365366 def _force_correct_text_stream(367 text_stream,285def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):286 return _force_correct_text_stream(287 text_writer,288 encoding,289 errors,370 is_binary,371 find_binary,372 force_readable=False,373 force_writable=False,374 ):375 if is_binary(text_stream, False):376 binary_reader = text_stream377 else:378 # If the stream looks compatible, and won't default to a379 # misconfigured ascii encoding, return it as-is.380 if _is_compatible_text_stream(text_stream, encoding, errors) and not (381 encoding is None and _stream_is_misconfigured(text_stream)382 ):383 return text_stream290 _is_binary_writer,291 _find_binary_writer,292 force_writable=force_writable,293 )294385 # Otherwise, get the underlying binary reader.386 binary_reader = find_binary(text_stream)295388 # If that's not possible, silently use the original reader389 # and get mojibake instead of exceptions.390 if binary_reader is None:391 return text_stream296def get_binary_stdin():297 reader = _find_binary_reader(sys.stdin)298 if reader is None:299 raise RuntimeError("Was not able to determine binary stream for sys.stdin.")300 return reader301393 # Default errors to replace instead of strict in order to get394 # something that works.395 if errors is None:396 errors = "replace"302398 # Wrap the binary stream in a text stream with the correct399 # encoding parameters.400 return _make_text_stream(401 binary_reader,402 encoding,403 errors,404 force_readable=force_readable,405 force_writable=force_writable,406 )303def get_binary_stdout():304 writer = _find_binary_writer(sys.stdout)305 if writer is None:306 raise RuntimeError("Was not able to determine binary stream for sys.stdout.")307 return writer308408 def _force_correct_text_reader(text_reader, encoding, errors, force_readable=False):409 return _force_correct_text_stream(410 text_reader,411 encoding,412 errors,413 _is_binary_reader,414 _find_binary_reader,415 force_readable=force_readable,416 )309418 def _force_correct_text_writer(text_writer, encoding, errors, force_writable=False):419 return _force_correct_text_stream(420 text_writer,421 encoding,422 errors,423 _is_binary_writer,424 _find_binary_writer,425 force_writable=force_writable,426 )310def get_binary_stderr():311 writer = _find_binary_writer(sys.stderr)312 if writer is None:313 raise RuntimeError("Was not able to determine binary stream for sys.stderr.")314 return writer315428 def get_binary_stdin():429 reader = _find_binary_reader(sys.stdin)430 if reader is None:431 raise RuntimeError("Was not able to determine binary stream for sys.stdin.")432 return reader316434 def get_binary_stdout():435 writer = _find_binary_writer(sys.stdout)436 if writer is None:437 raise RuntimeError(438 "Was not able to determine binary stream for sys.stdout."439 )440 return writer317def get_text_stdin(encoding=None, errors=None):318 rv = _get_windows_console_stream(sys.stdin, encoding, errors)319 if rv is not None:320 return rv321 return _force_correct_text_reader(sys.stdin, encoding, errors, force_readable=True)322442 def get_binary_stderr():443 writer = _find_binary_writer(sys.stderr)444 if writer is None:445 raise RuntimeError(446 "Was not able to determine binary stream for sys.stderr."447 )448 return writer323450 def get_text_stdin(encoding=None, errors=None):451 rv = _get_windows_console_stream(sys.stdin, encoding, errors)452 if rv is not None:453 return rv454 return _force_correct_text_reader(455 sys.stdin, encoding, errors, force_readable=True456 )324def get_text_stdout(encoding=None, errors=None):325 rv = _get_windows_console_stream(sys.stdout, encoding, errors)326 if rv is not None:327 return rv328 return _force_correct_text_writer(sys.stdout, encoding, errors, force_writable=True)329458 def get_text_stdout(encoding=None, errors=None):459 rv = _get_windows_console_stream(sys.stdout, encoding, errors)460 if rv is not None:461 return rv462 return _force_correct_text_writer(463 sys.stdout, encoding, errors, force_writable=True464 )330466 def get_text_stderr(encoding=None, errors=None):467 rv = _get_windows_console_stream(sys.stderr, encoding, errors)468 if rv is not None:469 return rv470 return _force_correct_text_writer(471 sys.stderr, encoding, errors, force_writable=True472 )331def get_text_stderr(encoding=None, errors=None):332 rv = _get_windows_console_stream(sys.stderr, encoding, errors)333 if rv is not None:334 return rv335 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)336474 def filename_to_ui(value):475 if isinstance(value, bytes):476 value = value.decode(get_filesystem_encoding(), "replace")477 else:478 value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace")479 return value337338def filename_to_ui(value):339 if isinstance(value, bytes):340 value = value.decode(get_filesystem_encoding(), "replace")341 else:342 value = value.encode("utf-8", "surrogateescape").decode("utf-8", "replace")343 return value344345482def get_streerror(e, default=None):346def get_strerror(e, default=None):347 if hasattr(e, "strerror"):348 msg = e.strerror349 else:350 if default is not None:
5 unmodified lines
356 return msg357358359def _wrap_io_open(file, mode, encoding, errors):496 """On Python 2, :func:`io.open` returns a text file wrapper that497 requires passing ``unicode`` to ``write``. Need to open the file in498 binary mode then wrap it in a subclass that can write ``str`` and499 ``unicode``.360 """Handles not passing ``encoding`` and ``errors`` in binary mode."""361 if "b" in mode:362 return open(file, mode)363501 Also handles not passing ``encoding`` and ``errors`` in binary mode.502 """503 binary = "b" in mode364 return open(file, mode, encoding=encoding, errors=errors)365505 if binary:506 kwargs = {}507 else:508 kwargs = {"encoding": encoding, "errors": errors}366510 if not PY2 or binary:511 return io.open(file, mode, **kwargs)512513 f = io.open(file, "{}b".format(mode.replace("t", "")))514 return _make_text_stream(f, **kwargs)515516367def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):368 binary = "b" in mode369370 # Standard streams first. These are simple because they don't need
43 unmodified lines
414415 while True:416 tmp_filename = os.path.join(417 os.path.dirname(filename),568 ".__atomic-write{:08x}".format(random.randrange(1 << 32)),418 f".__atomic-write{random.randrange(1 << 32):08x}",419 )420 try:421 fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)422 break
13 unmodified lines
436 f = _wrap_io_open(fd, mode, encoding, errors)437 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True438439590# Used in a destructor call, needs extra protection from interpreter cleanup.591if hasattr(os, "replace"):592 _replace = os.replace593 _can_replace = True594else:595 _replace = os.rename596 _can_replace = not WIN597598599class _AtomicFile(object):440class _AtomicFile:441 def __init__(self, f, tmp_filename, real_filename):442 self._f = f443 self._tmp_filename = tmp_filename444 self._real_filename = real_filename
6 unmodified lines
451 def close(self, delete=False):452 if self.closed:453 return454 self._f.close()614 if not _can_replace:615 try:616 os.remove(self._real_filename)617 except OSError:618 pass619 _replace(self._tmp_filename, self._real_filename)455 os.replace(self._tmp_filename, self._real_filename)456 self.closed = True457458 def __getattr__(self, name):459 return getattr(self._f, name)
7 unmodified lines
467 def __repr__(self):468 return repr(self._f)469470635auto_wrap_for_ansi = None636colorama = None637get_winterm_size = None638639471def strip_ansi(value):472 return _ansi_re.sub("", value)473474
23 unmodified lines
498if WIN:499 # Windows has a smaller terminal500 DEFAULT_COLUMNS = 79501671 from ._winconsole import _get_windows_console_stream, _wrap_std_stream502 from ._winconsole import _get_windows_console_stream503504 def _get_argv_encoding():505 import locale506507 return locale.getpreferredencoding()508678 if PY2:679680 def raw_input(prompt=""):681 sys.stderr.flush()682 if prompt:683 stdout = _default_text_stdout()684 stdout.write(prompt)685 stdin = _default_text_stdin()686 return stdin.readline().rstrip("\r\n")687509 try:510 import colorama511 except ImportError:512 pass
19 unmodified lines
532533 def _safe_write(s):534 try:535 return _write(s)715 except:536 except BaseException:537 ansi_wrapper.reset_all()538 raise539540 rv.write = _safe_write
14 unmodified lines
555556 def _get_argv_encoding():557 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()558738 _get_windows_console_stream = lambda *x: None739 _wrap_std_stream = lambda *x: None559 def _get_windows_console_stream(f, encoding, errors):560 return None561562563def term_len(x):564 return len(strip_ansi(x))
47 unmodified lines
modified:src/click/_termui_impl.py+26 added-36 removed
1# -*- coding: utf-8 -*-1"""2This module contains implementations for the termui module. To keep the3import time of Click down, some infrequently used functionality is4placed in this module and only imported as needed.5"""6import contextlib7import math8import os9import shlex10import sys11import time1213from ._compat import _default_text_stdout14from ._compat import CYGWIN15from ._compat import get_best_encoding16from ._compat import int_types16from ._compat import isatty17from ._compat import open_stream19from ._compat import range_type20from ._compat import shlex_quote18from ._compat import strip_ansi19from ._compat import term_len20from ._compat import WIN21from .exceptions import ClickException
19 unmodified lines
41 try:42 hint = get_hint(obj)43 except TypeError:44 return None48 if hint is NotImplemented or not isinstance(hint, int_types) or hint < 0:45 if hint is NotImplemented or not isinstance(hint, int) or hint < 0:46 return None47 return hint484953class ProgressBar(object):50class ProgressBar:51 def __init__(52 self,53 iterable,54 length=None,
30 unmodified lines
85 length = _length_hint(iterable)86 if iterable is None:87 if length is None:88 raise TypeError("iterable or length is required")92 iterable = range_type(length)89 iterable = range(length)90 self.iter = iter(iterable)91 self.length = length92 self.length_known = length is not None93 self.pos = 0
29 unmodified lines
123 # so it is re-entry safe. Calling `next(self.generator())`124 # twice works and does "what you want".125 return next(iter(self))126130 # Python 2 compat131 next = __next__132127 def is_fast(self):128 return time.time() - self.start <= self.short_limit129130 def render_finish(self):
29 unmodified lines
160 t //= 60161 hours = t % 24162 t //= 24163 if t > 0:170 return "{}d {:02}:{:02}:{:02}".format(t, hours, minutes, seconds)164 return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"165 else:172 return "{:02}:{:02}:{:02}".format(hours, minutes, seconds)166 return f"{hours:02}:{minutes:02}:{seconds:02}"167 return ""168169 def format_pos(self):170 pos = str(self.pos)171 if self.length_known:178 pos += "/{}".format(self.length)172 pos += f"/{self.length}"173 return pos174175 def format_pct(self):182 return "{: 4}%".format(int(self.pct * 100))[1:]176 return f"{int(self.pct * 100): 4}%"[1:]177178 def format_bar(self):179 if self.length_known:180 bar_length = int(self.pct * self.width)
138 unmodified lines
319 if not self.entered:320 raise RuntimeError("You need to use progress bars in a with block.")321322 if self.is_hidden:329 for rv in self.iter:330 yield rv323 yield from self.iter324 else:325 for rv in self.iter:326 self.current_item = rv327 yield rv
23 unmodified lines
351352 fd, filename = tempfile.mkstemp()353 os.close(fd)354 try:362 if (363 hasattr(os, "system")364 and os.system("more {}".format(shlex_quote(filename))) == 0365 ):355 if hasattr(os, "system") and os.system(f"more {shlex.quote(filename)}") == 0:356 return _pipepager(generator, "more", color)357 return _nullpager(stdout, generator, color)358 finally:359 os.unlink(filename)
10 unmodified lines
370 # If we're piping to less we might support colors under the371 # condition that372 cmd_detail = cmd.rsplit("/", 1)[-1].split()373 if color is None and cmd_detail[0] == "less":384 less_flags = "{}{}".format(os.environ.get("LESS", ""), " ".join(cmd_detail[1:]))374 less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_detail[1:])}"375 if not less_flags:376 env["LESS"] = "-R"377 color = True378 elif "r" in less_flags or "R" in less_flags:
6 unmodified lines
385 if not color:386 text = strip_ansi(text)387388 c.stdin.write(text.encode(encoding, "replace"))399 except (IOError, KeyboardInterrupt):389 except (OSError, KeyboardInterrupt):390 pass391 else:392 c.stdin.close()393
26 unmodified lines
420 encoding = get_best_encoding(sys.stdout)421 with open_stream(filename, "wb")[0] as f:422 f.write(text.encode(encoding))423 try:434 os.system("{} {}".format(shlex_quote(cmd), shlex_quote(filename)))424 os.system(f"{shlex.quote(cmd)} {shlex.quote(filename)}")425 finally:426 os.unlink(filename)427428
4 unmodified lines
433 text = strip_ansi(text)434 stream.write(text)435436447class Editor(object):437class Editor:438 def __init__(self, editor=None, env=None, require_save=True, extension=".txt"):439 self.editor = editor440 self.env = env441 self.require_save = require_save
8 unmodified lines
450 return rv451 if WIN:452 return "notepad"453 for editor in "sensible-editor", "vim", "nano":464 if os.system("which {} >/dev/null 2>&1".format(editor)) == 0:454 if os.system(f"which {editor} >/dev/null 2>&1") == 0:455 return editor456 return "vi"457458 def edit_file(self, filename):
6 unmodified lines
465 else:466 environ = None467 try:468 c = subprocess.Popen(479 "{} {}".format(shlex_quote(editor), shlex_quote(filename)),469 f"{shlex.quote(editor)} {shlex.quote(filename)}",470 env=environ,471 shell=True,472 )473 exit_code = c.wait()474 if exit_code != 0:485 raise ClickException("{}: Editing failed!".format(editor))475 raise ClickException(f"{editor}: Editing failed!")476 except OSError as e:487 raise ClickException("{}: Editing failed: {}".format(editor, e))477 raise ClickException(f"{editor}: Editing failed: {e}")478479 def edit(self, text):480 import tempfile481
60 unmodified lines
542 null.close()543 elif WIN:544 if locate:545 url = _unquote_file(url)556 args = "explorer /select,{}".format(shlex_quote(url))546 args = f"explorer /select,{shlex.quote(url)}"547 else:558 args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex_quote(url))548 args = f"start {'/WAIT' if wait else ''} \"\" {shlex.quote(url)}"549 return os.system(args)550 elif CYGWIN:551 if locate:552 url = _unquote_file(url)563 args = "cygstart {}".format(shlex_quote(os.path.dirname(url)))553 args = f"cygstart {shlex.quote(os.path.dirname(url))}"554 else:565 args = "cygstart {} {}".format("-w" if wait else "", shlex_quote(url))555 args = f"cygstart {'-w' if wait else ''} {shlex.quote(url)}"556 return os.system(args)557558 try:559 if locate:
13 unmodified lines
573 return 1574575576def _translate_ch_to_exc(ch):587 if ch == u"\x03":577 if ch == "\x03":578 raise KeyboardInterrupt()589 if ch == u"\x04" and not WIN: # Unix-like, Ctrl+D579 if ch == "\x04" and not WIN: # Unix-like, Ctrl+D580 raise EOFError()591 if ch == u"\x1a" and WIN: # Windows, Ctrl+Z581 if ch == "\x1a" and WIN: # Windows, Ctrl+Z582 raise EOFError()583584585if WIN:
38 unmodified lines
624 else:625 func = msvcrt.getwch626627 rv = func()638 if rv in (u"\x00", u"\xe0"):628 if rv in ("\x00", "\xe0"):629 # \x00 and \xe0 are control characters that indicate special key,630 # see above.631 rv += func()632 _translate_ch_to_exc(rv)
36 unmodified lines
modified:src/click/_textwrap.py+1 added-1 removed
31 unmodified lines
32 for idx, line in enumerate(text.splitlines()):33 indent = self.initial_indent34 if idx > 0:35 indent = self.subsequent_indent36 rv.append(indent + line)36 rv.append(f"{indent}{line}")37 return "\n".join(rv)
modified:src/click/_unicodefun.py+9 added-58 removed
1import codecs2import os3import sys35from ._compat import PY2478def _find_unicode_literals_frame():9 import __future__1011 if not hasattr(sys, "_getframe"): # not all Python implementations have it12 return 013 frm = sys._getframe(1)14 idx = 115 while frm is not None:16 if frm.f_globals.get("__name__", "").startswith("click."):17 frm = frm.f_back18 idx += 119 elif frm.f_code.co_flags & __future__.unicode_literals.compiler_flag:20 return idx21 else:22 break23 return 0242526def _check_for_unicode_literals():27 if not __debug__:28 return2930 from . import disable_unicode_literals_warning3132 if not PY2 or disable_unicode_literals_warning:33 return34 bad_frame = _find_unicode_literals_frame()35 if bad_frame <= 0:36 return37 from warnings import warn3839 warn(40 Warning(41 "Click detected the use of the unicode_literals __future__"42 " import. This is heavily discouraged because it can"43 " introduce subtle bugs in your code. You should instead"44 ' use explicit u"" literals for your unicode strings. For'45 " more information see"46 " https://click.palletsprojects.com/python3/"47 ),48 stacklevel=bad_frame,49 )505152def _verify_python3_env():53 """Ensures that the environment is good for unicode on Python 3."""5def _verify_python_env():6 """Ensures that the environment is good for Unicode."""54 if PY2:55 return7 try:8 import locale910 fs_enc = codecs.lookup(locale.getpreferredencoding()).name
43 unmodified lines
54 " export LANG=C.UTF-8"55 )56 else:57 extra += (107 "This system lists a couple of UTF-8 supporting locales"108 " that you can pick from. The following suitable"109 " locales were discovered: {}".format(", ".join(sorted(good_locales)))58 "This system lists some UTF-8 supporting locales that"59 " you can pick from. The following suitable locales"60 f" were discovered: {', '.join(sorted(good_locales))}"61 )6263 bad_locale = None64 for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):
5 unmodified lines
70 extra += (71 "\n\nClick discovered that you exported a UTF-8 locale"72 " but the locale system could not pick up from it"73 " because it does not exist. The exported locale is"123 " '{}' but it is not supported".format(bad_locale)74 f" {bad_locale!r} but it is not supported"75 )7677 raise RuntimeError(127 "Click will abort further execution because Python 3 was"78 "Click will abort further execution because Python was"79 " configured to use ASCII as encoding for the environment."129 " Consult https://click.palletsprojects.com/python3/ for"130 " mitigation steps.{}".format(extra)80 " Consult https://click.palletsprojects.com/unicode-support/"81 f" for mitigation steps.{extra}"82 )
modified:src/click/_winconsole.py+16 added-78 removed
1# -*- coding: utf-8 -*-1# This module is based on the excellent work by Adam Bartoš who2# provided a lot of what went into the implementation here in3# the discussion to issue1602 in the Python bug tracker.4#
2 unmodified lines
7# the entire interpreter but just work in our little world of8# echo and prompt.9import ctypes10import io12import os13import sys11import time15import zlib12from ctypes import byref13from ctypes import c_char14from ctypes import c_char_p15from ctypes import c_int
2 unmodified lines
18from ctypes import c_void_p19from ctypes import POINTER20from ctypes import py_object21from ctypes import windll26from ctypes import WinError22from ctypes import WINFUNCTYPE23from ctypes.wintypes import DWORD24from ctypes.wintypes import HANDLE25from ctypes.wintypes import LPCWSTR
1 unmodified line
2728import msvcrt2930from ._compat import _NonClosingTextIOWrapper36from ._compat import PY237from ._compat import text_type3132try:33 from ctypes import pythonapi4142 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer43 PyBuffer_Release = pythonapi.PyBuffer_Release34except ImportError:35 pythonapi = None36else:37 PyObject_GetBuffer = pythonapi.PyObject_GetBuffer38 PyBuffer_Release = pythonapi.PyBuffer_Release394041c_ssize_p = POINTER(c_ssize_t)42
46 unmodified lines
89 ("suboffsets", c_ssize_p),90 ("internal", c_void_p),91 ]92100 if PY2:101 _fields_.insert(-1, ("smalltable", c_ssize_t * 2))9310394# On PyPy we cannot get buffers so our ability to operate here is95# severely limited.96if pythonapi is None:97 get_buffer = None
46 unmodified lines
144 if GetLastError() == ERROR_OPERATION_ABORTED:145 # wait for KeyboardInterrupt146 time.sleep(0.1)147 if not rv:158 raise OSError("Windows error: {}".format(GetLastError()))148 raise OSError(f"Windows error: {GetLastError()}")149150 if buffer[0] == EOF:151 return 0152 return 2 * code_units_read.value
8 unmodified lines
161 if errno == ERROR_SUCCESS:162 return "ERROR_SUCCESS"163 elif errno == ERROR_NOT_ENOUGH_MEMORY:164 return "ERROR_NOT_ENOUGH_MEMORY"175 return "Windows error {}".format(errno)165 return f"Windows error {errno}"166167 def write(self, b):168 bytes_to_be_written = len(b)169 buf = get_buffer(b)
13 unmodified lines
183 raise OSError(self._get_error_message(GetLastError()))184 return bytes_written185186197class ConsoleStream(object):187class ConsoleStream:188 def __init__(self, text_stream, byte_stream):189 self._text_stream = text_stream190 self.buffer = byte_stream191
1 unmodified line
193 def name(self):194 return self.buffer.name195196 def write(self, x):207 if isinstance(x, text_type):197 if isinstance(x, str):198 return self._text_stream.write(x)199 try:200 self.flush()201 except Exception:
10 unmodified lines
212 def isatty(self):213 return self.buffer.isatty()214215 def __repr__(self):226 return "<ConsoleStream name={!r} encoding={!r}>".format(227 self.name, self.encoding228 )216 return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"217218231class WindowsChunkedWriter(object):219class WindowsChunkedWriter:220 """221 Wraps a stream (such as stdout), acting as a transparent proxy for all222 attribute access apart from method 'write()' which we wrap to write in223 limited chunks due to a Windows limitation on binary console streams.
16 unmodified lines
240 self.__wrapped.write(text[written : written + to_write])241 written += to_write242243256_wrapped_std_streams = set()257258259def _wrap_std_stream(name):260 # Python 2 & Windows 7 and below261 if (262 PY2263 and sys.getwindowsversion()[:2] <= (6, 1)264 and name not in _wrapped_std_streams265 ):266 setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))267 _wrapped_std_streams.add(name)268269244def _get_text_stdin(buffer_stream):245 text_stream = _NonClosingTextIOWrapper(246 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),247 "utf-16-le",
22 unmodified lines
270 )271 return ConsoleStream(text_stream, buffer_stream)272273300if PY2:301302 def _hash_py_argv():303 return zlib.crc32("\x00".join(sys.argv[1:]))304305 _initial_argv_hash = _hash_py_argv()306307 def _get_windows_argv():308 argc = c_int(0)309 argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))310 if not argv_unicode:311 raise WinError()312 try:313 argv = [argv_unicode[i] for i in range(0, argc.value)]314 finally:315 LocalFree(argv_unicode)316 del argv_unicode317318 if not hasattr(sys, "frozen"):319 argv = argv[1:]320 while len(argv) > 0:321 arg = argv[0]322 if not arg.startswith("-") or arg == "-":323 break324 argv = argv[1:]325 if arg.startswith(("-c", "-m")):326 break327328 return argv[1:]329330274_stream_factories = {275 0: _get_text_stdin,276 1: _get_text_stdout,277 2: _get_text_stderr,
15 unmodified lines
293294def _get_windows_console_stream(f, encoding, errors):295 if (296 get_buffer is not None354 and encoding in ("utf-16-le", None)355 and errors in ("strict", None)297 and encoding in {"utf-16-le", None}298 and errors in {"strict", None}299 and _is_console(f)300 ):301 func = _stream_factories.get(f.fileno())302 if func is not None:360 if not PY2:361 f = getattr(f, "buffer", None)362 if f is None:363 return None364 else:365 # If we are on Python 2 we need to set the stream that we366 # deal with to binary mode as otherwise the exercise if a367 # bit moot. The same problems apply as for368 # get_binary_stdin and friends from _compat.369 msvcrt.setmode(f.fileno(), os.O_BINARY)303 f = getattr(f, "buffer", None)304305 if f is None:306 return None307308 return func(f)
modified:src/click/core.py+58 added-93 removed
4 unmodified lines
5from contextlib import contextmanager6from functools import update_wrapper7from itertools import repeat89from ._compat import isidentifier10from ._compat import iteritems11from ._compat import PY212from ._compat import string_types13from ._unicodefun import _check_for_unicode_literals14from ._unicodefun import _verify_python3_env9from ._unicodefun import _verify_python_env10from .exceptions import Abort11from .exceptions import BadParameter12from .exceptions import ClickException13from .exceptions import Exit
11 unmodified lines
25from .types import BOOL26from .types import convert_type27from .types import IntRange28from .utils import echo34from .utils import get_os_args29from .utils import make_default_short_help30from .utils import make_str31from .utils import PacifyFlushWrapper32
2 unmodified lines
35SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."36SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."3738DEPRECATED_HELP_NOTICE = " (DEPRECATED)"45DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command %(name)s is deprecated."39DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command {name} is deprecated."404142def _maybe_show_deprecated_notice(cmd):43 if cmd.deprecated:50 echo(style(DEPRECATED_INVOKE_NOTICE % {"name": cmd.name}, fg="red"), err=True)44 echo(style(DEPRECATED_INVOKE_NOTICE.format(name=cmd.name), fg="red"), err=True)454647def fast_exit(code):48 """Exit without garbage collection, this speeds up exit by about 10ms for
6 unmodified lines
5556def _bashcomplete(cmd, prog_name, complete_var=None):57 """Internal handler for the bash completion support."""58 if complete_var is None:65 complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())59 complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()60 complete_instr = os.environ.get(complete_var)61 if not complete_instr:62 return63
16 unmodified lines
80 "Found a multi command as subcommand to a multi command"81 " that is in chain mode. This is not supported."82 )83 raise RuntimeError(90 "{}. Command '{}' is set to chain and '{}' was added as"91 " subcommand but it in itself is a multi command. ('{}' is a {}"92 " within a chained {} named '{}').".format(93 hint,94 base_command.name,95 cmd_name,96 cmd_name,97 cmd.__class__.__name__,98 base_command.__class__.__name__,99 base_command.name,100 )84 f"{hint}. Command {base_command.name!r} is set to chain and"85 f" {cmd_name!r} was added as a subcommand but it in itself is a"86 f" multi command. ({cmd_name!r} is a {type(cmd).__name__}"87 f" within a chained {type(base_command).__name__} named"88 f" {base_command.name!r})."89 )909192def batch(iterable, batch_size):93 return list(zip(*repeat(iter(iterable), batch_size)))9495108def invoke_param_callback(callback, ctx, param, value):109 code = getattr(callback, "__code__", None)110 args = getattr(code, "co_argcount", 3)111112 if args < 3:113 from warnings import warn114115 warn(116 "Parameter callbacks take 3 args, (ctx, param, value). The"117 " 2-arg style is deprecated and will be removed in 8.0.".format(callback),118 DeprecationWarning,119 stacklevel=3,120 )121 return callback(ctx, value)122123 return callback(ctx, param, value)12412596@contextmanager97def augment_usage_errors(ctx, param=None):98 """Context manager that attaches extra information to exceptions."""99 try:
25 unmodified lines
125126 return sorted(declaration_order, key=sort_key)127128159class ParameterSource(object):129class ParameterSource:130 """This is an enum that indicates the source of a command line parameter.131132 The enum has one of the following values: COMMANDLINE,133 ENVIRONMENT, DEFAULT, DEFAULT_MAP. The DEFAULT indicates that the
18 unmodified lines
152 :param value: the string value to verify153 """154 if value not in cls.VALUES:155 raise ValueError(186 "Invalid ParameterSource value: '{}'. Valid "187 "values are: {}".format(value, ",".join(cls.VALUES))156 f"Invalid ParameterSource value: {value!r}. Valid"157 f" values are: {','.join(cls.VALUES)}"158 )159160191class Context(object):161class Context:162 """The context is a special internal object that holds state relevant163 for the script execution at every single level. It's normally invisible164 to commands unless they opt-in to getting access to it.165
208 unmodified lines
374 parent is not None375 and parent.auto_envvar_prefix is not None376 and self.info_name is not None377 ):408 auto_envvar_prefix = "{}_{}".format(409 parent.auto_envvar_prefix, self.info_name.upper()378 auto_envvar_prefix = (379 f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"380 )381 else:382 auto_envvar_prefix = auto_envvar_prefix.upper()383 if auto_envvar_prefix is not None:
122 unmodified lines
506 rv = ""507 if self.info_name is not None:508 rv = self.info_name509 if self.parent is not None:540 rv = "{} {}".format(self.parent.command_path, rv)510 rv = f"{self.parent.command_path} {rv}"511 return rv.lstrip()512513 def find_root(self):514 """Finds the outermost context."""
144 unmodified lines
659 """660 return self._source_by_paramname[name]661662693class BaseCommand(object):663class BaseCommand:664 """The base command implements the minimal API contract of commands.665 Most code will never use this as it does not implement a lot of useful666 functionality but it can act as the direct subclass of alternative667 parsing methods that do not depend on the Click parser.
32 unmodified lines
700 #: an optional dictionary with defaults passed to the context.701 self.context_settings = context_settings702703 def __repr__(self):734 return "<{} {}>".format(self.__class__.__name__, self.name)704 return f"<{self.__class__.__name__} {self.name}>"705706 def get_usage(self, ctx):707 raise NotImplementedError("Base commands cannot get usage")708
14 unmodified lines
723 :param parent: the parent context if available.724 :param extra: extra keyword arguments forwarded to the context725 constructor.726 """757 for key, value in iteritems(self.context_settings):727 for key, value in self.context_settings.items():728 if key not in extra:729 extra[key] = value730 ctx = Context(self, info_name=info_name, parent=parent, **extra)731 with ctx.scope(cleanup=False):
18 unmodified lines
750 args=None,751 prog_name=None,752 complete_var=None,753 standalone_mode=True,784 **extra754 **extra,755 ):756 """This is the way to invoke a script with all the bells and757 whistles as a command line application. This will always terminate758 the application after a call. If this is not wanted, ``SystemExit``
25 unmodified lines
784 of :meth:`invoke`.785 :param extra: extra keyword arguments are forwarded to the context786 constructor. See :class:`Context` for more information.787 """818 # If we are in Python 3, we will verify that the environment is819 # sane at this point or reject further execution to avoid a820 # broken script.821 if not PY2:822 _verify_python3_env()823 else:824 _check_for_unicode_literals()788 # Verify that the environment is configured correctly, or reject789 # further execution to avoid a broken script.790 _verify_python_env()791792 if args is None:827 args = get_os_args()793 args = sys.argv[1:]794 else:795 args = list(args)796797 if prog_name is None:
27 unmodified lines
825 if not standalone_mode:826 raise827 e.show()828 sys.exit(e.exit_code)863 except IOError as e:829 except OSError as e:830 if e.errno == errno.EPIPE:831 sys.stdout = PacifyFlushWrapper(sys.stdout)832 sys.stderr = PacifyFlushWrapper(sys.stderr)833 sys.exit(1)
94 unmodified lines
928 self.hidden = hidden929 self.deprecated = deprecated930931 def __repr__(self):966 return "<{} {}>".format(self.__class__.__name__, self.name)932 return f"<{self.__class__.__name__} {self.name}>"933934 def get_usage(self, ctx):935 """Formats the usage line into a string and returns it.936
144 unmodified lines
1081 value, args = param.handle_parse_result(ctx, opts, args)10821083 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1084 ctx.fail(1119 "Got unexpected extra argument{} ({})".format(1120 "s" if len(args) != 1 else "", " ".join(map(make_str, args))1121 )1085 "Got unexpected extra"1086 f" argument{'s' if len(args) != 1 else ''}"1087 f" ({' '.join(map(make_str, args))})"1088 )10891090 ctx.args = args1091 return args
41 unmodified lines
1133 no_args_is_help=None,1134 subcommand_metavar=None,1135 chain=False,1136 result_callback=None,1171 **attrs1137 **attrs,1138 ):1139 Command.__init__(self, name, **attrs)1140 if no_args_is_help is None:1141 no_args_is_help = not invoke_without_command
201 unmodified lines
1343 # place.1344 if cmd is None and not ctx.resilient_parsing:1345 if split_opt(cmd_name)[0]:1346 self.parse_args(ctx, ctx.args)1381 ctx.fail("No such command '{}'.".format(original_cmd_name))1347 ctx.fail(f"No such command '{original_cmd_name}'.")13481349 return cmd_name, cmd, args[1:]13501351 def get_command(self, ctx, cmd_name):
98 unmodified lines
1450 rv.update(source.list_commands(ctx))1451 return sorted(rv)145214531488class Parameter(object):1454class Parameter:1455 r"""A parameter to a command comes in two versions: they are either1456 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently1457 not supported by design as some of the internals for parsing are1458 intentionally not finalized.
79 unmodified lines
1538 self.envvar = envvar1539 self.autocompletion = autocompletion15401541 def __repr__(self):1576 return "<{} {}>".format(self.__class__.__name__, self.name)1542 return f"<{self.__class__.__name__} {self.name}>"15431544 @property1545 def human_readable_name(self):1546 """Returns the human readable name of this parameter. This is the
44 unmodified lines
1591 if self.type.is_composite:1592 if self.nargs <= 1:1593 raise TypeError(1594 "Attempted to invoke composite type but nargs has"1629 " been set to {}. This is not supported; nargs"1630 " needs to be set to a fixed value > 1.".format(self.nargs)1595 f" been set to {self.nargs}. This is not supported;"1596 " nargs needs to be set to a fixed value > 1."1597 )1598 if self.multiple:1599 return tuple(self.type(x or (), self, ctx) for x in value or ())1600 return self.type(value or (), self, ctx)
66 unmodified lines
1667 raise1668 value = None1669 if self.callback is not None:1670 try:1705 value = invoke_param_callback(self.callback, ctx, self, value)1671 value = self.callback(ctx, self, value)1672 except Exception:1673 if not ctx.resilient_parsing:1674 raise1675
72 unmodified lines
1748 help=None,1749 hidden=False,1750 show_choices=True,1751 show_envvar=False,1786 **attrs1752 **attrs,1753 ):1754 default_is_missing = attrs.get("default", _missing) is _missing1755 Parameter.__init__(self, param_decls, type=type, **attrs)1756
67 unmodified lines
1824 name = None1825 possible_names = []18261827 for decl in decls:1862 if isidentifier(decl):1828 if decl.isidentifier():1829 if name is not None:1830 raise TypeError("Name defined twice")1831 name = decl1832 else:
13 unmodified lines
18461847 if name is None and possible_names:1848 possible_names.sort(key=lambda x: -len(x[0])) # group long options first1849 name = possible_names[0][1].replace("-", "_").lower()1884 if not isidentifier(name):1850 if not name.isidentifier():1851 name = None18521853 if name is None:1854 if not expose_value:
1 unmodified line
1856 raise TypeError("Could not determine name for option")18571858 if not opts and not secondary_opts:1859 raise TypeError(1894 "No options defined but a name was passed ({}). Did you"1895 " mean to declare an argument instead of an option?".format(name)1860 f"No options defined but a name was passed ({name})."1861 " Did you mean to declare an argument instead of an"1862 " option?"1863 )18641865 return name, opts, secondary_opts1866
12 unmodified lines
1879 action = "store"18801881 if self.is_flag:1882 kwargs.pop("nargs", None)1916 action_const = "{}_const".format(action)1883 action_const = f"{action}_const"1884 if self.is_bool_flag and self.secondary_opts:1885 parser.add_option(self.opts, action=action_const, const=True, **kwargs)1886 parser.add_option(1887 self.secondary_opts, action=action_const, const=False, **kwargs
15 unmodified lines
1903 rv, any_slashes = join_options(opts)1904 if any_slashes:1905 any_prefix_is_slash[:] = [True]1906 if not self.is_flag and not self.count:1940 rv += " {}".format(self.make_metavar())1907 rv += f" {self.make_metavar()}"1908 return rv19091910 rv = [_write_opts(self.opts)]1911 if self.secondary_opts:
4 unmodified lines
1916 if self.show_envvar:1917 envvar = self.envvar1918 if envvar is None:1919 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1953 envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())1920 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"1921 if envvar is not None:1955 extra.append(1956 "env var: {}".format(1957 ", ".join(str(d) for d in envvar)1958 if isinstance(envvar, (list, tuple))1959 else envvar1922 var_str = (1923 ", ".join(str(d) for d in envvar)1924 if isinstance(envvar, (list, tuple))1925 else envvar1960 )1926 )1927 extra.append(f"env var: {var_str}")1928 if self.default is not None and (self.show_default or ctx.show_default):1963 if isinstance(self.show_default, string_types):1964 default_string = "({})".format(self.show_default)1929 if isinstance(self.show_default, str):1930 default_string = f"({self.show_default})"1931 elif isinstance(self.default, (list, tuple)):1932 default_string = ", ".join(str(d) for d in self.default)1933 elif inspect.isfunction(self.default):1934 default_string = "(dynamic)"1935 else:1936 default_string = self.default1971 extra.append("default: {}".format(default_string))1937 extra.append(f"default: {default_string}")19381939 if self.required:1940 extra.append("required")1941 if extra:1976 help = "{}[{}]".format(1977 "{} ".format(help) if help else "", "; ".join(extra)1978 )1942 extra_str = ";".join(extra)1943 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"19441945 return ("; " if any_prefix_is_slash else " / ").join(rv), help19461947 def get_default(self, ctx):
36 unmodified lines
1984 rv = Parameter.resolve_envvar_value(self, ctx)1985 if rv is not None:1986 return rv1987 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:2023 envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())1988 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"1989 return os.environ.get(envvar)19901991 def value_from_envvar(self, ctx):1992 rv = self.resolve_envvar_value(ctx)
46 unmodified lines
2039 var = self.type.get_metavar(self)2040 if not var:2041 var = self.name.upper()2042 if not self.required:2078 var = "[{}]".format(var)2043 var = f"[{var}]"2044 if self.nargs != 1:2045 var += "..."2046 return var2047
7 unmodified lines
2055 name = name.replace("-", "_").lower()2056 else:2057 raise TypeError(2058 "Arguments take exactly one parameter declaration, got"2094 " {}".format(len(decls))2059 f" {len(decls)}."2060 )2061 return name, [arg], []20622063 def get_usage_pieces(self, ctx):
7 unmodified lines
modified:src/click/decorators.py+4 added-6 removed
1import inspect2import sys3from functools import update_wrapper45from ._compat import iteritems6from ._unicodefun import _check_for_unicode_literals5from .core import Argument6from .core import Command7from .core import Group8from .core import Option
56 unmodified lines
65 obj = ctx.find_object(object_type)66 if obj is None:67 raise RuntimeError(68 "Managed to invoke callback without a context"71 " object of type '{}' existing".format(object_type.__name__)69 f" object of type {object_type.__name__!r}"70 " existing."71 )72 return ctx.invoke(f, obj, *args, **kwargs)7374 return update_wrapper(new_func, f)
17 unmodified lines
92 help = help.decode("utf-8")93 else:94 help = inspect.cleandoc(help)95 attrs["help"] = help97 _check_for_unicode_literals()96 return cls(97 name=name or f.__name__.lower().replace("_", "-"),98 callback=f,99 params=params,102 **attrs100 **attrs,101 )102103104def command(name=None, cls=None, **attrs):
179 unmodified lines
284 pass285 else:286 for dist in pkg_resources.working_set:287 scripts = dist.get_entry_map().get("console_scripts") or {}290 for _, entry_point in iteritems(scripts):288 for entry_point in scripts.values():289 if entry_point.module_name == module:290 ver = dist.version291 break292 if ver is None:
39 unmodified lines
modified:src/click/exceptions.py+18 added-38 removed
1from ._compat import filename_to_ui2from ._compat import get_text_stderr3from ._compat import PY23from .utils import echo456def _join_param_hints(param_hint):
4 unmodified lines
1112class ClickException(Exception):13 """An exception that Click can handle and show to the user."""1416 #: The exit code for this exception15 #: The exit code for this exception.16 exit_code = 11718 def __init__(self, message):20 ctor_msg = message21 if PY2:22 if ctor_msg is not None:23 ctor_msg = ctor_msg.encode("utf-8")24 Exception.__init__(self, ctor_msg)19 super().__init__(message)20 self.message = message2122 def format_message(self):23 return self.message2425 def __str__(self):26 return self.message2733 if PY2:34 __unicode__ = __str__3536 def __str__(self):37 return self.message.encode("utf-8")3828 def show(self, file=None):29 if file is None:30 file = get_text_stderr()42 echo("Error: {}".format(self.format_message()), file=file)31 echo(f"Error: {self.format_message()}", file=file)323334class UsageError(ClickException):35 """An internal exception that signals a usage error. This typically
16 unmodified lines
52 file = get_text_stderr()53 color = None54 hint = ""55 if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:67 hint = "Try '{} {}' for help.\n".format(68 self.ctx.command_path, self.ctx.help_option_names[0]56 hint = (57 f"Try '{self.ctx.command_path}"58 f" {self.ctx.help_option_names[0]}' for help.\n"59 )60 if self.ctx is not None:61 color = self.ctx.color72 echo("{}\n{}".format(self.ctx.get_usage(), hint), file=file, color=color)73 echo("Error: {}".format(self.format_message()), file=file, color=color)62 echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)63 echo(f"Error: {self.format_message()}", file=file, color=color)646566class BadParameter(UsageError):67 """An exception that formats out a standardized error message for a
23 unmodified lines
91 param_hint = self.param_hint92 elif self.param is not None:93 param_hint = self.param.get_error_hint(self.ctx)94 else:105 return "Invalid value: {}".format(self.message)95 return f"Invalid value: {self.message}"96 param_hint = _join_param_hints(param_hint)97108 return "Invalid value for {}: {}".format(param_hint, self.message)98 return f"Invalid value for {param_hint}: {self.message}"99100101class MissingParameter(BadParameter):102 """Raised if click required an option or argument but it was not
30 unmodified lines
133 if self.param is not None:134 msg_extra = self.param.type.get_missing_message(self.param)135 if msg_extra:136 if msg:147 msg += ". {}".format(msg_extra)137 msg += f". {msg_extra}"138 else:139 msg = msg_extra140151 return "Missing {}{}{}{}".format(152 param_type,153 " {}".format(param_hint) if param_hint else "",154 ". " if msg else ".",155 msg or "",156 )141 hint_str = f" {param_hint}" if param_hint else ""142 return f"Missing {param_type}{hint_str}.{' ' if msg else ''}{msg or ''}"143144 def __str__(self):145 if self.message is None:146 param_name = self.param.name if self.param else None161 return "missing parameter: {}".format(param_name)147 return f"missing parameter: {param_name}"148 else:149 return self.message150165 if PY2:166 __unicode__ = __str__151168 def __str__(self):169 return self.__unicode__().encode("utf-8")170171152class NoSuchOption(UsageError):153 """Raised if click attempted to handle an option that does not154 exist.155
1 unmodified line
157 """158159 def __init__(self, option_name, message=None, possibilities=None, ctx=None):160 if message is None:181 message = "no such option: {}".format(option_name)161 message = f"no such option: {option_name}"162 UsageError.__init__(self, message, ctx)163 self.option_name = option_name164 self.possibilities = possibilities165166 def format_message(self):167 bits = [self.message]168 if self.possibilities:169 if len(self.possibilities) == 1:190 bits.append("Did you mean {}?".format(self.possibilities[0]))170 bits.append(f"Did you mean {self.possibilities[0]}?")171 else:172 possibilities = sorted(self.possibilities)193 bits.append("(Possible options: {})".format(", ".join(possibilities)))173 bits.append(f"(Possible options: {', '.join(possibilities)})")174 return " ".join(bits)175176177class BadOptionUsage(UsageError):
34 unmodified lines
212 self.ui_filename = ui_filename213 self.filename = filename214215 def format_message(self):236 return "Could not open file {}: {}".format(self.ui_filename, self.message)216 return f"Could not open file {self.ui_filename}: {self.message}"217218219class Abort(RuntimeError):220 """An internal signalling exception that signals Click to abort."""
13 unmodified lines
modified:src/click/formatting.py+6 added-10 removed
89 unmodified lines
9091 return "\n\n".join(rv)929394class HelpFormatter(object):94class HelpFormatter:95 """This class helps with formatting text-based help pages. It's96 usually just needed for very special internal cases, but it's also97 exposed so that developers can write their own fancy outputs.98
34 unmodified lines
133 :param prog: the program name.134 :param args: whitespace separated list of arguments.135 :param prefix: the prefix for the first line.136 """137 usage_prefix = "{:>{w}}{} ".format(prefix, prog, w=self.current_indent)137 usage_prefix = f"{prefix:>{self.current_indent}}{prog} "138 text_width = self.width - self.current_indent139140 if text_width >= (term_len(usage_prefix) + 20):141 # The arguments will fit to the right of the prefix.
20 unmodified lines
162 self.write("\n")163164 def write_heading(self, heading):165 """Writes a heading into the buffer."""166 self.write("{:>{w}}{}:\n".format("", heading, w=self.current_indent))166 self.write(f"{'':>{self.current_indent}}{heading}:\n")167168 def write_paragraph(self):169 """Writes a paragraph into the buffer."""170 if self.buffer:
32 unmodified lines
203204 first_col = min(widths[0], col_max) + col_spacing205206 for first, second in iter_rows(rows, len(widths)):207 self.write("{:>{w}}{}".format("", first, w=self.current_indent))207 self.write(f"{'':>{self.current_indent}}{first}")208 if not second:209 self.write("\n")210 continue211 if term_len(first) <= first_col - col_spacing:
6 unmodified lines
218 wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)219 lines = wrapped_text.splitlines()220221 if lines:222 self.write("{}\n".format(lines[0]))222 self.write(f"{lines[0]}\n")223224 for line in lines[1:]:225 self.write(226 "{:>{w}}{}\n".format(227 "", line, w=first_col + self.current_indent228 )229 )225 self.write(f"{'':>{first_col + self.current_indent}}{line}\n")226227 if len(lines) > 1:228 # separate long help from next option229 self.write("\n")
50 unmodified lines
modified:src/click/parser.py+13 added-14 removed
1# -*- coding: utf-8 -*-1"""2This module started out as largely a copy paste from the stdlib's3optparse module with the features removed that we do not need from4optparse because we implement them in Click on a higher level (for
77 unmodified lines
828384def _error_opt_args(nargs, opt):85 if nargs == 1:87 raise BadOptionUsage(opt, "{} option requires an argument".format(opt))88 raise BadOptionUsage(opt, "{} option requires {} arguments".format(opt, nargs))86 raise BadOptionUsage(opt, f"{opt} option requires an argument")87 raise BadOptionUsage(opt, f"{opt} option requires {nargs} arguments")888990def split_opt(opt):91 first = opt[:1]
7 unmodified lines
99def normalize_opt(opt, ctx):100 if ctx is None or ctx.token_normalize_func is None:101 return opt102 prefix, opt = split_opt(opt)104 return prefix + ctx.token_normalize_func(opt)103 return f"{prefix}{ctx.token_normalize_func(opt)}"104105106def split_arg_string(string):107 """Given an argument string this attempts to split it into small parts."""
13 unmodified lines
121 rv.append(arg)122 return rv123124126class Option(object):125class Option:126 def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):127 self._short_opts = []128 self._long_opts = []129 self.prefixes = set()130131 for opt in opts:132 prefix, value = split_opt(opt)133 if not prefix:135 raise ValueError("Invalid start character for option ({})".format(opt))134 raise ValueError(f"Invalid start character for option ({opt})")135 self.prefixes.add(prefix[0])136 if len(prefix) == 1 and len(value) == 1:137 self._short_opts.append(opt)138 else:
24 unmodified lines
163 state.opts.setdefault(self.dest, []).append(self.const)164 elif self.action == "count":165 state.opts[self.dest] = state.opts.get(self.dest, 0) + 1166 else:168 raise ValueError("unknown action '{}'".format(self.action))167 raise ValueError(f"unknown action '{self.action}'")168 state.order.append(self.obj)169170172class Argument(object):171class Argument:172 def __init__(self, dest, nargs=1, obj=None):173 self.dest = dest174 self.nargs = nargs175 self.obj = obj
4 unmodified lines
180 if holes == len(value):181 value = None182 elif holes != 0:183 raise BadArgumentUsage(185 "argument {} takes {} values".format(self.dest, self.nargs)184 f"argument {self.dest} takes {self.nargs} values"185 )186 state.opts[self.dest] = value187 state.order.append(self.obj)188189191class ParsingState(object):190class ParsingState:191 def __init__(self, rargs):192 self.opts = {}193 self.largs = []194 self.rargs = rargs195 self.order = []196197199class OptionParser(object):198class OptionParser:199 """The option parser is an internal class that is ultimately used to200 parse options and arguments. It's modelled after optparse and brings201 a similar but vastly simplified API. It should generally not be used202 directly as the high level Click classes wrap it for you.
143 unmodified lines
346 value = tuple(state.rargs[:nargs])347 del state.rargs[:nargs]348349 elif explicit_value is not None:351 raise BadOptionUsage(opt, "{} option does not take a value".format(opt))350 raise BadOptionUsage(opt, f"{opt} option does not take a value")351352 else:353 value = None354
5 unmodified lines
360 prefix = arg[0]361 unknown_options = []362363 for ch in arg[1:]:365 opt = normalize_opt(prefix + ch, self.ctx)364 opt = normalize_opt(f"{prefix}{ch}", self.ctx)365 option = self._short_opt.get(opt)366 i += 1367368 if not option:
29 unmodified lines
398 # remaining options and re-attach the prefix, then report that399 # to the state as new larg. This way there is basic combinatorics400 # that can be achieved while still ignoring unknown arguments.401 if self.ignore_unknown_options and unknown_options:403 state.largs.append("{}{}".format(prefix, "".join(unknown_options)))402 state.largs.append(f"{prefix}{''.join(unknown_options)}")403404 def _process_opts(self, arg, state):405 explicit_value = None406 # Long option handling happens in two parts. The first part is
25 unmodified lines
modified:src/click/termui.py+19 added-26 removed
6 unmodified lines
78from ._compat import DEFAULT_COLUMNS9from ._compat import get_winterm_size10from ._compat import isatty11from ._compat import raw_input12from ._compat import string_types11from ._compat import strip_ansi14from ._compat import text_type12from ._compat import WIN13from .exceptions import Abort14from .exceptions import UsageError15from .globals import resolve_color_default
4 unmodified lines
20from .utils import LazyFile2122# The prompt functions to use. The doc tools currently override these23# functions to customize how they work.27visible_prompt_func = raw_input24visible_prompt_func = input2526_ansi_colors = {27 "black": 30,28 "red": 31,
26 unmodified lines
55 text, suffix, show_default=False, default=None, show_choices=True, type=None56):57 prompt = text58 if type is not None and show_choices and isinstance(type, Choice):62 prompt += " ({})".format(", ".join(map(str, type.choices)))59 prompt += f" ({', '.join(map(str, type.choices))})"60 if default is not None and show_default:64 prompt = "{} [{}]".format(prompt, _format_default(default))65 return prompt + suffix61 prompt = f"{prompt} [{_format_default(default)}]"62 return f"{prompt}{suffix}"636465def _format_default(default):66 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):
85 unmodified lines
152 return default153 try:154 result = value_proc(value)155 except UsageError as e:159 echo("Error: {}".format(e.message), err=err) # noqa: B306156 echo(f"Error: {e.message}", err=err) # noqa: B306157 continue158 if not confirmation_prompt:159 return result160 while 1:
54 unmodified lines
215def get_terminal_size():216 """Returns the current size of the terminal as tuple in the form217 ``(width, height)`` in columns and rows.218 """222 # If shutil has get_terminal_size() (Python 3.3 and later) use that223 if sys.version_info >= (3, 3):224 import shutil219 import shutil220226 shutil_get_terminal_size = getattr(shutil, "get_terminal_size", None)227 if shutil_get_terminal_size:228 sz = shutil_get_terminal_size()229 return sz.columns, sz.lines221 if hasattr(shutil, "get_terminal_size"):222 return shutil.get_terminal_size()223224 # We provide a sensible default for get_winterm_size() when being invoked225 # inside a subprocess. Without this, it would not provide a useful input.226 if get_winterm_size is not None:
43 unmodified lines
270 color = resolve_color_default(color)271272 if inspect.isgeneratorfunction(text_or_generator):273 i = text_or_generator()281 elif isinstance(text_or_generator, string_types):274 elif isinstance(text_or_generator, str):275 i = [text_or_generator]276 else:277 i = iter(text_or_generator)278279 # convert every element of i to a text type if necessary287 text_generator = (el if isinstance(el, string_types) else text_type(el) for el in i)280 text_generator = (el if isinstance(el, str) else str(el) for el in i)281282 from ._termui_impl import pager283284 return pager(itertools.chain(text_generator, "\n"), color)
216 unmodified lines
501 """502 bits = []503 if fg:504 try:512 bits.append("\033[{}m".format(_ansi_colors[fg]))505 bits.append(f"\033[{_ansi_colors[fg]}m")506 except KeyError:514 raise TypeError("Unknown color '{}'".format(fg))507 raise TypeError(f"Unknown color {fg!r}")508 if bg:509 try:517 bits.append("\033[{}m".format(_ansi_colors[bg] + 10))510 bits.append(f"\033[{_ansi_colors[bg] + 10}m")511 except KeyError:519 raise TypeError("Unknown color '{}'".format(bg))512 raise TypeError(f"Unknown color {bg!r}")513 if bold is not None:521 bits.append("\033[{}m".format(1 if bold else 22))514 bits.append(f"\033[{1 if bold else 22}m")515 if dim is not None:523 bits.append("\033[{}m".format(2 if dim else 22))516 bits.append(f"\033[{2 if dim else 22}m")517 if underline is not None:525 bits.append("\033[{}m".format(4 if underline else 24))518 bits.append(f"\033[{4 if underline else 24}m")519 if blink is not None:527 bits.append("\033[{}m".format(5 if blink else 25))520 bits.append(f"\033[{5 if blink else 25}m")521 if reverse is not None:529 bits.append("\033[{}m".format(7 if reverse else 27))522 bits.append(f"\033[{7 if reverse else 27}m")523 bits.append(text)524 if reset:525 bits.append(_ansi_reset_all)526 return "".join(bits)
162 unmodified lines
modified:src/click/testing.py+30 added-50 removed
1import contextlib2import io3import os4import shlex5import shutil6import sys
1 unmodified line
89from . import formatting10from . import termui11from . import utils11from ._compat import iteritems12from ._compat import PY213from ._compat import string_types12from ._compat import _find_binary_reader131416if PY2:17 from cStringIO import StringIO18else:19 import io20 from ._compat import _find_binary_reader212223class EchoingStdin(object):15class EchoingStdin:16 def __init__(self, input, output):17 self._input = input18 self._output = output19
22 unmodified lines
4243def make_input_stream(input, charset):44 # Is already an input stream.45 if hasattr(input, "read"):54 if PY2:55 return input46 rv = _find_binary_reader(input)4748 if rv is not None:49 return rv5051 raise TypeError("Could not find binary reader for input stream.")5253 if input is None:54 input = b""55 elif not isinstance(input, bytes):56 input = input.encode(charset)65 if PY2:66 return StringIO(input)5758 return io.BytesIO(input)596070class Result(object):61class Result:62 """Holds the captured result of an invoked CLI script."""6364 def __init__(65 self, runner, stdout_bytes, stderr_bytes, exit_code, exception, exc_info=None
32 unmodified lines
98 "\r\n", "\n"99 )100101 def __repr__(self):111 return "<{} {}>".format(112 type(self).__name__, repr(self.exception) if self.exception else "okay"113 )102 exc_str = repr(self.exception) if self.exception else "okay"103 return f"<{type(self).__name__} {exc_str}>"104105116class CliRunner(object):106class CliRunner:107 """The CLI runner provides functionality to invoke a Click command line108 script for unittesting purposes in a isolated environment. This only109 works in single-threaded systems without any concurrency as it changes the110 global interpreter state.111122 :param charset: the character set for the input and output data. This is123 UTF-8 by default and should not be changed currently as124 the reporting to Click only works in Python 2 properly.112 :param charset: the character set for the input and output data.113 :param env: a dictionary with environment variables for overriding.114 :param echo_stdin: if this is set to `True`, then reading from stdin writes115 to stdout. This is useful for showing examples in116 some circumstances. Note that regular prompts
4 unmodified lines
121 noisy stderr, such that each may be measured122 independently123 """124137 def __init__(self, charset=None, env=None, echo_stdin=False, mix_stderr=True):138 if charset is None:139 charset = "utf-8"125 def __init__(self, charset="utf-8", env=None, echo_stdin=False, mix_stderr=True):126 self.charset = charset127 self.env = env or {}128 self.echo_stdin = echo_stdin129 self.mix_stderr = mix_stderr
39 unmodified lines
169 formatting.FORCED_WIDTH = 80170171 env = self.make_env(env)172187 if PY2:188 bytes_output = StringIO()189 if self.echo_stdin:190 input = EchoingStdin(input, bytes_output)191 sys.stdout = bytes_output192 if not self.mix_stderr:193 bytes_error = StringIO()194 sys.stderr = bytes_error195 else:196 bytes_output = io.BytesIO()173 bytes_output = io.BytesIO()197 if self.echo_stdin:198 input = EchoingStdin(input, bytes_output)199 input = io.TextIOWrapper(input, encoding=self.charset)200 sys.stdout = io.TextIOWrapper(bytes_output, encoding=self.charset)201 if not self.mix_stderr:202 bytes_error = io.BytesIO()203 sys.stderr = io.TextIOWrapper(bytes_error, encoding=self.charset)174175 if self.echo_stdin:176 input = EchoingStdin(input, bytes_output)177178 input = io.TextIOWrapper(input, encoding=self.charset)179 sys.stdout = io.TextIOWrapper(bytes_output, encoding=self.charset)180181 if not self.mix_stderr:182 bytes_error = io.BytesIO()183 sys.stderr = io.TextIOWrapper(bytes_error, encoding=self.charset)184185 if self.mix_stderr:186 sys.stderr = sys.stdout187188 sys.stdin = input189190 def visible_input(prompt=None):191 sys.stdout.write(prompt or "")192 val = input.readline().rstrip("\r\n")213 sys.stdout.write("{}\n".format(val))193 sys.stdout.write(f"{val}\n")194 sys.stdout.flush()195 return val196197 def hidden_input(prompt=None):218 sys.stdout.write("{}\n".format(prompt or ""))198 sys.stdout.write(f"{prompt or ''}\n")199 sys.stdout.flush()200 return input.readline().rstrip("\r\n")201202 def _getchar(echo):
20 unmodified lines
223 utils.should_strip_ansi = should_strip_ansi224225 old_env = {}226 try:247 for key, value in iteritems(env):227 for key, value in env.items():228 old_env[key] = os.environ.get(key)229 if value is None:230 try:231 del os.environ[key]
2 unmodified lines
234 else:235 os.environ[key] = value236 yield (bytes_output, not self.mix_stderr and bytes_error)237 finally:258 for key, value in iteritems(old_env):238 for key, value in old_env.items():239 if value is None:240 try:241 del os.environ[key]242 except Exception:
16 unmodified lines
259 input=None,260 env=None,261 catch_exceptions=True,262 color=False,283 **extra263 **extra,264 ):265 """Invokes a command in an isolated environment. The arguments are266 forwarded directly to the command line script, the `extra` keyword267 arguments are passed to the :meth:`~clickpkg.Command.main` function of
28 unmodified lines
296 with self.isolation(input=input, env=env, color=color) as outstreams:297 exception = None298 exit_code = 0299320 if isinstance(args, string_types):300 if isinstance(args, str):301 args = shlex.split(args)302303 try:304 prog_name = extra.pop("prog_name")
52 unmodified lines
357 finally:358 os.chdir(cwd)359 try:360 shutil.rmtree(t)381 except (OSError, IOError): # noqa: B014361 except OSError: # noqa: B014362 pass
modified:src/click/types.py+41 added-77 removed
3 unmodified lines
45from ._compat import _get_argv_encoding6from ._compat import filename_to_ui7from ._compat import get_filesystem_encoding8from ._compat import get_streerror8from ._compat import get_strerror9from ._compat import open_stream10from ._compat import PY211from ._compat import text_type10from .exceptions import BadParameter11from .utils import LazyFile12from .utils import safecall131417class ParamType(object):15class ParamType:16 """Helper for converting values through types. The following is17 necessary for a valid type:1819 * it needs a name
71 unmodified lines
91 try:92 return self.func(value)93 except ValueError:94 try:97 value = text_type(value)95 value = str(value)96 except UnicodeError:99 value = str(value).decode("utf-8", "replace")97 value = value.decode("utf-8", "replace")9899 self.fail(value, param, ctx)100101102class UnprocessedParamType(ParamType):
53 unmodified lines
156 self.choices = choices157 self.case_sensitive = case_sensitive158159 def get_metavar(self, param):161 return "[{}]".format("|".join(self.choices))160 return f"[{'|'.join(self.choices)}]"161162 def get_missing_message(self, param):164 return "Choose from:\n\t{}.".format(",\n\t".join(self.choices))163 choice_str = ",\n\t".join(self.choices)164 return f"Choose from:\n\t{choice_str}"165166 def convert(self, value, param, ctx):167 # Match through normalization and case sensitivity168 # first do token_normalize_func, then lowercase
9 unmodified lines
178 for normed_choice, original in normed_choices.items()179 }180181 if not self.case_sensitive:182 if PY2:183 lower = str.lower184 else:185 lower = str.casefold186187 normed_value = lower(normed_value)182 normed_value = normed_value.casefold()183 normed_choices = {189 lower(normed_choice): original184 normed_choice.casefold(): original185 for normed_choice, original in normed_choices.items()186 }187188 if normed_value in normed_choices:189 return normed_choices[normed_value]190191 self.fail(197 "invalid choice: {}. (choose from {})".format(198 value, ", ".join(self.choices)199 ),192 f"invalid choice: {value}. (choose from {', '.join(self.choices)})",193 param,194 ctx,195 )196197 def __repr__(self):205 return "Choice('{}')".format(list(self.choices))198 return f"Choice({list(self.choices)})"199200201class DateTime(ParamType):202 """The DateTime type converts date strings into `datetime` objects.
21 unmodified lines
224 def __init__(self, formats=None):225 self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]226227 def get_metavar(self, param):235 return "[{}]".format("|".join(self.formats))228 return f"[{'|'.join(self.formats)}]"229230 def _try_to_convert_date(self, value, format):231 try:232 return datetime.strptime(value, format)
7 unmodified lines
240 if dtime:241 return dtime242243 self.fail(251 "invalid datetime format: {}. (choose from {})".format(252 value, ", ".join(self.formats)253 )244 f"invalid datetime format: {value}. (choose from {', '.join(self.formats)})"245 )246247 def __repr__(self):248 return "DateTime"
5 unmodified lines
254 def convert(self, value, param, ctx):255 try:256 return int(value)257 except ValueError:267 self.fail("{} is not a valid integer".format(value), param, ctx)258 self.fail(f"{value} is not a valid integer", param, ctx)259260 def __repr__(self):261 return "INT"262
28 unmodified lines
291 and rv > self.max292 ):293 if self.min is None:294 self.fail(304 "{} is bigger than the maximum valid value {}.".format(305 rv, self.max306 ),295 f"{rv} is bigger than the maximum valid value {self.max}.",296 param,297 ctx,298 )299 elif self.max is None:300 self.fail(312 "{} is smaller than the minimum valid value {}.".format(313 rv, self.min314 ),301 f"{rv} is smaller than the minimum valid value {self.min}.",302 param,303 ctx,304 )305 else:306 self.fail(320 "{} is not in the valid range of {} to {}.".format(321 rv, self.min, self.max322 ),307 f"{rv} is not in the valid range of {self.min} to {self.max}.",308 param,309 ctx,310 )311 return rv312313 def __repr__(self):329 return "IntRange({}, {})".format(self.min, self.max)314 return f"IntRange({self.min}, {self.max})"315316317class FloatParamType(ParamType):318 name = "float"
1 unmodified line
320 def convert(self, value, param, ctx):321 try:322 return float(value)323 except ValueError:339 self.fail(340 "{} is not a valid floating point value".format(value), param, ctx341 )324 self.fail(f"{value} is not a valid floating point value", param, ctx)325326 def __repr__(self):327 return "FLOAT"328
28 unmodified lines
357 and rv > self.max358 ):359 if self.min is None:360 self.fail(378 "{} is bigger than the maximum valid value {}.".format(379 rv, self.max380 ),361 f"{rv} is bigger than the maximum valid value {self.max}.",362 param,363 ctx,364 )365 elif self.max is None:366 self.fail(386 "{} is smaller than the minimum valid value {}.".format(387 rv, self.min388 ),367 f"{rv} is smaller than the minimum valid value {self.min}.",368 param,369 ctx,370 )371 else:372 self.fail(394 "{} is not in the valid range of {} to {}.".format(395 rv, self.min, self.max396 ),373 f"{rv} is not in the valid range of {self.min} to {self.max}.",374 param,375 ctx,376 )377 return rv378379 def __repr__(self):403 return "FloatRange({}, {})".format(self.min, self.max)380 return f"FloatRange({self.min}, {self.max})"381382383class BoolParamType(ParamType):384 name = "boolean"
5 unmodified lines
390 if value in ("true", "t", "1", "yes", "y"):391 return True392 elif value in ("false", "f", "0", "no", "n"):393 return False417 self.fail("{} is not a valid boolean".format(value), param, ctx)394 self.fail(f"{value} is not a valid boolean", param, ctx)395396 def __repr__(self):397 return "BOOL"398
4 unmodified lines
403 def convert(self, value, param, ctx):404 import uuid405406 try:430 if PY2 and isinstance(value, text_type):431 value = value.encode("ascii")407 return uuid.UUID(value)408 except ValueError:434 self.fail("{} is not a valid UUID value".format(value), param, ctx)409 self.fail(f"{value} is not a valid UUID value", param, ctx)410411 def __repr__(self):412 return "UUID"413
74 unmodified lines
488 ctx.call_on_close(safecall(f.close))489 else:490 ctx.call_on_close(safecall(f.flush))491 return f517 except (IOError, OSError) as e: # noqa: B014492 except OSError as e: # noqa: B014493 self.fail(519 "Could not open file: {}: {}".format(520 filename_to_ui(value), get_streerror(e)521 ),494 f"Could not open file: {filename_to_ui(value)}: {get_strerror(e)}",495 param,496 ctx,497 )498
62 unmodified lines
561 self.path_type = "Path"562563 def coerce_path_result(self, rv):564 if self.type is not None and not isinstance(rv, self.type):592 if self.type is text_type:565 if self.type is str:566 rv = rv.decode(get_filesystem_encoding())567 else:568 rv = rv.encode(get_filesystem_encoding())569 return rv
12 unmodified lines
582 except OSError:583 if not self.exists:584 return self.coerce_path_result(rv)585 self.fail(613 "{} '{}' does not exist.".format(614 self.path_type, filename_to_ui(value)615 ),586 f"{self.path_type} {filename_to_ui(value)!r} does not exist.",587 param,588 ctx,589 )590591 if not self.file_okay and stat.S_ISREG(st.st_mode):592 self.fail(622 "{} '{}' is a file.".format(self.path_type, filename_to_ui(value)),593 f"{self.path_type} {filename_to_ui(value)!r} is a file.",594 param,595 ctx,596 )597 if not self.dir_okay and stat.S_ISDIR(st.st_mode):598 self.fail(628 "{} '{}' is a directory.".format(629 self.path_type, filename_to_ui(value)630 ),599 f"{self.path_type} {filename_to_ui(value)!r} is a directory.",600 param,601 ctx,602 )603 if self.writable and not os.access(value, os.W_OK):604 self.fail(636 "{} '{}' is not writable.".format(637 self.path_type, filename_to_ui(value)638 ),605 f"{self.path_type} {filename_to_ui(value)!r} is not writable.",606 param,607 ctx,608 )609 if self.readable and not os.access(value, os.R_OK):610 self.fail(644 "{} '{}' is not readable.".format(645 self.path_type, filename_to_ui(value)646 ),611 f"{self.path_type} {filename_to_ui(value)!r} is not readable.",612 param,613 ctx,614 )615
18 unmodified lines
634 self.types = [convert_type(ty) for ty in types]635636 @property637 def name(self):673 return "<{}>".format(" ".join(ty.name for ty in self.types))638 return f"<{' '.join(ty.name for ty in self.types)}>"639640 @property641 def arity(self):642 return len(self.types)
22 unmodified lines
665 if isinstance(ty, tuple):666 return Tuple(ty)667 if isinstance(ty, ParamType):668 return ty704 if ty is text_type or ty is str or ty is None:669 if ty is str or ty is None:670 return STRING671 if ty is int:672 return INT673 # Booleans are only okay if not guessed. This is done because for
11 unmodified lines
685 if __debug__:686 try:687 if issubclass(ty, ParamType):688 raise AssertionError(724 "Attempted to use an uninstantiated parameter type ({}).".format(ty)689 f"Attempted to use an uninstantiated parameter type ({ty})."690 )691 except TypeError:692 pass693 return FuncParamType(ty)694695696#: A dummy parameter type that just does nothing. From a user's732#: perspective this appears to just be the same as `STRING` but internally733#: no string conversion takes place. This is necessary to achieve the734#: same bytes/unicode behavior on Python 2/3 in situations where you want735#: to not convert argument types. This is usually useful when working736#: with file paths as they can appear in bytes and unicode.697#: perspective this appears to just be the same as `STRING` but698#: internally no string conversion takes place if the input was bytes.699#: This is usually useful when working with file paths as they can700#: appear in bytes and unicode.701#:702#: For path related uses the :class:`Path` type is a better choice but703#: there are situations where an unprocessed type is useful which is why704#: it is is provided.
22 unmodified lines
modified:src/click/utils.py+39 added-54 removed
1 unmodified line
2import sys34from ._compat import _default_text_stderr5from ._compat import _default_text_stdout6from ._compat import _find_binary_writer7from ._compat import auto_wrap_for_ansi8from ._compat import binary_streams9from ._compat import filename_to_ui10from ._compat import get_filesystem_encoding10from ._compat import get_streerror11from ._compat import get_strerror12from ._compat import is_bytes13from ._compat import open_stream13from ._compat import PY214from ._compat import should_strip_ansi15from ._compat import string_types15from ._compat import strip_ansi16from ._compat import text_streams18from ._compat import text_type17from ._compat import WIN18from .globals import resolve_color_default1922if not PY2:23 from ._compat import _find_binary_writer24elif WIN:25 from ._winconsole import _get_windows_argv26 from ._winconsole import _hash_py_argv27 from ._winconsole import _initial_argv_hash2029echo_native_types = string_types + (bytes, bytearray)21echo_native_types = (str, bytes, bytearray)222324def _posixify(name):25 return "-".join(name.split()).lower()
17 unmodified lines
43 try:44 return value.decode(get_filesystem_encoding())45 except UnicodeError:46 return value.decode("utf-8", "replace")55 return text_type(value)47 return str(value)484950def make_default_short_help(help, max_length=45):51 """Return a condensed version of help string."""
19 unmodified lines
7172 return "".join(result)737483class LazyFile(object):75class LazyFile:76 """A lazy file works like a regular file but it does not fully open77 the file but it does perform some basic checks early to see if the78 filename parameter does make sense. This is useful for safely opening79 files for writing.
24 unmodified lines
104105 def __repr__(self):106 if self._f is not None:107 return repr(self._f)116 return "<unopened file '{}' {}>".format(self.name, self.mode)108 return f"<unopened file '{self.name}' {self.mode}>"109110 def open(self):111 """Opens the file if it's not yet open. This call might fail with112 a :exc:`FileError`. Not handling this error will produce an error
4 unmodified lines
117 try:118 rv, self.should_close = open_stream(119 self.name, self.mode, self.encoding, self.errors, atomic=self.atomic120 )129 except (IOError, OSError) as e: # noqa: E402121 except OSError as e: # noqa: E402122 from .exceptions import FileError123132 raise FileError(self.name, hint=get_streerror(e))124 raise FileError(self.name, hint=get_strerror(e))125 self._f = rv126 return rv127128 def close(self):
18 unmodified lines
147 self.open()148 return iter(self._f)149150159class KeepOpenFile(object):151class KeepOpenFile:152 def __init__(self, file):153 self._file = file154155 def __getattr__(self, name):
66 unmodified lines
222 file = _default_text_stdout()223224 # Convert non bytes/text into the native string type.225 if message is not None and not isinstance(message, echo_native_types):234 message = text_type(message)226 message = str(message)227228 if nl:237 message = message or u""238 if isinstance(message, text_type):239 message += u"\n"229 message = message or ""230 if isinstance(message, str):231 message += "\n"232 else:233 message += b"\n"234243 # If there is a message, and we're in Python 3, and the value looks244 # like bytes, we manually need to find the binary stream and write the245 # message in there. This is done separately so that most stream246 # types will work as you would expect. Eg: you can write to StringIO247 # for other cases.248 if message and not PY2 and is_bytes(message):235 # If there is a message and the value looks like bytes, we manually236 # need to find the binary stream and write the message in there.237 # This is done separately so that most stream types will work as you238 # would expect. Eg: you can write to StringIO for other cases.239 if message and is_bytes(message):240 binary_file = _find_binary_writer(file)241 if binary_file is not None:242 file.flush()243 binary_file.write(message)
20 unmodified lines
264 file.flush()265266267def get_binary_stream(name):277 """Returns a system stream for byte processing. This essentially278 returns the stream from the sys module with the given name but it279 solves some compatibility issues between different Python versions.280 Primarily this function is necessary for getting binary streams on281 Python 3.268 """Returns a system stream for byte processing.269270 :param name: the name of the stream to open. Valid names are ``'stdin'``,271 ``'stdout'`` and ``'stderr'``272 """273 opener = binary_streams.get(name)274 if opener is None:288 raise TypeError("Unknown standard stream '{}'".format(name))275 raise TypeError(f"Unknown standard stream '{name}'")276 return opener()277278279def get_text_stream(name, encoding=None, errors="strict"):280 """Returns a system stream for text processing. This usually returns281 a wrapped stream around a binary stream returned from295 :func:`get_binary_stream` but it also can take shortcuts on Python 3296 for already correctly configured streams.282 :func:`get_binary_stream` but it also can take shortcuts for already283 correctly configured streams.284285 :param name: the name of the stream to open. Valid names are ``'stdin'``,286 ``'stdout'`` and ``'stderr'``287 :param encoding: overrides the detected default encoding.288 :param errors: overrides the default error mode.289 """290 opener = text_streams.get(name)291 if opener is None:305 raise TypeError("Unknown standard stream '{}'".format(name))292 raise TypeError(f"Unknown standard stream '{name}'")293 return opener(encoding, errors)294295296def open_file(
29 unmodified lines
326 return f327328329def get_os_args():343 """This returns the argument part of sys.argv in the most appropriate344 form for processing. What this means is that this return value is in345 a format that works for Click to process but does not necessarily346 correspond well to what's actually standard for the interpreter.330 """Returns the argument part of ``sys.argv``, removing the first331 value which is the name of the script.332348 On most environments the return value is ``sys.argv[:1]`` unchanged.349 However if you are on Windows and running Python 2 the return value350 will actually be a list of unicode strings instead because the351 default behavior on that platform otherwise will not be able to352 carry all possible values that sys.argv can have.353354 .. versionadded:: 6.0333 .. deprecated:: 8.0334 Will be removed in 8.1. Access ``sys.argv[1:]`` directly335 instead.336 """356 # We can only extract the unicode argv if sys.argv has not been357 # changed since the startup of the application.358 if PY2 and WIN and _initial_argv_hash == _hash_py_argv():359 return _get_windows_argv()337 import warnings338339 warnings.warn(340 "'get_os_args' is deprecated and will be removed in 8.1. Access"341 " 'sys.argv[1:]' directly instead.",342 DeprecationWarning,343 stacklevel=2,344 )345 return sys.argv[1:]346347348def format_filename(filename, shorten=False):
54 unmodified lines
403 if folder is None:404 folder = os.path.expanduser("~")405 return os.path.join(folder, app_name)406 if force_posix:422 return os.path.join(os.path.expanduser("~/.{}".format(_posixify(app_name))))407 return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))408 if sys.platform == "darwin":409 return os.path.join(410 os.path.expanduser("~/Library/Application Support"), app_name411 )
2 unmodified lines
414 _posixify(app_name),415 )416417433class PacifyFlushWrapper(object):418class PacifyFlushWrapper:419 """This wrapper is used to catch and suppress BrokenPipeErrors resulting420 from ``.flush()`` being called on broken pipe during the shutdown/final-GC421 of the Python interpreter. Notably ``.flush()`` is always called on422 ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any
6 unmodified lines
429430 def flush(self):431 try:432 self.wrapped.flush()448 except IOError as e:433 except OSError as e:434 import errno435436 if e.errno != errno.EPIPE:437 raise
3 unmodified lines
modified:tests/test_arguments.py+17 added-27 removed
1# -*- coding: utf-8 -*-1import sys23import pytest45import click7from click._compat import PY28from click._compat import text_type678def test_nargs_star(runner):9 @click.command()10 @click.argument("src", nargs=-1)11 @click.argument("dst")12 def copy(src, dst):16 click.echo("src={}".format("|".join(src)))17 click.echo("dst={}".format(dst))13 click.echo(f"src={'|'.join(src)}")14 click.echo(f"dst={dst}")1516 result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])17 assert not result.exception18 assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]
12 unmodified lines
31 @click.command()32 @click.argument("name", nargs=1)33 @click.argument("point", nargs=2, type=click.INT)34 def copy(name, point):38 click.echo("name={}".format(name))39 click.echo("point={0[0]}/{0[1]}".format(point))35 click.echo(f"name={name}")36 x, y = point37 click.echo(f"point={x}/{y}")3839 result = runner.invoke(copy, ["peter", "1", "2"])40 assert not result.exception41 assert result.output.splitlines() == ["name=peter", "point=1/2"]
11 unmodified lines
5354 @click.command()55 @click.argument("item", **opts)56 def copy(item):59 click.echo("name={0[0]} id={0[1]:d}".format(item))57 name, id = item58 click.echo(f"name={name} id={id:d}")5960 result = runner.invoke(copy, ["peter", "1"])61 assert not result.exception62 assert result.output.splitlines() == ["name=peter id=1"]
18 unmodified lines
81 @click.command()82 @click.argument("arg")83 def from_bytes(arg):84 assert isinstance(86 arg, text_type85 arg, str86 ), "UTF-8 encoded argument should be implicitly converted to Unicode"8788 # Simulate empty locale environment variables90 if PY2:91 monkeypatch.setattr(sys.stdin, "encoding", "ANSI_X3.4-1968")92 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "ANSI_X3.4-1968")93 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "ascii")94 else:95 monkeypatch.setattr(sys.stdin, "encoding", "utf-8")96 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")97 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")89 monkeypatch.setattr(sys.stdin, "encoding", "utf-8")90 monkeypatch.setattr(sys, "getfilesystemencoding", lambda: "utf-8")91 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")9293 runner.invoke(94 from_bytes,101 [u"Something outside of ASCII range: 林".encode("UTF-8")],95 ["Something outside of ASCII range: 林".encode()],96 catch_exceptions=False,97 )9899
88 unmodified lines
188def test_empty_nargs(runner):189 @click.command()190 @click.argument("arg", nargs=-1)191 def cmd(arg):198 click.echo("arg:{}".format("|".join(arg)))192 click.echo(f"arg:{'|'.join(arg)}")193194 result = runner.invoke(cmd, [])195 assert result.exit_code == 0196 assert result.output == "arg:\n"197198 @click.command()199 @click.argument("arg", nargs=-1, required=True)200 def cmd2(arg):207 click.echo("arg:{}".format("|".join(arg)))201 click.echo(f"arg:{'|'.join(arg)}")202203 result = runner.invoke(cmd2, [])204 assert result.exit_code == 2205 assert "Missing argument 'ARG...'" in result.output
2 unmodified lines
208def test_missing_arg(runner):209 @click.command()210 @click.argument("arg")211 def cmd(arg):218 click.echo("arg:{}".format(arg))212 click.echo(f"arg:{arg}")213214 result = runner.invoke(cmd, [])215 assert result.exit_code == 2216 assert "Missing argument 'ARG'." in result.output
44 unmodified lines
261 for arg in (a, b, c):262 click.echo(arg)263264 result = runner.invoke(cmd, ["a", "b", "c"])271 assert result.output.splitlines() == ["(u'a',)" if PY2 else "('a',)", "b", "c"]265 assert result.output.splitlines() == ["('a',)", "b", "c"]266267268def test_nargs_specified_plus_star_ordering(runner):269 @click.command()
4 unmodified lines
274 for arg in (a, b, c):275 click.echo(arg)276277 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])284 assert result.output.splitlines() == [285 "(u'a', u'b', u'c')" if PY2 else "('a', 'b', 'c')",286 "d",287 "(u'e', u'f')" if PY2 else "('e', 'f')",288 ]278 assert result.output.splitlines() == ["('a', 'b', 'c')", "d", "('e', 'f')"]279280281def test_defaults_for_nargs(runner):282 @click.command()
23 unmodified lines
modified:tests/test_bashcomplete.py-1 removed
1# -*- coding: utf-8 -*-1import pytest23import click4from click._bashcomplete import get_choices
495 unmodified lines
modified:tests/test_basic.py+13 added-14 removed
1# -*- coding: utf-8 -*-1import os2import uuid34import click
75 unmodified lines
80def test_basic_option(runner):81 @click.command()82 @click.option("--foo", default="no value")83 def cli(foo):85 click.echo(u"FOO:[{}]".format(foo))84 click.echo(f"FOO:[{foo}]")8586 result = runner.invoke(cli, [])87 assert not result.exception88 assert "FOO:[no value]" in result.output
9 unmodified lines
98 result = runner.invoke(cli, ["--foo="])99 assert not result.exception100 assert "FOO:[]" in result.output101103 result = runner.invoke(cli, [u"--foo=\N{SNOWMAN}"])102 result = runner.invoke(cli, ["--foo=\N{SNOWMAN}"])103 assert not result.exception105 assert u"FOO:[\N{SNOWMAN}]" in result.output104 assert "FOO:[\N{SNOWMAN}]" in result.output105106107def test_int_option(runner):108 @click.command()109 @click.option("--foo", default=42)110 def cli(foo):112 click.echo("FOO:[{}]".format(foo * 2))111 click.echo(f"FOO:[{foo * 2}]")112113 result = runner.invoke(cli, [])114 assert not result.exception115 assert "FOO:[84]" in result.output
13 unmodified lines
129 "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID130 )131 def cli(u):132 assert type(u) is uuid.UUID134 click.echo("U:[{}]".format(u))133 click.echo(f"U:[{u}]")134135 result = runner.invoke(cli, [])136 assert not result.exception137 assert "U:[ba122011-349f-423b-873b-9d6a79c688ab]" in result.output
11 unmodified lines
149 @click.command()150 @click.option("--foo", default=42, type=click.FLOAT)151 def cli(foo):152 assert type(foo) is float154 click.echo("FOO:[{}]".format(foo))153 click.echo(f"FOO:[{foo}]")154155 result = runner.invoke(cli, [])156 assert not result.exception157 assert "FOO:[42.0]" in result.output
22 unmodified lines
180 assert not result.exception181 assert result.output == "False\n"182 result = runner.invoke(cli, [])183 assert not result.exception185 assert result.output == "{}\n".format(default)184 assert result.output == f"{default}\n"185186 for default in True, False:187188 @click.command()
2 unmodified lines
191 click.echo(flag)192193 result = runner.invoke(cli, ["--flag"])194 assert not result.exception196 assert result.output == "{}\n".format(not default)195 assert result.output == f"{not default}\n"196 result = runner.invoke(cli, [])197 assert not result.exception199 assert result.output == "{}\n".format(default)198 assert result.output == f"{default}\n"199200201def test_boolean_conversion(runner):202 for default in True, False:
14 unmodified lines
217 assert result.output == "False\n"218219 result = runner.invoke(cli, [])220 assert not result.exception222 assert result.output == "{}\n".format(default)221 assert result.output == f"{default}\n"222223224def test_file_option(runner):225 @click.command()
80 unmodified lines
306307 @click.command()308 @click.option("-f", type=click.Path(exists=True))309 def showtype(f):311 click.echo("is_file={}".format(os.path.isfile(f)))312 click.echo("is_dir={}".format(os.path.isdir(f)))310 click.echo(f"is_file={os.path.isfile(f)}")311 click.echo(f"is_dir={os.path.isdir(f)}")312313 with runner.isolated_filesystem():314 result = runner.invoke(showtype, ["-f", "xxx"])315 assert "does not exist" in result.output
4 unmodified lines
320321 @click.command()322 @click.option("-f", type=click.Path())323 def exists(f):325 click.echo("exists={}".format(os.path.exists(f)))324 click.echo(f"exists={os.path.exists(f)}")325326 with runner.isolated_filesystem():327 result = runner.invoke(exists, ["-f", "xxx"])328 assert "exists=False" in result.output
231 unmodified lines
modified:tests/test_chain.py+7 added-8 removed
5 unmodified lines
678def debug():9 click.echo(10 "{}={}".format(11 sys._getframe(1).f_code.co_name, "|".join(click.get_current_context().args)12 )10 f"{sys._getframe(1).f_code.co_name}"11 f"={'|'.join(click.get_current_context().args)}"12 )131415def test_basic_chaining(runner):
59 unmodified lines
7576 @cli.command("sdist")77 @click.option("--format")78 def sdist(format):80 click.echo("sdist called {}".format(format))79 click.echo(f"sdist called {format}")8081 @cli.command("bdist")82 @click.option("--format")83 def bdist(format):85 click.echo("bdist called {}".format(format))84 click.echo(f"bdist called {format}")8586 result = runner.invoke(cli, ["bdist", "--format=1", "sdist", "--format=2"])87 assert not result.exception88 assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]
6 unmodified lines
9596 @cli.command("sdist")97 @click.argument("format")98 def sdist(format):100 click.echo("sdist called {}".format(format))99 click.echo(f"sdist called {format}")100101 @cli.command("bdist")102 @click.argument("format")103 def bdist(format):105 click.echo("bdist called {}".format(format))104 click.echo(f"bdist called {format}")105106 result = runner.invoke(cli, ["bdist", "1", "sdist", "2"])107 assert not result.exception108 assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]
81 unmodified lines
190191 @click.group(chain=True)192 @click.argument("arg")193 def cli(arg):195 click.echo("cli:{}".format(arg))194 click.echo(f"cli:{arg}")195196 @cli.command()197 def a():198 click.echo("a")
31 unmodified lines
modified:tests/test_commands.py+5 added-6 removed
1# -*- coding: utf-8 -*-1import re23import click4
19 unmodified lines
2425 @cli.command()26 @click.option("--count", default=1)27 def test(count):29 click.echo("Count: {:d}".format(count))28 click.echo(f"Count: {count:d}")2930 @cli.command()31 @click.option("--count", default=1)32 @click.pass_context
67 unmodified lines
100def test_group_with_args(runner):101 @click.group()102 @click.argument("obj")103 def cli(obj):105 click.echo("obj={}".format(obj))104 click.echo(f"obj={obj}")105106 @cli.command()107 def move():108 click.echo("move")
100 unmodified lines
209210 @cli.command()211 @click.pass_context212 def sync(ctx):214 click.echo("Debug is {}".format("on" if ctx.obj["DEBUG"] else "off"))213 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")214215 result = runner.invoke(cli, ["sync"])216 assert result.exception is None217 assert result.output == "Debug is off\n"
44 unmodified lines
262 @click.command(context_settings=dict(ignore_unknown_options=True))263 @click.argument("args", nargs=-1, type=click.UNPROCESSED)264 @click.option("--verbose", "-v", count=True)265 def cli(verbose, args):267 click.echo("Verbosity: {}".format(verbose))268 click.echo("Args: {}".format("|".join(args)))266 click.echo(f"Verbosity: {verbose}")267 click.echo(f"Args: {'|'.join(args)}")268269 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])270 assert not result.exception271 assert result.output.splitlines() == [
29 unmodified lines
modified:tests/test_compat.py+1 added-17 removed
1import pytest23import click3from click._compat import should_strip_ansi4from click._compat import WIN568def test_legacy_callbacks(runner):9 def legacy_callback(ctx, value):10 return value.upper()1112 @click.command()13 @click.option("--foo", callback=legacy_callback)14 def cli(foo):15 click.echo(foo)1617 with pytest.warns(DeprecationWarning, match="2-arg style"):18 result = runner.invoke(cli, ["--foo", "wat"])19 assert result.exit_code == 020 assert "WAT" in result.output21227def test_bash_func_name():8 from click._bashcomplete import get_completion_script910 script = get_completion_script("foo-bar baz_blah", "_COMPLETE_VAR", "bash").strip()
11 unmodified lines
222324@pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")25def test_is_jupyter_kernel_output():42 class JupyterKernelFakeStream(object):26 class JupyterKernelFakeStream:27 pass2829 # implementation detail, aka cheapskate test30 JupyterKernelFakeStream.__module__ = "ipykernel.faked"
1 unmodified line
modified:tests/test_context.py+6 added-7 removed
1# -*- coding: utf-8 -*-1import pytest23import click4from click.core import ParameterSource567def test_ensure_context_objects(runner):9 class Foo(object):8 class Foo:9 def __init__(self):10 self.title = "default"1112 pass_foo = click.make_pass_decorator(Foo, ensure=True)
13 unmodified lines
26 assert result.output == "default\n"272829def test_get_context_objects(runner):31 class Foo(object):30 class Foo:31 def __init__(self):32 self.title = "default"3334 pass_foo = click.make_pass_decorator(Foo, ensure=True)
14 unmodified lines
49 assert result.output == "test\n"505152def test_get_context_objects_no_ensuring(runner):54 class Foo(object):53 class Foo:54 def __init__(self):55 self.title = "default"5657 pass_foo = click.make_pass_decorator(Foo)
14 unmodified lines
72 assert result.output == "test\n"737475def test_get_context_objects_missing(runner):77 class Foo(object):76 class Foo:77 pass7879 pass_foo = click.make_pass_decorator(Foo)80
49 unmodified lines
130 assert click.get_current_context(silent=True) is None131132133def test_context_meta(runner):135 LANG_KEY = "{}.lang".format(__name__)134 LANG_KEY = f"{__name__}.lang"135136 def set_language(value):137 click.get_current_context().meta[LANG_KEY] = value138
78 unmodified lines
217 Test to check that make_pass_decorator doesn't consume arguments based on218 invocation order.219 """220222 class Foo(object):221 class Foo:222 title = "foocmd"223224 pass_foo = click.make_pass_decorator(Foo)225
102 unmodified lines
modified:tests/test_defaults.py+3 added-3 removed
4 unmodified lines
5 @click.command()6 @click.option("--foo", default=42, type=click.FLOAT)7 def cli(foo):8 assert type(foo) is float9 click.echo("FOO:[{}]".format(foo))9 click.echo(f"FOO:[{foo}]")1011 result = runner.invoke(cli, [])12 assert not result.exception13 assert "FOO:[42.0]" in result.output
17 unmodified lines
31 @click.option(32 "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT33 )34 def cli(arg):35 for item in arg:36 click.echo("<{0[0]:d}|{0[1]:d}>".format(item))35 for a, b in arg:36 click.echo(f"<{a:d}|{b:d}>")3738 result = runner.invoke(cli, [])39 assert not result.exception40 assert result.output.splitlines() == ["<1|2>", "<3|4>"]
modified:tests/test_formatting.py+4 added-5 removed
1# -*- coding: utf-8 -*-1import click234def test_basic_functionality(runner):
144 unmodified lines
149def test_formatting_usage_error(runner):150 @click.command()151 @click.argument("arg")152 def cmd(arg):154 click.echo("arg:{}".format(arg))153 click.echo(f"arg:{arg}")154155 result = runner.invoke(cmd, [])156 assert result.exit_code == 2157 assert result.output.splitlines() == [
48 unmodified lines
206207 @cmd.command()208 @click.argument("bar")209 def foo(bar):211 click.echo("foo:{}".format(bar))210 click.echo(f"foo:{bar}")211212 result = runner.invoke(cmd, ["foo"])213 assert result.exit_code == 2214 assert result.output.splitlines() == [
7 unmodified lines
222def test_formatting_usage_error_no_help(runner):223 @click.command(add_help_option=False)224 @click.argument("arg")225 def cmd(arg):227 click.echo("arg:{}".format(arg))226 click.echo(f"arg:{arg}")227228 result = runner.invoke(cmd, [])229 assert result.exit_code == 2230 assert result.output.splitlines() == [
6 unmodified lines
237def test_formatting_usage_custom_help(runner):238 @click.command(context_settings=dict(help_option_names=["--man"]))239 @click.argument("arg")240 def cmd(arg):242 click.echo("arg:{}".format(arg))241 click.echo(f"arg:{arg}")242243 result = runner.invoke(cmd, [])244 assert result.exit_code == 2245 assert result.output.splitlines() == [
107 unmodified lines
modified:tests/test_imports.py+2 added-7 removed
4 unmodified lines
5from click._compat import WIN678IMPORT_TEST = b"""\9try:10 import __builtin__ as builtins11except ImportError:12 import builtins9import builtins1011found_imports = set()12real_import = builtins.__import__13import sys
43 unmodified lines
57 c = subprocess.Popen(58 [sys.executable, "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE59 )60 rv = c.communicate(IMPORT_TEST)[0]6465 if sys.version_info[0] != 2:66 rv = rv.decode("utf-8")61 rv = rv.decode("utf-8")62 imported = json.loads(rv)6364 for module in imported:65 if module == "click" or module.startswith("click."):
2 unmodified lines
modified:tests/test_options.py+15 added-16 removed
1# -*- coding: utf-8 -*-1import os2import re34import pytest56import click8from click._compat import text_type789def test_prefixes(runner):10 @click.command()11 @click.option("++foo", is_flag=True, help="das foo")12 @click.option("--bar", is_flag=True, help="das bar")13 def cli(foo, bar):16 click.echo("foo={} bar={}".format(foo, bar))14 click.echo(f"foo={foo} bar={bar}")1516 result = runner.invoke(cli, ["++foo", "--bar"])17 assert not result.exception18 assert result.output == "foo=True bar=True\n"
24 unmodified lines
43def test_nargs_tup_composite_mult(runner):44 @click.command()45 @click.option("--item", type=(str, int), multiple=True)46 def copy(item):49 for item in item:50 click.echo("name={0[0]} id={0[1]:d}".format(item))47 for name, id in item:48 click.echo(f"name={name} id={id:d}")4950 result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])51 assert not result.exception52 assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]
2 unmodified lines
55def test_counting(runner):56 @click.command()57 @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))58 def cli(v):61 click.echo("verbosity={:d}".format(v))59 click.echo(f"verbosity={v:d}")6061 result = runner.invoke(cli, ["-vvv"])62 assert not result.exception63 assert result.output == "verbosity=3\n"
20 unmodified lines
84 pass8586 result = runner.invoke(cli, [unknown_flag])87 assert result.exception90 assert "no such option: {}".format(unknown_flag) in result.output88 assert f"no such option: {unknown_flag}" in result.output899091def test_multiple_required(runner):92 @click.command()
13 unmodified lines
106def test_empty_envvar(runner):107 @click.command()108 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")109 def cli(mypath):112 click.echo("mypath: {}".format(mypath))110 click.echo(f"mypath: {mypath}")111112 result = runner.invoke(cli, [], env={"MYPATH": ""})113 assert result.exit_code == 0114 assert result.output == "mypath: None\n"
28 unmodified lines
143 result = runner.invoke(144 cmd,145 [],146 auto_envvar_prefix="TEST",149 env={"TEST_ARG": "foo{}bar".format(os.path.pathsep)},147 env={"TEST_ARG": f"foo{os.path.pathsep}bar"},148 )149 assert not result.exception150 assert result.output == "foo|bar\n"151
15 unmodified lines
167 @click.command()168 @click.option("--arg1", multiple=True, default=("foo", "bar"))169 @click.option("--arg2", multiple=True, default=(1, "a"))170 def cmd(arg1, arg2):173 assert all(isinstance(e[0], text_type) for e in arg1)174 assert all(isinstance(e[1], text_type) for e in arg1)171 assert all(isinstance(e[0], str) for e in arg1)172 assert all(isinstance(e[1], str) for e in arg1)173174 assert all(isinstance(e[0], int) for e in arg2)177 assert all(isinstance(e[1], text_type) for e in arg2)175 assert all(isinstance(e[1], str) for e in arg2)176177 result = runner.invoke(178 cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split()179 )
240 unmodified lines
420 pass421422 result = runner.invoke(cmd, ["--help"],)423 assert result.exit_code == 0424 i = " " * 21425 assert (426 " -C, --config PATH Configuration file to use.\n"428 "{i}\n"429 "{i}If not given, the environment variable CONFIG_FILE is\n"430 "{i}consulted and used if set. If neither are given, a default\n"431 "{i}configuration file is loaded.".format(i=" " * 21)427 f"{i}\n"428 f"{i}If not given, the environment variable CONFIG_FILE is\n"429 f"{i}consulted and used if set. If neither are given, a default\n"430 f"{i}configuration file is loaded."431 ) in result.output432433434def test_argument_custom_class(runner):
123 unmodified lines
modified:tests/test_termui.py+10 added-11 removed
1# -*- coding: utf-8 -*-1import time23import pytest45import click._termui_impl6from click._compat import WIN7810class FakeClock(object):9class FakeClock:10 def __init__(self):11 self.now = time.time()1213 def advance_time(self, seconds=1):
26 unmodified lines
40 assert label in runner.invoke(cli, []).output414243def test_progressbar_length_hint(runner, monkeypatch):45 class Hinted(object):44 class Hinted:45 def __init__(self, n):46 self.items = list(range(n))4748 def __length_hint__(self):
72 unmodified lines
121def test_progressbar_format_pos(runner, pos, length):122 with _create_progress(length, length_known=length != 0, pos=pos) as progress:123 result = progress.format_pos()124 if progress.length_known:126 assert result == "{}/{}".format(pos, length)125 assert result == f"{pos}/{length}"126 else:127 assert result == str(pos)128129
116 unmodified lines
246 def cli(f):247 click.echo(f.name)248249 result = runner.invoke(cli)251 assert result.output == "file [{0}]: \n{0}\n".format(__file__)250 assert result.output == f"file [{__file__}]: \n{__file__}\n"251252253def test_secho(runner):254 with runner.isolation() as outstreams:
34 unmodified lines
289290 @click.command()291 def cli():292 with click.progressbar(294 range(4), item_show_func=lambda x: "Custom {}".format(x)293 range(4), item_show_func=lambda x: f"Custom {x}"294 ) as progress:295 for _ in progress:296 fake_clock.advance_time()297 print("")
15 unmodified lines
313314 @click.command()315 def cli():316 with click.progressbar(318 length=6, item_show_func=lambda x: "Custom {}".format(x)317 length=6, item_show_func=lambda x: f"Custom {x}"318 ) as progress:319 while not progress.finished:320 fake_clock.advance_time()321 progress.update(2, progress.pos)
9 unmodified lines
331 assert "Custom 2" in lines[1]332 assert "Custom 4" in lines[2]333334336@pytest.mark.parametrize("key_char", (u"h", u"H", u"é", u"À", u" ", u"字", u"àH", u"àR"))335@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))336@pytest.mark.parametrize("echo", [True, False])337@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")338def test_getchar_windows(runner, monkeypatch, key_char, echo):339 monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)
2 unmodified lines
342 assert click.getchar(echo) == key_char343344345@pytest.mark.parametrize(347 "special_key_char, key_char", [(u"\x00", "a"), (u"\x00", "b"), (u"\xe0", "c")]346 "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]347)348@pytest.mark.skipif(349 not WIN, reason="Tests special character inputs using the msvcrt module."350)
2 unmodified lines
353 monkeypatch.setattr(354 click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()355 )356 monkeypatch.setattr(click.termui, "_getchar", None)358 assert click.getchar() == special_key_char + key_char357 assert click.getchar() == f"{special_key_char}{key_char}"358359360@pytest.mark.parametrize(362 ("key_char", "exc"), [(u"\x03", KeyboardInterrupt), (u"\x1a", EOFError)],361 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)],362)363@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")364def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):365 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)
4 unmodified lines
modified:tests/test_testing.py+7 added-13 removed
1import os2import sys3from io import BytesIO45import pytest67import click7from click._compat import PY28from click._compat import WIN9from click.testing import CliRunner1011# Use the most reasonable io that users would use for the python version.12if PY2:13 from cStringIO import StringIO as ReasonableBytesIO14else:15 from io import BytesIO as ReasonableBytesIO111712def test_runner():13 @click.command()14 def test():15 i = click.get_binary_stream("stdin")
28 unmodified lines
44 o.write(chunk)45 o.flush()4647 runner = CliRunner()54 result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))48 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))49 assert not result.exception50 assert result.output == "Hello World!\n"5152 runner = CliRunner(echo_stdin=True)59 result = runner.invoke(test, input=ReasonableBytesIO(b"Hello World!\n"))53 result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))54 assert not result.exception55 assert result.output == "Hello World!\nHello World!\n"565758def test_prompts():59 @click.command()60 @click.option("--foo", prompt=True)61 def test(foo):68 click.echo("foo={}".format(foo))62 click.echo(f"foo={foo}")6364 runner = CliRunner()65 result = runner.invoke(test, input="wau wau\n")66 assert not result.exception
1 unmodified line
6869 @click.command()70 @click.option("--foo", prompt=True, hide_input=True)71 def test(foo):78 click.echo("foo={}".format(foo))72 click.echo(f"foo={foo}")7374 runner = CliRunner()75 result = runner.invoke(test, input="wau wau\n")76 assert not result.exception
47 unmodified lines
124 assert result.output == "hello world\n"125 assert not result.exception126127 result = runner.invoke(cli, color=True)134 assert result.output == "{}\n".format(click.style("hello world", fg="blue"))128 assert result.output == f"{click.style('hello world', fg='blue')}\n"129 assert not result.exception130131132def test_with_color_but_pause_not_blocking():
79 unmodified lines
212213def test_env():214 @click.command()215 def cli_env():222 click.echo("ENV={}".format(os.environ["TEST_CLICK_ENV"]))216 click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")217218 runner = CliRunner()219220 env_orig = dict(os.environ)
77 unmodified lines
modified:tests/test_utils.py+12 added-29 removed
1import os2import stat3import sys4from io import StringIO56import pytest78import click._termui_impl
2 unmodified lines
111213def test_echo(runner):14 with runner.isolation() as outstreams:14 click.echo(u"\N{SNOWMAN}")15 click.echo("\N{SNOWMAN}")16 click.echo(b"\x44\x44")17 click.echo(42, nl=False)18 click.echo(b"a", nl=False)19 click.echo("\x1b[31mx\x1b[39m", nl=False)20 bytes = outstreams[0].getvalue().replace(b"\r\n", b"\n")21 assert bytes == b"\xe2\x98\x83\nDD\n42ax"2222 # If we are in Python 2, we expect that writing bytes into a string io23 # does not do anything crazy. In Python 324 if sys.version_info[0] == 2:25 import StringIO2627 sys.stdout = x = StringIO.StringIO()28 try:29 click.echo("\xf6")30 finally:31 sys.stdout = sys.__stdout__32 assert x.getvalue() == "\xf6\n"3334 # And in any case, if wrapped, we expect bytes to survive.23 # if wrapped, we expect bytes to survive.24 @click.command()25 def cli():26 click.echo(b"\xf6")27
9 unmodified lines
37def test_echo_custom_file():38 import io3940 f = io.StringIO()52 click.echo(u"hello", file=f)53 assert f.getvalue() == u"hello\n"41 click.echo("hello", file=f)42 assert f.getvalue() == "hello\n"434445@pytest.mark.parametrize(46 ("styles", "ref"),
32 unmodified lines
7980def test_filename_formatting():81 assert click.format_filename(b"foo.txt") == "foo.txt"82 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"94 assert click.format_filename(u"/x/foo.txt") == "/x/foo.txt"95 assert click.format_filename(u"/x/foo.txt", shorten=True) == "foo.txt"83 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"84 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"8586 # filesystem encoding on windows permits this.87 if not WIN:99 assert (100 click.format_filename(b"/x/foo\xff.txt", shorten=True) == u"foo\ufffd.txt"101 )88 assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\ufffd.txt"899091def test_prompts(runner):92 @click.command()
96 unmodified lines
189 assert styled_text == "\x1b[31mfoo\x1b[0m"190191 click.echo(styled_text, color=False)192 out, err = capfd.readouterr()206 assert out == "{}\n".format(text)193 assert out == f"{text}\n"194195 click.echo(styled_text, color=True)196 out, err = capfd.readouterr()210 assert out == "{}\n".format(styled_text)197 assert out == f"{styled_text}\n"198199 isatty = True200 click.echo(styled_text)201 out, err = capfd.readouterr()215 assert out == "{}\n".format(styled_text)202 assert out == f"{styled_text}\n"203204 isatty = False205 click.echo(styled_text)206 out, err = capfd.readouterr()220 assert out == "{}\n".format(text)207 assert out == f"{text}\n"208209210@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")211def test_echo_writing_to_standard_error(capfd, monkeypatch):212 def emulate_input(text):213 """Emulate keyboard input."""227 if sys.version_info[0] == 2:228 from StringIO import StringIO229 else:230 from io import StringIO214 monkeypatch.setattr(sys, "stdin", StringIO(text))215216 click.echo("Echo to standard output")217 out, err = capfd.readouterr()
161 unmodified lines
modified:.azure-pipelines.yml+8 added-15 removed
7 unmodified lines
8 TOXENV: py910strategy:11 matrix:12 Python 3.8 Linux:12 Linux:13 vmImage: ubuntu-latest14 Python 3.8 Windows:14 Windows:15 vmImage: windows-latest16 Python 3.8 Mac:16 Mac:17 vmImage: macos-latest18 PyPy 3 Linux:19 python.version: pypy320 Python 3.7 Linux:18 Python 3.7:19 python.version: '3.7'22 Python 3.6 Linux:20 Python 3.6:21 python.version: '3.6'24 Python 3.5 Linux:25 python.version: '3.5'26 Python 2.7 Linux:27 python.version: '2.7'28 Python 2.7 Windows:29 vmImage: windows-latest30 python.version: '2.7'22 PyPy:23 python.version: pypy324 Docs:25 TOXENV: docs26 Style:27 TOXENV: style
3 unmodified lines
3132steps:33 - task: UsePythonVersion@034 inputs:42 versionSpec: "$(python.version)"35 versionSpec: $(python.version)36 displayName: Use Python $(python.version)3738 - script: pip --disable-pip-version-check install -U tox39 displayName: Install tox
3 unmodified lines
modified:.pre-commit-config.yaml+3 added-2 removed
1repos:2 - repo: https://github.com/asottile/pyupgrade3 rev: v2.1.03 rev: v2.2.04 hooks:5 - id: pyupgrade6 args: ["--py36-plus"]7 - repo: https://github.com/asottile/reorder_python_imports7 rev: v2.0.08 rev: v2.2.09 hooks:10 - id: reorder-python-imports11 args: ["--application-directories", "src"]12 - repo: https://github.com/ambv/black
16 unmodified lines
modified:CHANGES.rst+1 added
3 unmodified lines
4-----------56Unreleased78- Drop support for Python 2 and 3.5.9- Adds a repr to Command, showing the command name for friendlier10 debugging. :issue:`1267`, :pr:`1295`11- Add support for distinguishing the source of a command line12 parameter. :issue:`1264`, :pr:`1329`
627 unmodified lines
modified:setup.cfg+30 added-4 removed
1[metadata]2name = click3version = attr: click.__version__4url = https://palletsprojects.com/p/click/5project_urls =6 Documentation = https://click.palletsprojects.com/7 Code = https://github.com/pallets/click8 Issue tracker = https://github.com/pallets/click/issues9license = BSD-3-Clause2license_file = LICENSE.rst10license_files = LICENSE.rst11maintainer = Pallets12maintainer_email = contact@palletsprojects.com13description = Composable command line interface toolkit14long_description = file: README.rst15long_description_content_type = text/x-rst16classifiers =17 Development Status :: 5 - Production/Stable18 Intended Audience :: Developers19 License :: OSI Approved :: BSD License20 Operating System :: OS Independent21 Programming Language :: Python224[bdist_wheel]5universal = 123[options]24packages = find:25package_dir = = src26include_package_data = true27python_requires = >= 3.628# Dependencies are in setup.py for GitHub's dependency graph.2930[options.packages.find]31where = src3233[tool:pytest]34testpaths = tests35filterwarnings =36 error3738[coverage:run]13branch = True39branch = true40source =41 src42 tests43
27 unmodified lines
modified:setup.py+1 added-38 removed
1import io2import re34from setuptools import find_packages1from setuptools import setup27with io.open("README.rst", "rt", encoding="utf8") as f:8 readme = f.read()910with io.open("src/click/__init__.py", "rt", encoding="utf8") as f:11 version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)1213setup(14 name="click",15 version=version,16 url="https://palletsprojects.com/p/click/",17 project_urls={18 "Documentation": "https://click.palletsprojects.com/",19 "Code": "https://github.com/pallets/click",20 "Issue tracker": "https://github.com/pallets/click/issues",21 },22 license="BSD-3-Clause",23 maintainer="Pallets",24 maintainer_email="contact@palletsprojects.com",25 description="Composable command line interface toolkit",26 long_description=readme,27 packages=find_packages("src"),28 package_dir={"": "src"},29 include_package_data=True,30 python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",31 classifiers=[32 "Development Status :: 5 - Production/Stable",33 "Intended Audience :: Developers",34 "License :: OSI Approved :: BSD License",35 "Operating System :: OS Independent",36 "Programming Language :: Python",37 "Programming Language :: Python :: 2",38 "Programming Language :: Python :: 3",39 ],40)3setup(name="click")
modified:tox.ini+1 added-1 removed
1[tox]2envlist =3 py{38,37,36,35,27,py3,py}3 py{38,37,36,py3}4 style5 docs6skip_missing_interpreters = true7
14 unmodified lines