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
Provenance
- Commit
97de2c9- Tree
556f74b- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
19fdc85- Parent 2
a1d726b
61 files changed+849 added−1498 removed
modified:docs/advanced.rst+7 added-7 removed
44 unmodified lines45 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))}")50 51 And it can then be used like this:52 53 .. click:example::37 unmodified lines91 @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}")96 97 In this case the callback returns the URL unchanged but also passes a98 second ``fp`` value to the callback. What's more recommended is to pass99 the information in a wrapper however:15 unmodified lines115 @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}")120 121 122 Token Normalization123 -------------------15 unmodified lines139 140 @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}")144 145 And how it works on the command line:146 147 .. click:run::22 unmodified lines170 171 @cli.command()172 @click.option('--count', default=1)173 def test(count):174- click.echo('Count: %d' % count)174+ click.echo(f'Count: {count}')175 176 @cli.command()177 @click.option('--count', default=1)178 @click.pass_context120 unmodified lines299 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)305 306 And what it looks like:307 87 unmodified lines395 @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}")400 401 .. click:run::402 403 invoke(cli, prog_name='cli', args=['8080'])5 unmodified linesmodified:docs/arguments.rst+1 added-1 removed
53 unmodified lines54 @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}")59 60 And what it looks like:61 62 .. click:run::207 unmodified linesmodified:docs/bashcomplete.rst+3 added-3 removed
48 unmodified lines49 50 @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]}")55 56 57 Completion help strings58 -----------------------19 unmodified lines78 79 @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}")83 84 85 Activation86 ----------77 unmodified linesmodified:docs/commands.rst+5 added-5 removed
23 unmodified lines24 25 @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'}")29 30 @cli.command() # @cli, not @click!31 def sync():32 click.echo('Syncing')62 unmodified lines95 96 @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'}")100 101 if __name__ == '__main__':102 cli(obj={})103 61 unmodified lines165 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}")170 171 @cli.command()172 def sync():173 click.echo('The subcommand')291 unmodified lines465 466 @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}/")470 471 if __name__ == '__main__':472 cli(default_map={473 'runserver': {37 unmodified lines511 512 @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}/")516 517 if __name__ == '__main__':518 cli()519 52 unmodified linesmodified:docs/conf.py+5 added
1 from pallets_sphinx_themes import get_version2 from pallets_sphinx_themes import ProjectLink3 4+import click._compat5+6+# compat until pallets-sphinx-themes is updated7+click._compat.text_type = str8+9 # Project --------------------------------------------------------------10 11 project = "Click"12 copyright = "2014 Pallets"43 unmodified linesmodified:docs/documentation.rst+2 added-2 removed
22 unmodified lines23 @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}!")28 29 And what it looks like:30 31 .. click:run::140 unmodified lines172 @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}!")177 178 Example:179 180 .. click:run::61 unmodified linesmodified:docs/index.rst+2 added-2 removed
34 unmodified lines35 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}!")40 41 if __name__ == '__main__':42 hello()43 36 unmodified lines80 testing81 utils82 bashcomplete83 exceptions84- python384+ unicode-support85 wincmd86 87 API Reference88 -------------19 unmodified linesmodified:docs/options.rst+22 added-18 removed
83 unmodified lines84 @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}")89 90 And on the command line:91 92 .. click:run::27 unmodified lines120 121 @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}")126 127 And on the command line:128 129 .. click:run::16 unmodified lines146 147 @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}")152 153 And on the command line:154 155 .. click:run::8 unmodified lines164 165 @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}")170 171 .. _multiple-options:172 173 Multiple Options40 unmodified lines214 215 @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}")219 220 And on the command line:221 222 .. click:run::60 unmodified lines283 284 @click.command()285 @click.option('/debug;/no-debug')286 def log(debug):284- click.echo('debug=%s' % debug)287+ click.echo(f"debug={debug}")288 289 if __name__ == '__main__':290 log()291 112 unmodified lines404 405 @click.command()406 @click.option('--name', prompt=True)407 def hello(name):405- click.echo('Hello %s!' % name)408+ click.echo(f"Hello {name}!")409 410 And what it looks like:411 412 .. click:run::8 unmodified lines421 422 @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}!")426 427 What it looks like:428 429 .. click:run::15 unmodified lines445 @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')}")450 451 What it looks like:452 453 .. click:run::7 unmodified lines461 462 @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')}")466 467 Dynamic Defaults for Prompts468 ----------------------------469 157 unmodified lines627 628 @click.command()629 @click.option('--username')630 def greet(username):628- click.echo('Hello %s!' % username)631+ click.echo(f'Hello {username}!')632 633 if __name__ == '__main__':634 greet(auto_envvar_prefix='GREETER')635 16 unmodified lines652 653 @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'}")657 658 @cli.command()659 @click.option('--username')660 def greet(username):658- click.echo('Hello %s!' % username)661+ click.echo(f"Hello {username}!")662 663 if __name__ == '__main__':664 cli(auto_envvar_prefix='GREETER')665 13 unmodified lines679 680 @click.command()681 @click.option('--username', envvar='USERNAME')682 def greet(username):680- click.echo('Hello %s!' % username)683+ click.echo(f"Hello {username}!")684 685 if __name__ == '__main__':686 greet()687 40 unmodified lines728 729 .. click:run::730 731 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"})733 734 Other Prefix Characters735 -----------------------736 7 unmodified lines744 745 @click.command()746 @click.option('+w/-w')747 def chmod(w):745- click.echo('writable=%s' % w)748+ click.echo(f"writable={w}")749 750 if __name__ == '__main__':751 chmod()752 11 unmodified lines764 765 @click.command()766 @click.option('/debug;/no-debug')767 def log(debug):765- click.echo('debug=%s' % debug)768+ click.echo(f"debug={debug}")769 770 if __name__ == '__main__':771 log()772 63 unmodified lines836 837 @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)")842 843 if __name__ == '__main__':844 roll()845 7 unmodified linesdeleted:docs/python3.rst-191 removed
1-Python 3 Support2-================3-4-.. currentmodule:: click5-6-Click supports Python 3, but like all other command line utility libraries,7-it suffers from the Unicode text model in Python 3. All examples in the8-documentation were written so that they could run on both Python 2.x and9-Python 3.4 or higher.10-11-.. _python3-limitations:12-13-Python 3 Limitations14---------------------15-16-At the moment, Click suffers from a few problems with Python 3:17-18-* 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.22-23- 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!26-27- For more information see :ref:`python3-surrogates`.28-29-* 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.34-35- This is not supported::36-37- sys.stdin = io.StringIO('Input here')38- sys.stdout = io.StringIO()39-40- Instead you need to do this::41-42- 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')47-48- 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.51-52-Python 2 and 3 Differences53---------------------------54-55-Click attempts to minimize the differences between Python 2 and Python 356-by following best practices for both languages.57-58-In Python 2, the following is true:59-60-* ``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.71-72-In Python 3, the following is true:73-74-* ``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.80-81- 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.89-90-.. _python3-surrogates:91-92-Python 3 Surrogate Handling93----------------------------94-95-Click in Python 3 does all the Unicode handling in the standard library96-and is subject to its behavior. In Python 2, Click does all the Unicode97-handling itself, which means there are differences in error behavior.98-99-The most glaring difference is that in Python 2, Unicode will "just work",100-while in Python 3, it requires extra care. The reason for this is that in101-Python 3, the encoding detection is done in the interpreter, and on Linux102-and certain other operating systems, its encoding handling is problematic.103-104-The biggest source of frustration is that Click scripts invoked by105-init systems (sysvinit, upstart, systemd, etc.), deployment tools (salt,106-puppet), or cron jobs (cron) will refuse to work unless a Unicode locale is107-exported.108-109-If Click encounters such an environment it will prevent further execution110-to force you to set a locale. This is done because Click cannot know111-about the state of the system once it's invoked and restore the values112-before Python's Unicode handling kicked in.113-114-If you see something like this error in Python 3::115-116- 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.122-123-.. note::124-125- 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.128-129-You are dealing with an environment where Python 3 thinks you are130-restricted to ASCII data. The solution to these problems is different131-depending on which locale your computer is running in.132-133-For instance, if you have a German Linux machine, you can fix the problem134-by exporting the locale to ``de_DE.utf-8``::135-136- export LC_ALL=de_DE.utf-8137- export LANG=de_DE.utf-8138-139-If you are on a US machine, ``en_US.utf-8`` is the encoding of choice. On140-some newer Linux systems, you could also try ``C.UTF-8`` as the locale::141-142- export LC_ALL=C.UTF-8143- export LANG=C.UTF-8144-145-On some systems it was reported that `UTF-8` has to be written as `UTF8`146-and vice versa. To see which locales are supported you can invoke147-``locale -a``::148-149- locale -a150-151-You need to do this before you invoke your Python script. If you are152-curious about the reasons for this, you can join the discussions in the153-Python 3 bug tracker:154-155-* `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)164-165-Note (Python 3.7 onwards): Even though your locale may not be properly166-configured, Python 3.7 Click will not raise the above exception because Python167-3.7 programs are better at choosing default locales. This doesn't change the168-general issue that your locale may be misconfigured.169-170-Unicode Literals171-----------------172-173-Starting 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 to175-the negative consequences of this import with regards to unintentionally176-causing bugs due to introducing Unicode data to APIs that are incapable of177-handling them. For some examples of this issue, see the discussion on178-this github issue: `python-future#22179-<https://github.com/PythonCharmers/python-future/issues/22>`_.180-181-If you use ``unicode_literals`` in any file that defines a Click command182-or that invokes a click command you will be given a warning. You are183-strongly encouraged to not use ``unicode_literals`` and instead use184-explicit ``u`` prefixes for your Unicode strings.185-186-If you do want to ignore the warning and continue using187-``unicode_literals`` on your own peril, you can disable the warning as188-follows::189-190- import click191- click.disable_unicode_literals_warning = Truemodified:docs/quickstart.rst+3 added-5 removed
155 unmodified lines156 -------157 158 Why does this example use :func:`echo` instead of the regular159 :func:`print` function? The answer to this question is that Click160-attempts to support both Python 2 and Python 3 the same way and to be very160+attempts to support different environments consistently and to be very161 robust even when the environment is misconfigured. Click wants to be162 functional at least on a basic level even if everything is completely163 broken.164 3 unmodified lines168 169 As an added benefit, starting with Click 2.0, the echo function also170 has good support for ANSI colors. It will automatically strip ANSI codes171 if the output stream is a file and if colorama is supported, ANSI colors172-will also work on Windows. Note that in Python 2, the :func:`echo` function173-does not parse color code information from bytearrays. See :ref:`ansi-colors`174-for more information.172+will also work on Windows. See :ref:`ansi-colors`.173 174 If you don't need this, you can also use the `print()` construct /175 function.176 60 unmodified lines237 @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}!")242 243 What it looks like:244 245 .. click:run::30 unmodified linesmodified:docs/testing.rst+3 added-3 removed
28 unmodified lines29 30 @click.command()31 @click.argument('name')32 def hello(name):33- click.echo('Hello %s!' % name)33+ click.echo(f'Hello {name}!')34 35 .. code-block:: python36 :caption: test_hello.py37 15 unmodified lines53 54 @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'}")58 59 @cli.command()60 def sync():61 click.echo('Syncing')63 unmodified lines125 126 @click.command()127 @click.option('--foo', prompt=True)128 def prompt(foo):129- click.echo('foo=%s' % foo)129+ click.echo(f"foo={foo}")130 131 .. code-block:: python132 :caption: test_prompt.py133 12 unmodified linesadded:docs/unicode-support.rst+112 added
1+Unicode Support2+===============3+4+.. currentmodule:: click5+6+Click has to take extra care to support Unicode text in different7+environments.8+9+* 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.13+14+ 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!17+18+* 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.23+24+ This is not supported::25+26+ sys.stdin = io.StringIO('Input here')27+ sys.stdout = io.StringIO()28+29+ Instead you need to do this::30+31+ 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')36+37+ 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.40+41+* ``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.44+45+* ``sys.argv`` is always text. This means that the native type for46+ input values to the types in Click is Unicode, not bytes.47+48+ 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.51+52+* 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.57+58+59+Surrogate Handling60+------------------61+62+Click does all the Unicode handling in the standard library and is63+subject to its behavior. Unicode requires extra care. The reason for64+this is that the encoding detection is done in the interpreter, and on65+Linux and certain other operating systems, its encoding handling is66+problematic.67+68+The biggest source of frustration is that Click scripts invoked by init69+systems, deployment tools, or cron jobs will refuse to work unless a70+Unicode locale is exported.71+72+If Click encounters such an environment it will prevent further73+execution to force you to set a locale. This is done because Click74+cannot know about the state of the system once it's invoked and restore75+the values before Python's Unicode handling kicked in.76+77+If you see something like this error::78+79+ 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.85+86+You are dealing with an environment where Python thinks you are87+restricted to ASCII data. The solution to these problems is different88+depending on which locale your computer is running in.89+90+For instance, if you have a German Linux machine, you can fix the91+problem by exporting the locale to ``de_DE.utf-8``::92+93+ export LC_ALL=de_DE.utf-894+ export LANG=de_DE.utf-895+96+If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.97+On some newer Linux systems, you could also try ``C.UTF-8`` as the98+locale::99+100+ export LC_ALL=C.UTF-8101+ export LANG=C.UTF-8102+103+On some systems it was reported that ``UTF-8`` has to be written as104+``UTF8`` and vice versa. To see which locales are supported you can105+invoke ``locale -a``.106+107+You need to export the values before you invoke your Python script.108+109+In Python 3.7 and later you will no longer get a ``RuntimeError`` in110+many cases thanks to :pep:`538` and :pep:`540`, which changed the111+default assumption in unconfigured environments. This doesn't change the112+general issue that your locale may be misconfigured.modified:docs/utils.rst+17 added-28 removed
11 unmodified lines12 ------------------13 14 The most obvious helper is the :func:`echo` function, which in many ways15 works like the Python ``print`` statement or function. The main difference is16-that it works the same in Python 2 and 3, it intelligently detects17-misconfigured output streams, and it will never fail (except in Python 3; for18-more information see :ref:`python3-limitations`).16+that it works the same in many different terminal environments.17 18 Example::19 20 import click21 22 click.echo('Hello World!')23 26-Most importantly, it can print both Unicode and binary data, unlike the27-built-in ``print`` function in Python 3, which cannot output any bytes. It28-will, however, emit a trailing newline by default, which needs to be29-suppressed by passing ``nl=False``::24+It can output both text and binary data. It will emit a trailing newline25+by default, which needs to be suppressed by passing ``nl=False``::26 27 click.echo(b'\xe2\x98\x83', nl=False)28 29 Last but not least :func:`echo` uses click's intelligent internal output30 streams to stdout and stderr which support unicode output on the Windows31 console. This means for as long as you are using `click.echo` you can32 output unicode characters (there are some limitations on the default font37-with regards to which characters can be displayed). This functionality is38-new in Click 6.0.33+with regards to which characters can be displayed).34 35 .. versionadded:: 6.036 42-Click now emulates output streams on Windows to support unicode to the37+Click emulates output streams on Windows to support unicode to the38 Windows console through separate APIs. For more information see39 :doc:`wincmd`.40 41 .. versionadded:: 3.042 48-Starting with Click 3.0 you can also easily print to standard error by49-passing ``err=True``::43+You can also easily print to standard error by passing ``err=True``::44 45 click.echo('Hello World!', err=True)46 47 3 unmodified lines51 -----------52 53 .. versionadded:: 2.054 61-Starting with Click 2.0, the :func:`echo` function gained extra62-functionality to deal with ANSI colors and styles. Note that on Windows,63-this functionality is only available if `colorama`_ is installed. If it64-is installed, then ANSI codes are intelligently handled. Note that in Python65-2, the echo function doesn't parse color code information from bytearrays.55+The :func:`echo` function gained extra functionality to deal with ANSI56+colors and styles. Note that on Windows, this functionality is only57+available if `colorama`_ is installed. If it is installed, then ANSI58+codes are intelligently handled.59 60 Primarily this means that:61 62 - Click's :func:`echo` function will automatically strip ANSI color codes41 unmodified lines104 .. click:example::105 106 @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)))109 110 If 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:111 112 .. click:example::113 def _generate_output():114 for idx in range(50000):123- yield "Line %d\n" % idx115+ yield f"Line {idx}\n"116 117 @click.command()118 def less():119 click.echo_via_pager(_generate_output())124 unmodified lines244 Printing Filenames245 ------------------246 247 Because filenames might not be Unicode, formatting them can be a bit256-tricky. Generally, this is easier in Python 2 than on 3, as you can just257-write the bytes to stdout with the ``print`` function, but in Python 3, you258-will always need to operate in Unicode.248+tricky.249 250 The way this works with click is through the :func:`format_filename`251 function. It does a best-effort conversion of the filename to Unicode and252 will never fail. This makes it possible to use these filenames in the253 context of a full Unicode string.254 255 Example::256 267- click.echo('Path: %s' % click.format_filename(b'foo.txt'))257+ click.echo(f"Path: {click.format_filename(b'foo.txt')}")258 259 260 Standard Streams261 ----------------8 unmodified lines270 :func:`get_text_stream` functions, which produce consistent results with271 different Python versions and for a wide variety of terminal configurations.272 273 The end result is that these functions will always return a functional284-stream object (except in very odd cases in Python 3; see285-:ref:`python3-limitations`).274+stream object (except in very odd cases; see :doc:`/unicode-support`).275 276 Example::277 278 import click58 unmodified lines337 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 rv343 344 345 Showing Progress Bars38 unmodified lines384 import time385 386 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)390 391 Another useful feature is to associate a label with the progress bar which392 will be shown preceding the progress bar::17 unmodified linesmodified:docs/why.rst-1 removed
10 unmodified lines11 * 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 linesmodified:docs/wincmd.rst+1 added-17 removed
1 unmodified line2 =====================3 4 .. versionadded:: 6.05 6-Until Click 6.0 there are various bugs and limitations with using Click on7-a Windows console. Most notably the decoding of command line arguments8-was performed with the wrong encoding on Python 2 and on all versions of9-Python output of unicode characters was impossible. Starting with Click10-6.0 we now emulate output streams on Windows to support unicode to the6+Click emulates output streams on Windows to support unicode to the7 Windows console through separate APIs and we perform different decoding of8 parameters.9 10 Here is a brief overview of how this works and what it means to you.6 unmodified lines17 performed to the type expected value as late as possible. This has some18 advantages as it allows us to accept the data in the most appropriate form19 for the operating system and Python version.20 25-For instance paths are left as bytes on Python 2 unless you explicitly26-tell it otherwise.27-21 This caused some problems on Windows where initially the wrong encoding22 was used and garbage ended up in your input data. We not only fixed the23 encoding part, but we also now extract unicode parameters from `sys.argv`.24 32-This means that on Python 2 under Windows, the arguments processed will33-*most likely* be of unicode nature and not bytes. This was something that34-previously did not really happen unless you explicitly passed in unicode35-parameters so your custom types need to be aware of this.36-25 There is also another limitation with this: if `sys.argv` was modified26 prior to invoking a click handler, we have to fall back to the regular27 byte input in which case not all unicode values are available but only a28 subset of the codepage used for parameters.13 unmodified lines42 stream will also use ``utf-16-le`` as internal encoding. However there is43 some hackery going on that the underlying raw IO buffer is still bypassing44 the unicode APIs and byte output through an indirection is still possible.45 58-This hackery is used on both Python 2 and Python 3 as neither version of59-Python has native support for cmd.exe with unicode characters. There are60-some limitations you need to be aware of:61-46 * 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 some15 unmodified linesmodified:examples/aliases/aliases.py+5 added-9 removed
1+import configparser2 import os3 4 import click5 5-try:6- import configparser7-except ImportError:8- import ConfigParser as configparser6 10-11-class Config(object):7+class Config:8 """The config in this example only holds aliases."""9 10 def __init__(self):11 self.path = os.getcwd()52 unmodified lines64 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))}")69 70 71 def read_config(ctx, param, value):72 """Callback that is used whenever --config is passed. We use this to47 unmodified lines120 @cli.command()121 @pass_config122 def status(config):123 """Shows the status."""128- click.echo("Status for {}".format(config.path))124+ click.echo(f"Status for {config.path}")125 126 127 @cli.command()128 @pass_config5 unmodified lines134 def 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 lines17 18 @cli.command(help="A command to print environment variables")19 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20 def 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]}")23 24 25 @click.group(help="A group that holds a subcommand")26 def group():11 unmodified lines38 39 @group.command(help="Choose a user")40 @click.argument("user", type=click.STRING, autocompletion=list_users)41 def subcmd(user):42- click.echo("Chosen user is {}".format(user))42+ click.echo(f"Chosen user is {user}")43 44 45 cli.add_command(group)modified:examples/colors/colors.py+3 added-7 removed
28 unmodified lines29 30 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))38 39 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 lines9 def 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 lines6 7 CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX")8 9 10-class Environment(object):10+class Environment:11 def __init__(self):12 self.verbose = False13 self.home = os.getcwd()14 23 unmodified lines38 return rv39 40 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 linesmodified:examples/imagepipe/imagepipe.py+21 added-27 removed
58 unmodified lines59 """60 61 @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)65 66 return update_wrapper(new_func, f)67 68 17 unmodified lines86 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)99 100 101 @cli.command("save")102 @click.option(8 unmodified lines111 """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)119 120 121 @cli.command("display")122 @processor123 def 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 image129 130 6 unmodified lines137 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 image144 145 9 unmodified lines155 156 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 lines171 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}'")176 177 178 def convert_flip(ctx, param, value):179 if value is None:2 unmodified lines182 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}'")187 188 189 @cli.command("transpose")190 @click.option(5 unmodified lines196 """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 image207 208 3 unmodified lines212 def 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)218 219 220 @cli.command("smoothen")8 unmodified lines229 def 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 image3 unmodified lines242 @processor243 def 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)248 249 250 @cli.command("sharpen")3 unmodified lines254 @processor255 def 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)261 262 13 unmodified lines276 if image is not None:277 yield image278 return279 285- 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 image287 293- for image in imageiter:294- yield image288+ yield from imageitermodified:examples/naval/naval.py+5 added-5 removed
19 unmodified lines20 @ship.command("new")21 @click.argument("name")22 def ship_new(name):23 """Creates a new ship."""24- click.echo("Created ship {}".format(name))24+ click.echo(f"Created ship {name}")25 26 27 @ship.command("move")28 @click.argument("ship")1 unmodified line30 @click.argument("y", type=float)31 @click.option("--speed", metavar="KN", default=10, help="Speed in knots.")32 def 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}")35 36 37 @ship.command("shoot")38 @click.argument("ship")39 @click.argument("x", type=float)40 @click.argument("y", type=float)41 def 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}")44 45 46 @cli.group("mine")47 def mine():12 unmodified lines60 )61 @click.option("ty", "--drifting", flag_value="drifting", help="Drifting mine.")62 def 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}")65 66 67 @mine.command("remove")68 @click.argument("x", type=float)69 @click.argument("y", type=float)70 def 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 lines4 5 import click6 7 8-class Repo(object):8+class Repo:9 def __init__(self, home):10 self.home = home11 self.config = {}12 self.verbose = False13 14 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)18 19 def __repr__(self):20- return "<Repo {}>".format(self.home)20+ return f"<Repo {self.home}>"21 22 23 pass_repo = click.make_pass_decorator(Repo)24 52 unmodified lines77 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}")86 87 88 @cli.command()89 @click.confirmation_option()2 unmodified lines92 """Deletes a repository.93 94 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!")98 99 100 @cli.command()34 unmodified lines135 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 return2 unmodified lines146 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}")152 153 154 @cli.command(short_help="Copies files.")155 @click.option(6 unmodified lines162 """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-81 import math2 import random3 import time4 9 unmodified lines14 @cli.command()15 def 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))20 21 22 @cli.command()23 def 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))29 30 31 @cli.command()22 unmodified lines54 process_slowly(item)55 56 def show_item(item):57 if item is not None:59- return "Item #{}".format(item)58+ return f"Item #{item}"59 60 with click.progressbar(61 filter(items),62 label="Committing transaction",6 unmodified lines69 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 lines92 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 lines117 @cli.command()118 def 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!")130 131 38 unmodified linesmodified:examples/validation/validation.py+6 added-10 removed
1+from urllib import parse as urlparse2+3 import click4 3-try:4- from urllib import parse as urlparse5-except ImportError:6- import urlparse5 8-6 def 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 value6 unmodified lines16 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 value17 unmodified lines42 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 lines71 from .utils import get_os_args72 from .utils import get_text_stream73 from .utils import open_file74 75-# Controls if click should emit the warning about the use of unicode76-# literals.77-disable_unicode_literals_warning = False78-79-__version__ = "8.0.dev"75+__version__ = "8.0.0.dev"modified:src/click/_bashcomplete.py+3 added-7 removed
1 import copy2 import os3 import re4+from collections import abc5 6 from .core import Argument7 from .core import MultiCommand8 from .core import Option9 from .parser import split_arg_string10 from .types import Choice11 from .utils import echo12 12-try:13- from collections import abc14-except ImportError:15- import collections as abc16-13 WORDBREAK = "="14 15 # Note, only BASH version 4.4 and later have the nosort option.16 COMPLETION_SCRIPT_BASH = """76 unmodified lines93 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 lines344 args = cwords[1:]345 346 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])351 352 return True19 unmodified linesmodified:src/click/_compat.py+172 added-351 removed
1-# flake8: noqa1 import codecs2 import io3 import os4 import re5 import sys6 from weakref import WeakKeyDictionary7 9-PY2 = sys.version_info[0] == 28 CYGWIN = sys.platform.startswith("cygwin")9 MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)10 # Determine local App Engine environment, per Google's own suggestion11 APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(12 "SERVER_SOFTWARE", ""13 )14 WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS215 DEFAULT_COLUMNS = 8018-19-16+auto_wrap_for_ansi = None17+colorama = None18+get_winterm_size = None19 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")20 21 22 def get_filesystem_encoding():40 unmodified lines63 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)71 73- # 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:77-78- 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)86-87- def writelines(self, lines):88- for line in lines:89- self.write(line)90-72 def __del__(self):73 try:74 self.detach()75 except Exception:3 unmodified lines79 # https://bitbucket.org/pypy/pypy/issue/180380 return self._stream.isatty()81 82 102-class _FixupStream(object):83+class _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 lines101 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)105+106 return self._stream.read(size)107 108 def readable(self):109 if self._force_readable:32 unmodified lines142 return False143 return True144 145 169-if 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 = xrange146+def is_bytes(x):147+ return isinstance(x, (bytes, memoryview, bytearray))148 177- from pipes import quote as shlex_quote149 179- def is_bytes(x):180- return isinstance(x, (buffer, bytearray))181-182- _identifier_re = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")183-184- # 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 f204-150+def _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.157 211- 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 f158 159+def _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 True170 226- 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 f171 236- def isidentifier(x):237- return _identifier_re.search(x) is not None172+def _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 stream179 239- def get_binary_stdin():240- return set_binary_mode(sys.stdin)180+ buf = getattr(stream, "buffer", None)181 242- 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 buf186 246- def get_binary_stderr():247- _wrap_std_stream("stderr")248- return set_binary_mode(sys.stderr)187 250- 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)188+def _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 stream195 256- 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)197 263- 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 buf202 270- def filename_to_ui(value):271- if isinstance(value, bytes):272- value = value.decode(get_filesystem_encoding(), "replace")273- return value203 204+def _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")211 276-else:277- import io212 279- 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())213+def _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)220 287- from shlex import quote as shlex_quote221 289- def is_bytes(x):290- return isinstance(x, (bytes, memoryview, bytearray))222+def _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)229 292- 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.230 300- 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 True231+def _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_stream249 312- 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)252 320- 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_stream257 322- # 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"262 327- 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+ )272 335- buf = getattr(stream, "buffer", None)273 337- # 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 buf274+def _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+ )283 342- 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")284 350- 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)357-358- 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)365-366- def _force_correct_text_stream(367- text_stream,285+def _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+ )294 385- # Otherwise, get the underlying binary reader.386- binary_reader = find_binary(text_stream)295 388- # 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_stream296+def 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 reader301 393- # Default errors to replace instead of strict in order to get394- # something that works.395- if errors is None:396- errors = "replace"302 398- # 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- )303+def 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 writer308 408- 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- )309 418- 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- )310+def 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 writer315 428- 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 reader316 434- 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 writer317+def 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)322 442- 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 writer323 450- 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- )324+def 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)329 458- 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- )330 466- 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- )331+def 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)336 474- 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 value337 338+def 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 value344 345+482-def get_streerror(e, default=None):346+def get_strerror(e, default=None):347 if hasattr(e, "strerror"):348 msg = e.strerror349 else:350 if default is not None:5 unmodified lines356 return msg357 358 359 def _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)363 501- Also handles not passing ``encoding`` and ``errors`` in binary mode.502- """503- binary = "b" in mode364+ return open(file, mode, encoding=encoding, errors=errors)365 505- if binary:506- kwargs = {}507- else:508- kwargs = {"encoding": encoding, "errors": errors}366 510- if not PY2 or binary:511- return io.open(file, mode, **kwargs)512-513- f = io.open(file, "{}b".format(mode.replace("t", "")))514- return _make_text_stream(f, **kwargs)515-516-367 def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):368 binary = "b" in mode369 370 # Standard streams first. These are simple because they don't need43 unmodified lines414 415 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 break13 unmodified lines436 f = _wrap_io_open(fd, mode, encoding, errors)437 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True438 439 590-# Used in a destructor call, needs extra protection from interpreter cleanup.591-if hasattr(os, "replace"):592- _replace = os.replace593- _can_replace = True594-else:595- _replace = os.rename596- _can_replace = not WIN597-598-599-class _AtomicFile(object):440+class _AtomicFile:441 def __init__(self, f, tmp_filename, real_filename):442 self._f = f443 self._tmp_filename = tmp_filename444 self._real_filename = real_filename6 unmodified lines451 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 = True457 458 def __getattr__(self, name):459 return getattr(self._f, name)7 unmodified lines467 def __repr__(self):468 return repr(self._f)469 470 635-auto_wrap_for_ansi = None636-colorama = None637-get_winterm_size = None638-639-471 def strip_ansi(value):472 return _ansi_re.sub("", value)473 474 23 unmodified lines498 if WIN:499 # Windows has a smaller terminal500 DEFAULT_COLUMNS = 79501 671- from ._winconsole import _get_windows_console_stream, _wrap_std_stream502+ from ._winconsole import _get_windows_console_stream503 504 def _get_argv_encoding():505 import locale506 507 return locale.getpreferredencoding()508 678- if PY2:679-680- 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")687-509 try:510 import colorama511 except ImportError:512 pass19 unmodified lines532 533 def _safe_write(s):534 try:535 return _write(s)715- except:536+ except BaseException:537 ansi_wrapper.reset_all()538 raise539 540 rv.write = _safe_write14 unmodified lines555 556 def _get_argv_encoding():557 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()558 738- _get_windows_console_stream = lambda *x: None739- _wrap_std_stream = lambda *x: None559+ def _get_windows_console_stream(f, encoding, errors):560+ return None561 562 563 def term_len(x):564 return len(strip_ansi(x))47 unmodified linesmodified:src/click/_termui_impl.py+26 added-36 removed
1-# -*- coding: utf-8 -*-1 """2 This module contains implementations for the termui module. To keep the3 import time of Click down, some infrequently used functionality is4 placed in this module and only imported as needed.5 """6 import contextlib7 import math8 import os9+import shlex10 import sys11 import time12 13 from ._compat import _default_text_stdout14 from ._compat import CYGWIN15 from ._compat import get_best_encoding16-from ._compat import int_types16 from ._compat import isatty17 from ._compat import open_stream19-from ._compat import range_type20-from ._compat import shlex_quote18 from ._compat import strip_ansi19 from ._compat import term_len20 from ._compat import WIN21 from .exceptions import ClickException19 unmodified lines41 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 hint48 49 53-class ProgressBar(object):50+class ProgressBar:51 def __init__(52 self,53 iterable,54 length=None,30 unmodified lines85 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 = 029 unmodified lines123 # so it is re-entry safe. Calling `next(self.generator())`124 # twice works and does "what you want".125 return next(iter(self))126 130- # Python 2 compat131- next = __next__132-127 def is_fast(self):128 return time.time() - self.start <= self.short_limit129 130 def render_finish(self):29 unmodified lines160 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 ""168 169 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 pos174 175 def format_pct(self):182- return "{: 4}%".format(int(self.pct * 100))[1:]176+ return f"{int(self.pct * 100): 4}%"[1:]177 178 def format_bar(self):179 if self.length_known:180 bar_length = int(self.pct * self.width)138 unmodified lines319 if not self.entered:320 raise RuntimeError("You need to use progress bars in a with block.")321 322 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 rv23 unmodified lines351 352 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 lines370 # 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 lines385 if not color:386 text = strip_ansi(text)387 388 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 lines420 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)427 428 4 unmodified lines433 text = strip_ansi(text)434 stream.write(text)435 436 447-class Editor(object):437+class 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_save8 unmodified lines450 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"457 458 def edit_file(self, filename):6 unmodified lines465 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}")478 479 def edit(self, text):480 import tempfile481 60 unmodified lines542 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)557 558 try:559 if locate:13 unmodified lines573 return 1574 575 576 def _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()583 584 585 if WIN:38 unmodified lines624 else:625 func = msvcrt.getwch626 627 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 linesmodified:src/click/_textwrap.py+1 added-1 removed
31 unmodified lines32 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
1 import codecs2 import os3-import sys3 5-from ._compat import PY24 7-8-def _find_unicode_literals_frame():9- import __future__10-11- 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 024-25-26-def _check_for_unicode_literals():27- if not __debug__:28- return29-30- from . import disable_unicode_literals_warning31-32- 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 warn38-39- 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- )50-51-52-def _verify_python3_env():53- """Ensures that the environment is good for unicode on Python 3."""5+def _verify_python_env():6+ """Ensures that the environment is good for Unicode."""54- if PY2:55- return7 try:8 import locale9 10 fs_enc = codecs.lookup(locale.getpreferredencoding()).name43 unmodified lines54 " 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 )62 63 bad_locale = None64 for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):5 unmodified lines70 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 )76 77 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 lines7 # the entire interpreter but just work in our little world of8 # echo and prompt.9 import ctypes10 import io12-import os13-import sys11 import time15-import zlib12 from ctypes import byref13 from ctypes import c_char14 from ctypes import c_char_p15 from ctypes import c_int2 unmodified lines18 from ctypes import c_void_p19 from ctypes import POINTER20 from ctypes import py_object21 from ctypes import windll26-from ctypes import WinError22 from ctypes import WINFUNCTYPE23 from ctypes.wintypes import DWORD24 from ctypes.wintypes import HANDLE25 from ctypes.wintypes import LPCWSTR1 unmodified line27 28 import msvcrt29 30 from ._compat import _NonClosingTextIOWrapper36-from ._compat import PY237-from ._compat import text_type31 32 try:33 from ctypes import pythonapi41-42- PyObject_GetBuffer = pythonapi.PyObject_GetBuffer43- PyBuffer_Release = pythonapi.PyBuffer_Release34 except ImportError:35 pythonapi = None36+else:37+ PyObject_GetBuffer = pythonapi.PyObject_GetBuffer38+ PyBuffer_Release = pythonapi.PyBuffer_Release39 40 41 c_ssize_p = POINTER(c_ssize_t)42 46 unmodified lines89 ("suboffsets", c_ssize_p),90 ("internal", c_void_p),91 ]92 100- if PY2:101- _fields_.insert(-1, ("smalltable", c_ssize_t * 2))93 103-94 # On PyPy we cannot get buffers so our ability to operate here is95 # severely limited.96 if pythonapi is None:97 get_buffer = None46 unmodified lines144 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()}")149 150 if buffer[0] == EOF:151 return 0152 return 2 * code_units_read.value8 unmodified lines161 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}"166 167 def write(self, b):168 bytes_to_be_written = len(b)169 buf = get_buffer(b)13 unmodified lines183 raise OSError(self._get_error_message(GetLastError()))184 return bytes_written185 186 197-class ConsoleStream(object):187+class ConsoleStream:188 def __init__(self, text_stream, byte_stream):189 self._text_stream = text_stream190 self.buffer = byte_stream191 1 unmodified line193 def name(self):194 return self.buffer.name195 196 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 lines212 def isatty(self):213 return self.buffer.isatty()214 215 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}>"217 218 231-class WindowsChunkedWriter(object):219+class 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 lines240 self.__wrapped.write(text[written : written + to_write])241 written += to_write242 243 256-_wrapped_std_streams = set()257-258-259-def _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)268-269-244 def _get_text_stdin(buffer_stream):245 text_stream = _NonClosingTextIOWrapper(246 io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),247 "utf-16-le",22 unmodified lines270 )271 return ConsoleStream(text_stream, buffer_stream)272 273 300-if PY2:301-302- def _hash_py_argv():303- return zlib.crc32("\x00".join(sys.argv[1:]))304-305- _initial_argv_hash = _hash_py_argv()306-307- 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_unicode317-318- 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- break327-328- return argv[1:]329-330-274 _stream_factories = {275 0: _get_text_stdin,276 1: _get_text_stdout,277 2: _get_text_stderr,15 unmodified lines293 294 def _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)304+305+ if f is None:306+ return None307+308 return func(f)modified:src/click/core.py+58 added-93 removed
4 unmodified lines5 from contextlib import contextmanager6 from functools import update_wrapper7 from itertools import repeat8 9-from ._compat import isidentifier10-from ._compat import iteritems11-from ._compat import PY212-from ._compat import string_types13-from ._unicodefun import _check_for_unicode_literals14-from ._unicodefun import _verify_python3_env9+from ._unicodefun import _verify_python_env10 from .exceptions import Abort11 from .exceptions import BadParameter12 from .exceptions import ClickException13 from .exceptions import Exit11 unmodified lines25 from .types import BOOL26 from .types import convert_type27 from .types import IntRange28 from .utils import echo34-from .utils import get_os_args29 from .utils import make_default_short_help30 from .utils import make_str31 from .utils import PacifyFlushWrapper32 2 unmodified lines35 SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."36 SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."37 38 DEPRECATED_HELP_NOTICE = " (DEPRECATED)"45-DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command %(name)s is deprecated."39+DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command {name} is deprecated."40 41 42 def _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)45 46 47 def fast_exit(code):48 """Exit without garbage collection, this speeds up exit by about 10ms for6 unmodified lines55 56 def _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 lines80 "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 )90 91 92 def batch(iterable, batch_size):93 return list(zip(*repeat(iter(iterable), batch_size)))94 95 108-def invoke_param_callback(callback, ctx, param, value):109- code = getattr(callback, "__code__", None)110- args = getattr(code, "co_argcount", 3)111-112- if args < 3:113- from warnings import warn114-115- 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)122-123- return callback(ctx, param, value)124-125-96 @contextmanager97 def augment_usage_errors(ctx, param=None):98 """Context manager that attaches extra information to exceptions."""99 try:25 unmodified lines125 126 return sorted(declaration_order, key=sort_key)127 128 159-class ParameterSource(object):129+class ParameterSource:130 """This is an enum that indicates the source of a command line parameter.131 132 The enum has one of the following values: COMMANDLINE,133 ENVIRONMENT, DEFAULT, DEFAULT_MAP. The DEFAULT indicates that the18 unmodified lines152 :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 )159 160 191-class Context(object):161+class 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 lines374 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 lines506 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()512 513 def find_root(self):514 """Finds the outermost context."""144 unmodified lines659 """660 return self._source_by_paramname[name]661 662 693-class BaseCommand(object):663+class 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 lines700 #: an optional dictionary with defaults passed to the context.701 self.context_settings = context_settings702 703 def __repr__(self):734- return "<{} {}>".format(self.__class__.__name__, self.name)704+ return f"<{self.__class__.__name__} {self.name}>"705 706 def get_usage(self, ctx):707 raise NotImplementedError("Base commands cannot get usage")708 14 unmodified lines723 :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 lines750 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 lines784 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()791 792 if args is None:827- args = get_os_args()793+ args = sys.argv[1:]794 else:795 args = list(args)796 797 if prog_name is None:27 unmodified lines825 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 lines928 self.hidden = hidden929 self.deprecated = deprecated930 931 def __repr__(self):966- return "<{} {}>".format(self.__class__.__name__, self.name)932+ return f"<{self.__class__.__name__} {self.name}>"933 934 def get_usage(self, ctx):935 """Formats the usage line into a string and returns it.936 144 unmodified lines1081 value, args = param.handle_parse_result(ctx, opts, args)1082 1083 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 )1089 1090 ctx.args = args1091 return args41 unmodified lines1133 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_command201 unmodified lines1343 # 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}'.")1348 1349 return cmd_name, cmd, args[1:]1350 1351 def get_command(self, ctx, cmd_name):98 unmodified lines1450 rv.update(source.list_commands(ctx))1451 return sorted(rv)1452 1453 1488-class Parameter(object):1454+class 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 lines1538 self.envvar = envvar1539 self.autocompletion = autocompletion1540 1541 def __repr__(self):1576- return "<{} {}>".format(self.__class__.__name__, self.name)1542+ return f"<{self.__class__.__name__} {self.name}>"1543 1544 @property1545 def human_readable_name(self):1546 """Returns the human readable name of this parameter. This is the44 unmodified lines1591 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 lines1667 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 lines1748 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 lines1824 name = None1825 possible_names = []1826 1827 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 lines1846 1847 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 = None1852 1853 if name is None:1854 if not expose_value:1 unmodified line1856 raise TypeError("Could not determine name for option")1857 1858 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 )1864 1865 return name, opts, secondary_opts1866 12 unmodified lines1879 action = "store"1880 1881 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, **kwargs15 unmodified lines1903 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 rv1909 1910 rv = [_write_opts(self.opts)]1911 if self.secondary_opts:4 unmodified lines1916 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}")1938 1939 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}]"1944 1945 return ("; " if any_prefix_is_slash else " / ").join(rv), help1946 1947 def get_default(self, ctx):36 unmodified lines1984 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)1990 1991 def value_from_envvar(self, ctx):1992 rv = self.resolve_envvar_value(ctx)46 unmodified lines2039 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 lines2055 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], []2062 2063 def get_usage_pieces(self, ctx):7 unmodified linesmodified:src/click/decorators.py+4 added-6 removed
1 import inspect2 import sys3 from functools import update_wrapper4 5-from ._compat import iteritems6-from ._unicodefun import _check_for_unicode_literals5 from .core import Argument6 from .core import Command7 from .core import Group8 from .core import Option56 unmodified lines65 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)73 74 return update_wrapper(new_func, f)17 unmodified lines92 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 )102 103 104 def command(name=None, cls=None, **attrs):179 unmodified lines284 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 linesmodified:src/click/exceptions.py+18 added-38 removed
1 from ._compat import filename_to_ui2 from ._compat import get_text_stderr3-from ._compat import PY23 from .utils import echo4 5 6 def _join_param_hints(param_hint):4 unmodified lines11 12 class ClickException(Exception):13 """An exception that Click can handle and show to the user."""14 16- #: The exit code for this exception15+ #: The exit code for this exception.16 exit_code = 117 18 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 = message21 22 def format_message(self):23 return self.message24 25 def __str__(self):26 return self.message27 33- if PY2:34- __unicode__ = __str__35-36- def __str__(self):37- return self.message.encode("utf-8")38-28 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)32 33 34 class UsageError(ClickException):35 """An internal exception that signals a usage error. This typically16 unmodified lines52 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)64 65 66 class BadParameter(UsageError):67 """An exception that formats out a standardized error message for a23 unmodified lines91 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)97 108- return "Invalid value for {}: {}".format(param_hint, self.message)98+ return f"Invalid value for {param_hint}: {self.message}"99 100 101 class MissingParameter(BadParameter):102 """Raised if click required an option or argument but it was not30 unmodified lines133 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_extra140 151- 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 ''}"143 144 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.message150 165- if PY2:166- __unicode__ = __str__151 168- def __str__(self):169- return self.__unicode__().encode("utf-8")170-171-152 class NoSuchOption(UsageError):153 """Raised if click attempted to handle an option that does not154 exist.155 1 unmodified line157 """158 159 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 = possibilities165 166 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)175 176 177 class BadOptionUsage(UsageError):34 unmodified lines212 self.ui_filename = ui_filename213 self.filename = filename214 215 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}"217 218 219 class Abort(RuntimeError):220 """An internal signalling exception that signals Click to abort."""13 unmodified linesmodified:src/click/formatting.py+6 added-10 removed
89 unmodified lines90 91 return "\n\n".join(rv)92 93 94-class HelpFormatter(object):94+class 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 lines133 :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_indent139 140 if text_width >= (term_len(usage_prefix) + 20):141 # The arguments will fit to the right of the prefix.20 unmodified lines162 self.write("\n")163 164 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")167 168 def write_paragraph(self):169 """Writes a paragraph into the buffer."""170 if self.buffer:32 unmodified lines203 204 first_col = min(widths[0], col_max) + col_spacing205 206 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 lines218 wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)219 lines = wrapped_text.splitlines()220 221 if lines:222- self.write("{}\n".format(lines[0]))222+ self.write(f"{lines[0]}\n")223 224 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")226 227 if len(lines) > 1:228 # separate long help from next option229 self.write("\n")50 unmodified linesmodified:src/click/parser.py+13 added-14 removed
1-# -*- coding: utf-8 -*-1 """2 This module started out as largely a copy paste from the stdlib's3 optparse module with the features removed that we do not need from4 optparse because we implement them in Click on a higher level (for77 unmodified lines82 83 84 def _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")88 89 90 def split_opt(opt):91 first = opt[:1]7 unmodified lines99 def 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)}"104 105 106 def split_arg_string(string):107 """Given an argument string this attempts to split it into small parts."""13 unmodified lines121 rv.append(arg)122 return rv123 124 126-class Option(object):125+class 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()130 131 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 lines163 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)169 170 172-class Argument(object):171+class Argument:172 def __init__(self, dest, nargs=1, obj=None):173 self.dest = dest174 self.nargs = nargs175 self.obj = obj4 unmodified lines180 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)188 189 191-class ParsingState(object):190+class ParsingState:191 def __init__(self, rargs):192 self.opts = {}193 self.largs = []194 self.rargs = rargs195 self.order = []196 197 199-class OptionParser(object):198+class 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 lines346 value = tuple(state.rargs[:nargs])347 del state.rargs[:nargs]348 349 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")351 352 else:353 value = None354 5 unmodified lines360 prefix = arg[0]361 unknown_options = []362 363 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 += 1367 368 if not option:29 unmodified lines398 # 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)}")403 404 def _process_opts(self, arg, state):405 explicit_value = None406 # Long option handling happens in two parts. The first part is25 unmodified linesmodified:src/click/termui.py+19 added-26 removed
6 unmodified lines7 8 from ._compat import DEFAULT_COLUMNS9 from ._compat import get_winterm_size10 from ._compat import isatty11-from ._compat import raw_input12-from ._compat import string_types11 from ._compat import strip_ansi14-from ._compat import text_type12 from ._compat import WIN13 from .exceptions import Abort14 from .exceptions import UsageError15 from .globals import resolve_color_default4 unmodified lines20 from .utils import LazyFile21 22 # The prompt functions to use. The doc tools currently override these23 # functions to customize how they work.27-visible_prompt_func = raw_input24+visible_prompt_func = input25 26 _ansi_colors = {27 "black": 30,28 "red": 31,26 unmodified lines55 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}"63 64 65 def _format_default(default):66 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):85 unmodified lines152 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 lines215 def 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 shutil220 226- 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()223 224 # 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 lines270 color = resolve_color_default(color)271 272 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)278 279 # 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)281 282 from ._termui_impl import pager283 284 return pager(itertools.chain(text_generator, "\n"), color)216 unmodified lines501 """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 linesmodified:src/click/testing.py+30 added-50 removed
1 import contextlib2+import io3 import os4 import shlex5 import shutil6 import sys1 unmodified line8 9 from . import formatting10 from . import termui11 from . import utils11-from ._compat import iteritems12-from ._compat import PY213-from ._compat import string_types12+from ._compat import _find_binary_reader13 14 16-if PY2:17- from cStringIO import StringIO18-else:19- import io20- from ._compat import _find_binary_reader21-22-23-class EchoingStdin(object):15+class EchoingStdin:16 def __init__(self, input, output):17 self._input = input18 self._output = output19 22 unmodified lines42 43 def 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)47+48 if rv is not None:49 return rv50+51 raise TypeError("Could not find binary reader for input stream.")52 53 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)57+58 return io.BytesIO(input)59 60 70-class Result(object):61+class Result:62 """Holds the captured result of an invoked CLI script."""63 64 def __init__(65 self, runner, stdout_bytes, stderr_bytes, exit_code, exception, exc_info=None32 unmodified lines98 "\r\n", "\n"99 )100 101 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}>"104 105 116-class CliRunner(object):106+class 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.111 122- :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 prompts4 unmodified lines121 noisy stderr, such that each may be measured122 independently123 """124 137- 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_stderr39 unmodified lines169 formatting.FORCED_WIDTH = 80170 171 env = self.make_env(env)172 187- 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)174 175+ if self.echo_stdin:176+ input = EchoingStdin(input, bytes_output)177+178+ input = io.TextIOWrapper(input, encoding=self.charset)179+ sys.stdout = io.TextIOWrapper(bytes_output, encoding=self.charset)180+181+ if not self.mix_stderr:182+ bytes_error = io.BytesIO()183+ sys.stderr = io.TextIOWrapper(bytes_error, encoding=self.charset)184+185 if self.mix_stderr:186 sys.stderr = sys.stdout187 188 sys.stdin = input189 190 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 val196 197 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")201 202 def _getchar(echo):20 unmodified lines223 utils.should_strip_ansi = should_strip_ansi224 225 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 lines234 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 lines259 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 of28 unmodified lines296 with self.isolation(input=input, env=env, color=color) as outstreams:297 exception = None298 exit_code = 0299 320- if isinstance(args, string_types):300+ if isinstance(args, str):301 args = shlex.split(args)302 303 try:304 prog_name = extra.pop("prog_name")52 unmodified lines357 finally:358 os.chdir(cwd)359 try:360 shutil.rmtree(t)381- except (OSError, IOError): # noqa: B014361+ except OSError: # noqa: B014362 passmodified:src/click/types.py+41 added-77 removed
3 unmodified lines4 5 from ._compat import _get_argv_encoding6 from ._compat import filename_to_ui7 from ._compat import get_filesystem_encoding8-from ._compat import get_streerror8+from ._compat import get_strerror9 from ._compat import open_stream10-from ._compat import PY211-from ._compat import text_type10 from .exceptions import BadParameter11 from .utils import LazyFile12 from .utils import safecall13 14 17-class ParamType(object):15+class ParamType:16 """Helper for converting values through types. The following is17 necessary for a valid type:18 19 * it needs a name71 unmodified lines91 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")98+99 self.fail(value, param, ctx)100 101 102 class UnprocessedParamType(ParamType):53 unmodified lines156 self.choices = choices157 self.case_sensitive = case_sensitive158 159 def get_metavar(self, param):161- return "[{}]".format("|".join(self.choices))160+ return f"[{'|'.join(self.choices)}]"161 162 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}"165 166 def convert(self, value, param, ctx):167 # Match through normalization and case sensitivity168 # first do token_normalize_func, then lowercase9 unmodified lines178 for normed_choice, original in normed_choices.items()179 }180 181 if not self.case_sensitive:182- if PY2:183- lower = str.lower184- else:185- lower = str.casefold186-187- 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 }187 188 if normed_value in normed_choices:189 return normed_choices[normed_value]190 191 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 )196 197 def __repr__(self):205- return "Choice('{}')".format(list(self.choices))198+ return f"Choice({list(self.choices)})"199 200 201 class DateTime(ParamType):202 """The DateTime type converts date strings into `datetime` objects.21 unmodified lines224 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"]226 227 def get_metavar(self, param):235- return "[{}]".format("|".join(self.formats))228+ return f"[{'|'.join(self.formats)}]"229 230 def _try_to_convert_date(self, value, format):231 try:232 return datetime.strptime(value, format)7 unmodified lines240 if dtime:241 return dtime242 243 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 )246 247 def __repr__(self):248 return "DateTime"5 unmodified lines254 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)259 260 def __repr__(self):261 return "INT"262 28 unmodified lines291 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 rv312 313 def __repr__(self):329- return "IntRange({}, {})".format(self.min, self.max)314+ return f"IntRange({self.min}, {self.max})"315 316 317 class FloatParamType(ParamType):318 name = "float"1 unmodified line320 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)325 326 def __repr__(self):327 return "FLOAT"328 28 unmodified lines357 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 rv378 379 def __repr__(self):403- return "FloatRange({}, {})".format(self.min, self.max)380+ return f"FloatRange({self.min}, {self.max})"381 382 383 class BoolParamType(ParamType):384 name = "boolean"5 unmodified lines390 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)395 396 def __repr__(self):397 return "BOOL"398 4 unmodified lines403 def convert(self, value, param, ctx):404 import uuid405 406 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)410 411 def __repr__(self):412 return "UUID"413 74 unmodified lines488 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 lines561 self.path_type = "Path"562 563 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 rv12 unmodified lines582 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 )590 591 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 lines634 self.types = [convert_type(ty) for ty in types]635 636 @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)}>"639 640 @property641 def arity(self):642 return len(self.types)22 unmodified lines665 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 for11 unmodified lines685 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)694 695 696 #: 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 linesmodified:src/click/utils.py+39 added-54 removed
1 unmodified line2 import sys3 4 from ._compat import _default_text_stderr5 from ._compat import _default_text_stdout6+from ._compat import _find_binary_writer7 from ._compat import auto_wrap_for_ansi8 from ._compat import binary_streams9 from ._compat import filename_to_ui10 from ._compat import get_filesystem_encoding10-from ._compat import get_streerror11+from ._compat import get_strerror12 from ._compat import is_bytes13 from ._compat import open_stream13-from ._compat import PY214 from ._compat import should_strip_ansi15-from ._compat import string_types15 from ._compat import strip_ansi16 from ._compat import text_streams18-from ._compat import text_type17 from ._compat import WIN18 from .globals import resolve_color_default19 22-if not PY2:23- from ._compat import _find_binary_writer24-elif WIN:25- from ._winconsole import _get_windows_argv26- from ._winconsole import _hash_py_argv27- from ._winconsole import _initial_argv_hash20 29-echo_native_types = string_types + (bytes, bytearray)21+echo_native_types = (str, bytes, bytearray)22 23 24 def _posixify(name):25 return "-".join(name.split()).lower()17 unmodified lines43 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)48 49 50 def make_default_short_help(help, max_length=45):51 """Return a condensed version of help string."""19 unmodified lines71 72 return "".join(result)73 74 83-class LazyFile(object):75+class 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 lines104 105 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}>"109 110 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 error4 unmodified lines117 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 FileError123 132- raise FileError(self.name, hint=get_streerror(e))124+ raise FileError(self.name, hint=get_strerror(e))125 self._f = rv126 return rv127 128 def close(self):18 unmodified lines147 self.open()148 return iter(self._f)149 150 159-class KeepOpenFile(object):151+class KeepOpenFile:152 def __init__(self, file):153 self._file = file154 155 def __getattr__(self, name):66 unmodified lines222 file = _default_text_stdout()223 224 # 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)227 228 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"234 243- # 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 lines264 file.flush()265 266 267 def 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.269 270 :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()277 278 279 def 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.284 285 :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)294 295 296 def open_file(29 unmodified lines326 return f327 328 329 def 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.332 348- 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.353-354- .. 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 warnings338+339+ 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:]346 347 348 def format_filename(filename, shorten=False):54 unmodified lines403 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 lines414 _posixify(app_name),415 )416 417 433-class PacifyFlushWrapper(object):418+class 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 any6 unmodified lines429 430 def flush(self):431 try:432 self.wrapped.flush()448- except IOError as e:433+ except OSError as e:434 import errno435 436 if e.errno != errno.EPIPE:437 raise3 unmodified linesmodified:tests/test_arguments.py+17 added-27 removed
1-# -*- coding: utf-8 -*-1 import sys2 3 import pytest4 5 import click7-from click._compat import PY28-from click._compat import text_type6 7 8 def 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}")15 16 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 lines31 @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}")38 39 result = runner.invoke(copy, ["peter", "1", "2"])40 assert not result.exception41 assert result.output.splitlines() == ["name=peter", "point=1/2"]11 unmodified lines53 54 @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}")59 60 result = runner.invoke(copy, ["peter", "1"])61 assert not result.exception62 assert result.output.splitlines() == ["name=peter id=1"]18 unmodified lines81 @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"87 88 # 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")92 93 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 )98 99 88 unmodified lines188 def 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)}")193 194 result = runner.invoke(cmd, [])195 assert result.exit_code == 0196 assert result.output == "arg:\n"197 198 @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)}")202 203 result = runner.invoke(cmd2, [])204 assert result.exit_code == 2205 assert "Missing argument 'ARG...'" in result.output2 unmodified lines208 def 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}")213 214 result = runner.invoke(cmd, [])215 assert result.exit_code == 2216 assert "Missing argument 'ARG'." in result.output44 unmodified lines261 for arg in (a, b, c):262 click.echo(arg)263 264 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"]266 267 268 def test_nargs_specified_plus_star_ordering(runner):269 @click.command()4 unmodified lines274 for arg in (a, b, c):275 click.echo(arg)276 277 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')"]279 280 281 def test_defaults_for_nargs(runner):282 @click.command()23 unmodified linesmodified:tests/test_bashcomplete.py-1 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 import click4 from click._bashcomplete import get_choices495 unmodified linesmodified:tests/test_basic.py+13 added-14 removed
1-# -*- coding: utf-8 -*-1 import os2 import uuid3 4 import click75 unmodified lines80 def 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}]")85 86 result = runner.invoke(cli, [])87 assert not result.exception88 assert "FOO:[no value]" in result.output9 unmodified lines98 result = runner.invoke(cli, ["--foo="])99 assert not result.exception100 assert "FOO:[]" in result.output101 103- 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.output105 106 107 def 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}]")112 113 result = runner.invoke(cli, [])114 assert not result.exception115 assert "FOO:[84]" in result.output13 unmodified lines129 "--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}]")134 135 result = runner.invoke(cli, [])136 assert not result.exception137 assert "U:[ba122011-349f-423b-873b-9d6a79c688ab]" in result.output11 unmodified lines149 @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}]")154 155 result = runner.invoke(cli, [])156 assert not result.exception157 assert "FOO:[42.0]" in result.output22 unmodified lines180 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"185 186 for default in True, False:187 188 @click.command()2 unmodified lines191 click.echo(flag)192 193 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"199 200 201 def test_boolean_conversion(runner):202 for default in True, False:14 unmodified lines217 assert result.output == "False\n"218 219 result = runner.invoke(cli, [])220 assert not result.exception222- assert result.output == "{}\n".format(default)221+ assert result.output == f"{default}\n"222 223 224 def test_file_option(runner):225 @click.command()80 unmodified lines306 307 @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)}")312 313 with runner.isolated_filesystem():314 result = runner.invoke(showtype, ["-f", "xxx"])315 assert "does not exist" in result.output4 unmodified lines320 321 @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)}")325 326 with runner.isolated_filesystem():327 result = runner.invoke(exists, ["-f", "xxx"])328 assert "exists=False" in result.output231 unmodified linesmodified:tests/test_chain.py+7 added-8 removed
5 unmodified lines6 7 8 def 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 )13 14 15 def test_basic_chaining(runner):59 unmodified lines75 76 @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}")80 81 @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}")85 86 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 lines95 96 @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}")100 101 @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}")105 106 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 lines190 191 @click.group(chain=True)192 @click.argument("arg")193 def cli(arg):195- click.echo("cli:{}".format(arg))194+ click.echo(f"cli:{arg}")195 196 @cli.command()197 def a():198 click.echo("a")31 unmodified linesmodified:tests/test_commands.py+5 added-6 removed
1-# -*- coding: utf-8 -*-1 import re2 3 import click4 19 unmodified lines24 25 @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}")29 30 @cli.command()31 @click.option("--count", default=1)32 @click.pass_context67 unmodified lines100 def 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}")105 106 @cli.command()107 def move():108 click.echo("move")100 unmodified lines209 210 @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'}")214 215 result = runner.invoke(cli, ["sync"])216 assert result.exception is None217 assert result.output == "Debug is off\n"44 unmodified lines262 @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)}")268 269 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])270 assert not result.exception271 assert result.output.splitlines() == [29 unmodified linesmodified:tests/test_compat.py+1 added-17 removed
1 import pytest2 3-import click3 from click._compat import should_strip_ansi4 from click._compat import WIN5 6 8-def test_legacy_callbacks(runner):9- def legacy_callback(ctx, value):10- return value.upper()11-12- @click.command()13- @click.option("--foo", callback=legacy_callback)14- def cli(foo):15- click.echo(foo)16-17- 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.output21-22-7 def test_bash_func_name():8 from click._bashcomplete import get_completion_script9 10 script = get_completion_script("foo-bar baz_blah", "_COMPLETE_VAR", "bash").strip()11 unmodified lines22 23 24 @pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")25 def test_is_jupyter_kernel_output():42- class JupyterKernelFakeStream(object):26+ class JupyterKernelFakeStream:27 pass28 29 # implementation detail, aka cheapskate test30 JupyterKernelFakeStream.__module__ = "ipykernel.faked"1 unmodified linemodified:tests/test_context.py+6 added-7 removed
1-# -*- coding: utf-8 -*-1 import pytest2 3 import click4 from click.core import ParameterSource5 6 7 def test_ensure_context_objects(runner):9- class Foo(object):8+ class Foo:9 def __init__(self):10 self.title = "default"11 12 pass_foo = click.make_pass_decorator(Foo, ensure=True)13 unmodified lines26 assert result.output == "default\n"27 28 29 def test_get_context_objects(runner):31- class Foo(object):30+ class Foo:31 def __init__(self):32 self.title = "default"33 34 pass_foo = click.make_pass_decorator(Foo, ensure=True)14 unmodified lines49 assert result.output == "test\n"50 51 52 def test_get_context_objects_no_ensuring(runner):54- class Foo(object):53+ class Foo:54 def __init__(self):55 self.title = "default"56 57 pass_foo = click.make_pass_decorator(Foo)14 unmodified lines72 assert result.output == "test\n"73 74 75 def test_get_context_objects_missing(runner):77- class Foo(object):76+ class Foo:77 pass78 79 pass_foo = click.make_pass_decorator(Foo)80 49 unmodified lines130 assert click.get_current_context(silent=True) is None131 132 133 def test_context_meta(runner):135- LANG_KEY = "{}.lang".format(__name__)134+ LANG_KEY = f"{__name__}.lang"135 136 def set_language(value):137 click.get_current_context().meta[LANG_KEY] = value138 78 unmodified lines217 Test to check that make_pass_decorator doesn't consume arguments based on218 invocation order.219 """220 222- class Foo(object):221+ class Foo:222 title = "foocmd"223 224 pass_foo = click.make_pass_decorator(Foo)225 102 unmodified linesmodified:tests/test_defaults.py+3 added-3 removed
4 unmodified lines5 @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}]")10 11 result = runner.invoke(cli, [])12 assert not result.exception13 assert "FOO:[42.0]" in result.output17 unmodified lines31 @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}>")37 38 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 -*-1 import click2 3 4 def test_basic_functionality(runner):144 unmodified lines149 def 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}")154 155 result = runner.invoke(cmd, [])156 assert result.exit_code == 2157 assert result.output.splitlines() == [48 unmodified lines206 207 @cmd.command()208 @click.argument("bar")209 def foo(bar):211- click.echo("foo:{}".format(bar))210+ click.echo(f"foo:{bar}")211 212 result = runner.invoke(cmd, ["foo"])213 assert result.exit_code == 2214 assert result.output.splitlines() == [7 unmodified lines222 def 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}")227 228 result = runner.invoke(cmd, [])229 assert result.exit_code == 2230 assert result.output.splitlines() == [6 unmodified lines237 def 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}")242 243 result = runner.invoke(cmd, [])244 assert result.exit_code == 2245 assert result.output.splitlines() == [107 unmodified linesmodified:tests/test_imports.py+2 added-7 removed
4 unmodified lines5 from click._compat import WIN6 7 8 IMPORT_TEST = b"""\9-try:10- import __builtin__ as builtins11-except ImportError:12- import builtins9+import builtins10 11 found_imports = set()12 real_import = builtins.__import__13 import sys43 unmodified lines57 c = subprocess.Popen(58 [sys.executable, "-"], stdin=subprocess.PIPE, stdout=subprocess.PIPE59 )60 rv = c.communicate(IMPORT_TEST)[0]64-65- if sys.version_info[0] != 2:66- rv = rv.decode("utf-8")61+ rv = rv.decode("utf-8")62 imported = json.loads(rv)63 64 for module in imported:65 if module == "click" or module.startswith("click."):2 unmodified linesmodified:tests/test_options.py+15 added-16 removed
1-# -*- coding: utf-8 -*-1 import os2 import re3 4 import pytest5 6 import click8-from click._compat import text_type7 8 9 def 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}")15 16 result = runner.invoke(cli, ["++foo", "--bar"])17 assert not result.exception18 assert result.output == "foo=True bar=True\n"24 unmodified lines43 def 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}")49 50 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 lines55 def 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}")60 61 result = runner.invoke(cli, ["-vvv"])62 assert not result.exception63 assert result.output == "verbosity=3\n"20 unmodified lines84 pass85 86 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.output89 90 91 def test_multiple_required(runner):92 @click.command()13 unmodified lines106 def 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}")111 112 result = runner.invoke(cli, [], env={"MYPATH": ""})113 assert result.exit_code == 0114 assert result.output == "mypath: None\n"28 unmodified lines143 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 lines167 @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)173 174 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)176 177 result = runner.invoke(178 cmd, "--arg1 a b --arg1 test 1 --arg2 2 two --arg2 4 four".split()179 )240 unmodified lines420 pass421 422 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.output432 433 434 def test_argument_custom_class(runner):123 unmodified linesmodified:tests/test_termui.py+10 added-11 removed
1-# -*- coding: utf-8 -*-1 import time2 3 import pytest4 5 import click._termui_impl6 from click._compat import WIN7 8 10-class FakeClock(object):9+class FakeClock:10 def __init__(self):11 self.now = time.time()12 13 def advance_time(self, seconds=1):26 unmodified lines40 assert label in runner.invoke(cli, []).output41 42 43 def test_progressbar_length_hint(runner, monkeypatch):45- class Hinted(object):44+ class Hinted:45 def __init__(self, n):46 self.items = list(range(n))47 48 def __length_hint__(self):72 unmodified lines121 def 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)128 129 116 unmodified lines246 def cli(f):247 click.echo(f.name)248 249 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"251 252 253 def test_secho(runner):254 with runner.isolation() as outstreams:34 unmodified lines289 290 @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 lines313 314 @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 lines331 assert "Custom 2" in lines[1]332 assert "Custom 4" in lines[2]333 334 336-@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.")338 def test_getchar_windows(runner, monkeypatch, key_char, echo):339 monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)2 unmodified lines342 assert click.getchar(echo) == key_char343 344 345 @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 lines353 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}"358 359 360 @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.")364 def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):365 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)4 unmodified linesmodified:tests/test_testing.py+7 added-13 removed
1 import os2 import sys3+from io import BytesIO4 5 import pytest6 7 import click7-from click._compat import PY28 from click._compat import WIN9 from click.testing import CliRunner10 11-# Use the most reasonable io that users would use for the python version.12-if PY2:13- from cStringIO import StringIO as ReasonableBytesIO14-else:15- from io import BytesIO as ReasonableBytesIO11 17-12 def test_runner():13 @click.command()14 def test():15 i = click.get_binary_stream("stdin")28 unmodified lines44 o.write(chunk)45 o.flush()46 47 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"51 52 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"56 57 58 def 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}")63 64 runner = CliRunner()65 result = runner.invoke(test, input="wau wau\n")66 assert not result.exception1 unmodified line68 69 @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}")73 74 runner = CliRunner()75 result = runner.invoke(test, input="wau wau\n")76 assert not result.exception47 unmodified lines124 assert result.output == "hello world\n"125 assert not result.exception126 127 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.exception130 131 132 def test_with_color_but_pause_not_blocking():79 unmodified lines212 213 def 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']}")217 218 runner = CliRunner()219 220 env_orig = dict(os.environ)77 unmodified linesmodified:tests/test_utils.py+12 added-29 removed
1 import os2 import stat3 import sys4+from io import StringIO5 6 import pytest7 8 import click._termui_impl2 unmodified lines11 12 13 def 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"22 22- # 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 StringIO26-27- sys.stdout = x = StringIO.StringIO()28- try:29- click.echo("\xf6")30- finally:31- sys.stdout = sys.__stdout__32- assert x.getvalue() == "\xf6\n"33-34- # 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 lines37 def test_echo_custom_file():38 import io39 40 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"43 44 45 @pytest.mark.parametrize(46 ("styles", "ref"),32 unmodified lines79 80 def 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"85 86 # 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"89 90 91 def test_prompts(runner):92 @click.command()96 unmodified lines189 assert styled_text == "\x1b[31mfoo\x1b[0m"190 191 click.echo(styled_text, color=False)192 out, err = capfd.readouterr()206- assert out == "{}\n".format(text)193+ assert out == f"{text}\n"194 195 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"198 199 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"203 204 isatty = False205 click.echo(styled_text)206 out, err = capfd.readouterr()220- assert out == "{}\n".format(text)207+ assert out == f"{text}\n"208 209 210 @pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")211 def 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))215 216 click.echo("Echo to standard output")217 out, err = capfd.readouterr()161 unmodified linesmodified:.azure-pipelines.yml+8 added-15 removed
7 unmodified lines8 TOXENV: py9 10 strategy: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: style3 unmodified lines31 32 steps:33 - task: UsePythonVersion@034 inputs:42- versionSpec: "$(python.version)"35+ versionSpec: $(python.version)36 displayName: Use Python $(python.version)37 38 - script: pip --disable-pip-version-check install -U tox39 displayName: Install tox3 unmodified linesmodified:.pre-commit-config.yaml+3 added-2 removed
1 repos: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/black16 unmodified linesmodified:CHANGES.rst+1 added
3 unmodified lines4 -----------5 6 Unreleased7 8+- 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 linesmodified:setup.cfg+30 added-4 removed
1 [metadata]2+name = click3+version = attr: click.__version__4+url = https://palletsprojects.com/p/click/5+project_urls =6+ Documentation = https://click.palletsprojects.com/7+ Code = https://github.com/pallets/click8+ Issue tracker = https://github.com/pallets/click/issues9+license = BSD-3-Clause2-license_file = LICENSE.rst10+license_files = LICENSE.rst11+maintainer = Pallets12+maintainer_email = contact@palletsprojects.com13+description = Composable command line interface toolkit14+long_description = file: README.rst15+long_description_content_type = text/x-rst16+classifiers =17+ Development Status :: 5 - Production/Stable18+ Intended Audience :: Developers19+ License :: OSI Approved :: BSD License20+ Operating System :: OS Independent21+ Programming Language :: Python22 4-[bdist_wheel]5-universal = 123+[options]24+packages = find:25+package_dir = = src26+include_package_data = true27+python_requires = >= 3.628+# Dependencies are in setup.py for GitHub's dependency graph.29 30+[options.packages.find]31+where = src32+33 [tool:pytest]34 testpaths = tests35 filterwarnings =36 error37 38 [coverage:run]13-branch = True39+branch = true40 source =41 src42 tests43 27 unmodified linesmodified:setup.py+1 added-38 removed
1-import io2-import re3-4-from setuptools import find_packages1 from setuptools import setup2 7-with io.open("README.rst", "rt", encoding="utf8") as f:8- readme = f.read()9-10-with io.open("src/click/__init__.py", "rt", encoding="utf8") as f:11- version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)12-13-setup(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-)3+setup(name="click")modified:tox.ini+1 added-1 removed
1 [tox]2 envlist =3- py{38,37,36,35,27,py3,py}3+ py{38,37,36,py3}4 style5 docs6 skip_missing_interpreters = true7 14 unmodified lines