Skip to content
Myr

f-strings everywhere

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

authored by David Lord · committed by David Lord · parent b444e63 · Browse files · 40 files+188 added−227 removed
This commit

State

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

Diff stats

40 files+188 added−227 removed

  • tests:+29 added−27 removed
  • other:+159 added−200 removed

40 files+188 added−227 removed

modified:docs/advanced.rst+7 added-7 removed
44 unmodified lines
45 if not matches:46 return None47 elif len(matches) == 1:48 return click.Group.get_command(self, ctx, matches[0])49 ctx.fail('Too many matches: %s' % ', '.join(sorted(matches)))49 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")5051And it can then be used like this:5253.. click:example::
37 unmodified lines
91 @click.command()92 @click.option('--url', callback=open_url)93 def cli(url, fp=None):94 if fp is not None:95 click.echo('%s: %s' % (url, fp.code))95 click.echo(f"{url}: {fp.code}")9697In this case the callback returns the URL unchanged but also passes a98second ``fp`` value to the callback. What's more recommended is to pass99the information in a wrapper however:
15 unmodified lines
115 @click.command()116 @click.option('--url', callback=open_url)117 def cli(url):118 if url is not None:119 click.echo('%s: %s' % (url.url, url.fp.code))119 click.echo(f"{url.url}: {url.fp.code}")120121122Token Normalization123-------------------
15 unmodified lines
139140 @click.command(context_settings=CONTEXT_SETTINGS)141 @click.option('--name', default='Pete')142 def cli(name):143 click.echo('Name: %s' % name)143 click.echo(f"Name: {name}")144145And how it works on the command line:146147.. click:run::
22 unmodified lines
170171 @cli.command()172 @click.option('--count', default=1)173 def test(count):174 click.echo('Count: %d' % count)174 click.echo(f'Count: {count}')175176 @cli.command()177 @click.option('--count', default=1)178 @click.pass_context
120 unmodified lines
299 def cli(verbose, timeit_args):300 """A fake wrapper around Python's timeit."""301 cmdline = ['echo', 'python', '-mtimeit'] + list(timeit_args)302 if verbose:303 click.echo('Invoking: %s' % ' '.join(cmdline))303 click.echo(f"Invoking: {' '.join(cmdline)}")304 call(cmdline)305306And what it looks like:307
87 unmodified lines
395 @click.argument('port', nargs=1, default=8080, envvar="PORT")396 @click.pass_context397 def cli(ctx, port):398 source = ctx.get_parameter_source("port")399 click.echo("Port came from {}".format(source))399 click.echo(f"Port came from {source}")400401.. click:run::402403 invoke(cli, prog_name='cli', args=['8080'])
5 unmodified lines
modified:docs/arguments.rst+1 added-1 removed
53 unmodified lines
54 @click.argument('dst', nargs=1)55 def copy(src, dst):56 """Move file SRC to DST."""57 for fn in src:58 click.echo('move %s to folder %s' % (fn, dst))58 click.echo(f"move {fn} to folder {dst}")5960And what it looks like:6162.. click:run::
207 unmodified lines
modified:docs/bashcomplete.rst+3 added-3 removed
48 unmodified lines
4950 @click.command()51 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)52 def cmd1(envvar):53 click.echo('Environment variable: %s' % envvar)54 click.echo('Value: %s' % os.environ[envvar])53 click.echo(f"Environment variable: {envvar}")54 click.echo(f"Value: {os.environ[envvar]}")555657Completion help strings58-----------------------
19 unmodified lines
7879 @click.command()80 @click.argument("color", type=click.STRING, autocompletion=get_colors)81 def cmd1(color):82 click.echo('Chosen color is %s' % color)82 click.echo(f"Chosen color is {color}")838485Activation86----------
77 unmodified lines
modified:docs/commands.rst+5 added-5 removed
23 unmodified lines
2425 @click.group()26 @click.option('--debug/--no-debug', default=False)27 def cli(debug):28 click.echo('Debug mode is %s' % ('on' if debug else 'off'))28 click.echo(f"Debug mode is {'on' if debug else 'off'}")2930 @cli.command() # @cli, not @click!31 def sync():32 click.echo('Syncing')
62 unmodified lines
9596 @cli.command()97 @click.pass_context98 def sync(ctx):99 click.echo('Debug is %s' % (ctx.obj['DEBUG'] and 'on' or 'off'))99 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")100101 if __name__ == '__main__':102 cli(obj={})103
61 unmodified lines
165 def cli(ctx):166 if ctx.invoked_subcommand is None:167 click.echo('I was invoked without subcommand')168 else:169 click.echo('I am about to invoke %s' % ctx.invoked_subcommand)169 click.echo(f"I am about to invoke {ctx.invoked_subcommand}")170171 @cli.command()172 def sync():173 click.echo('The subcommand')
291 unmodified lines
465466 @cli.command()467 @click.option('--port', default=8000)468 def runserver(port):469 click.echo('Serving on http://127.0.0.1:%d/' % port)469 click.echo(f"Serving on http://127.0.0.1:{port}/")470471 if __name__ == '__main__':472 cli(default_map={473 'runserver': {
37 unmodified lines
511512 @cli.command()513 @click.option('--port', default=8000)514 def runserver(port):515 click.echo('Serving on http://127.0.0.1:%d/' % port)515 click.echo(f"Serving on http://127.0.0.1:{port}/")516517 if __name__ == '__main__':518 cli()519
52 unmodified lines
modified:docs/documentation.rst+2 added-2 removed
22 unmodified lines
23 @click.argument('name')24 def hello(count, name):25 """This script prints hello NAME COUNT times."""26 for x in range(count):27 click.echo('Hello %s!' % name)27 click.echo(f"Hello {name}!")2829And what it looks like:3031.. click:run::
140 unmodified lines
172 @click.argument('name', metavar='<name>')173 def hello(count, name):174 """This script prints hello <name> <int> times."""175 for x in range(count):176 click.echo('Hello %s!' % name)176 click.echo(f"Hello {name}!")177178Example:179180.. click:run::
61 unmodified lines
modified:docs/index.rst+1 added-1 removed
34 unmodified lines
35 help='The person to greet.')36 def hello(count, name):37 """Simple program that greets NAME for a total of COUNT times."""38 for x in range(count):39 click.echo('Hello %s!' % name)39 click.echo(f"Hello {name}!")4041 if __name__ == '__main__':42 hello()43
64 unmodified lines
modified:docs/options.rst+22 added-18 removed
83 unmodified lines
84 @click.command()85 @click.option('--from', '-f', 'from_')86 @click.option('--to', '-t')87 def reserved_param_name(from_, to):88 click.echo('from %s to %s' % (from_, to))88 click.echo(f"from {from_} to {to}")8990And on the command line:9192.. click:run::
27 unmodified lines
120121 @click.command()122 @click.option('--pos', nargs=2, type=float)123 def findme(pos):124 a, b = pos124 click.echo('%s / %s' % pos)125 click.echo(f"{a} / {b}")126127And on the command line:128129.. click:run::
16 unmodified lines
146147 @click.command()148 @click.option('--item', type=(str, int))149 def putitem(item):149 click.echo('name=%s id=%d' % item)150 name, id = item151 click.echo(f"name={name} id={id}")152153And on the command line:154155.. click:run::
8 unmodified lines
164165 @click.command()166 @click.option('--item', nargs=2, type=click.Tuple([str, int]))167 def putitem(item):166 click.echo('name=%s id=%d' % item)168 name, id = item169 click.echo(f"name={name} id={id}")170171.. _multiple-options:172173Multiple Options
40 unmodified lines
214215 @click.command()216 @click.option('-v', '--verbose', count=True)217 def log(verbose):215 click.echo('Verbosity: %s' % verbose)218 click.echo(f"Verbosity: {verbose}")219220And on the command line:221222.. click:run::
60 unmodified lines
283284 @click.command()285 @click.option('/debug;/no-debug')286 def log(debug):284 click.echo('debug=%s' % debug)287 click.echo(f"debug={debug}")288289 if __name__ == '__main__':290 log()291
112 unmodified lines
404405 @click.command()406 @click.option('--name', prompt=True)407 def hello(name):405 click.echo('Hello %s!' % name)408 click.echo(f"Hello {name}!")409410And what it looks like:411412.. click:run::
8 unmodified lines
421422 @click.command()423 @click.option('--name', prompt='Your name please')424 def hello(name):422 click.echo('Hello %s!' % name)425 click.echo(f"Hello {name}!")426427What it looks like:428429.. click:run::
15 unmodified lines
445 @click.command()446 @click.option('--password', prompt=True, hide_input=True,447 confirmation_prompt=True)448 def encrypt(password):446 click.echo('Encrypting password to %s' % password.encode('rot13'))449 click.echo(f"Encrypting password to {password.encode('rot13')}")450451What it looks like:452453.. click:run::
7 unmodified lines
461462 @click.command()463 @click.password_option()464 def encrypt(password):462 click.echo('Encrypting password to %s' % password.encode('rot13'))465 click.echo(f"Encrypting password to {password.encode('rot13')}")466467Dynamic Defaults for Prompts468----------------------------469
157 unmodified lines
627628 @click.command()629 @click.option('--username')630 def greet(username):628 click.echo('Hello %s!' % username)631 click.echo(f'Hello {username}!')632633 if __name__ == '__main__':634 greet(auto_envvar_prefix='GREETER')635
16 unmodified lines
652653 @click.group()654 @click.option('--debug/--no-debug')655 def cli(debug):653 click.echo('Debug mode is %s' % ('on' if debug else 'off'))656 click.echo(f"Debug mode is {'on' if debug else 'off'}")657658 @cli.command()659 @click.option('--username')660 def greet(username):658 click.echo('Hello %s!' % username)661 click.echo(f"Hello {username}!")662663 if __name__ == '__main__':664 cli(auto_envvar_prefix='GREETER')665
13 unmodified lines
679680 @click.command()681 @click.option('--username', envvar='USERNAME')682 def greet(username):680 click.echo('Hello %s!' % username)683 click.echo(f"Hello {username}!")684685 if __name__ == '__main__':686 greet()687
40 unmodified lines
728729.. click:run::730731 import os729 invoke(perform, env={'PATHS': './foo/bar%s./test' % os.path.pathsep})732 invoke(perform, env={"PATHS": f"./foo/bar{os.path.pathsep}./test"})733734Other Prefix Characters735-----------------------736
7 unmodified lines
744745 @click.command()746 @click.option('+w/-w')747 def chmod(w):745 click.echo('writable=%s' % w)748 click.echo(f"writable={w}")749750 if __name__ == '__main__':751 chmod()752
11 unmodified lines
764765 @click.command()766 @click.option('/debug;/no-debug')767 def log(debug):765 click.echo('debug=%s' % debug)768 click.echo(f"debug={debug}")769770 if __name__ == '__main__':771 log()772
63 unmodified lines
836837 @click.command()838 @click.option('--rolls', callback=validate_rolls, default='1d6')839 def roll(rolls):837 click.echo('Rolling a %d-sided dice %d time(s)' % rolls)840 sides, times = rolls841 click.echo(f"Rolling a {sides}-sided dice {times} time(s)")842843 if __name__ == '__main__':844 roll()845
7 unmodified lines
modified:docs/quickstart.rst+1 added-1 removed
238 unmodified lines
239 @click.option('--count', default=1, help='number of greetings')240 @click.argument('name')241 def hello(count, name):242 for x in range(count):243 click.echo('Hello %s!' % name)243 click.echo(f"Hello {name}!")244245What it looks like:246247.. click:run::
30 unmodified lines
modified:docs/testing.rst+3 added-3 removed
28 unmodified lines
2930 @click.command()31 @click.argument('name')32 def hello(name):33 click.echo('Hello %s!' % name)33 click.echo(f'Hello {name}!')3435.. code-block:: python36 :caption: test_hello.py37
15 unmodified lines
5354 @click.group()55 @click.option('--debug/--no-debug', default=False)56 def cli(debug):57 click.echo('Debug mode is %s' % ('on' if debug else 'off'))57 click.echo(f"Debug mode is {'on' if debug else 'off'}")5859 @cli.command()60 def sync():61 click.echo('Syncing')
63 unmodified lines
125126 @click.command()127 @click.option('--foo', prompt=True)128 def prompt(foo):129 click.echo('foo=%s' % foo)129 click.echo(f"foo={foo}")130131.. code-block:: python132 :caption: test_prompt.py133
12 unmodified lines
modified:docs/utils.rst+5 added-6 removed
110 unmodified lines
111.. click:example::112113 @click.command()114 def less():115 click.echo_via_pager('\n'.join('Line %d' % idx116 for idx in range(200)))115 click.echo_via_pager("\n".join(f"Line {idx}" for idx in range(200)))116117If 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:118119.. click:example::120 def _generate_output():121 for idx in range(50000):123 yield "Line %d\n" % idx122 yield f"Line {idx}\n"123124 @click.command()125 def less():126 click.echo_via_pager(_generate_output())
135 unmodified lines
262context of a full Unicode string.263264Example::265267 click.echo('Path: %s' % click.format_filename(b'foo.txt'))266 click.echo(f"Path: {click.format_filename(b'foo.txt')}")267268269Standard Streams270----------------
76 unmodified lines
347 parser.read([cfg])348 rv = {}349 for section in parser.sections():350 for key, value in parser.items(section):352 rv['%s.%s' % (section, key)] = value351 rv[f"{section}.{key}"] = value352 return rv353354355Showing Progress Bars
38 unmodified lines
394 import time395396 with click.progressbar([1, 2, 3]) as bar:397 for x in bar:399 print('sleep({})...'.format(x))398 print(f"sleep({x})...")399 time.sleep(x)400401Another useful feature is to associate a label with the progress bar which402will be shown preceding the progress bar::
17 unmodified lines
modified:examples/aliases/aliases.py+1 added-1 removed
63 unmodified lines
64 if not matches:65 return None66 elif len(matches) == 1:67 return click.Group.get_command(self, ctx, matches[0])68 ctx.fail("Too many matches: {}".format(", ".join(sorted(matches))))68 ctx.fail(f"Too many matches: {', '.join(sorted(matches))}")697071def read_config(ctx, param, value):72 """Callback that is used whenever --config is passed. We use this to
66 unmodified lines
modified:examples/bashcompletion/bashcompletion.py+1 added-1 removed
17 unmodified lines
18@cli.command(help="A command to print environment variables")19@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20def cmd1(envvar):21 click.echo(f"Environment variable: {envvar}")22 click.echo("Value: {}".format(os.environ[envvar]))22 click.echo(f"Value: {os.environ[envvar]}")232425@click.group(help="A group that holds a subcommand")26def group():
19 unmodified lines
modified:examples/complex/complex/commands/cmd_init.py+1 added-1 removed
8 unmodified lines
9def cli(ctx, path):10 """Initializes a repository."""11 if path is None:12 path = ctx.home13 ctx.log("Initialized the repository in %s", click.format_filename(path))13 ctx.log(f"Initialized the repository in {click.format_filename(path)}")
modified:examples/imagepipe/imagepipe.py+2 added-3 removed
228 unmodified lines
229def smoothen_cmd(images, iterations):230 """Applies a smoothening filter."""231 for image in images:232 click.echo(233 "Smoothening '{}' {} time{}".format(234 image.filename, iterations, "s" if iterations != 1 else ""235 )233 f"Smoothening {image.filename!r} {iterations}"234 f" time{'s' if iterations != 1 else ''}"235 )236 for _ in range(iterations):237 image = copy_filename(image.filter(ImageFilter.BLUR), image)238 yield image
50 unmodified lines
modified:examples/repo/repo.py+1 added-1 removed
76 unmodified lines
77 of SRC and create that folder.78 """79 if dest is None:80 dest = posixpath.split(src)[-1] or "."81 click.echo("Cloning repo {} to {}".format(src, os.path.abspath(dest)))81 click.echo(f"Cloning repo {src} to {os.path.basename(dest)}")82 repo.home = dest83 if shallow:84 click.echo("Making shallow checkout")85 click.echo(f"Checking out revision {rev}")
81 unmodified lines
modified:examples/termui/termui.py+1 added-1 removed
22 unmodified lines
23def pager():24 """Demonstrates using the pager."""25 lines = []26 for x in range(200):27 lines.append("{}. Hello World!".format(click.style(str(x), fg="green")))27 lines.append(f"{click.style(str(x), fg='green')}. Hello World!")28 click.echo_via_pager("\n".join(lines))293031@cli.command()
138 unmodified lines
modified:examples/validation/validation.py+1 added-2 removed
15 unmodified lines
16 if not isinstance(value, tuple):17 value = urlparse.urlparse(value)18 if value.scheme not in ("http", "https"):19 self.fail(20 "invalid URL scheme ({}). Only HTTP URLs are"21 " allowed".format(value.scheme),20 f"invalid URL scheme ({value.scheme}). Only HTTP URLs are allowed",21 param,22 ctx,23 )24 return value
24 unmodified lines
modified:src/click/_bashcomplete.py+1 added-1 removed
343 unmodified lines
344 args = cwords[1:]345346 for item in get_choices(cli, prog_name, args, incomplete):347 if item[1]:348 echo("{arg}\t{desc}".format(arg=item[0], desc=item[1]))348 echo(f"{item[0]}\t{item[1]}")349 else:350 echo(item[0])351352 return True
19 unmodified lines
modified:src/click/_compat.py+2 added-2 removed
62 unmodified lines
63 encoding,64 errors,65 force_readable=False,66 force_writable=False,67 **extra67 **extra,68 ):69 self._stream = stream = _FixupStream(stream, force_readable, force_writable)70 super().__init__(stream, encoding, errors, **extra)71
342 unmodified lines
414415 while True:416 tmp_filename = os.path.join(417 os.path.dirname(filename),418 ".__atomic-write{:08x}".format(random.randrange(1 << 32)),418 f".__atomic-write{random.randrange(1 << 32):08x}",419 )420 try:421 fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)422 break
189 unmodified lines
modified:src/click/_termui_impl.py+9 added-12 removed
171 unmodified lines
172 pos += f"/{self.length}"173 return pos174175 def format_pct(self):176 return "{: 4}%".format(int(self.pct * 100))[1:]176 return f"{int(self.pct * 100): 4}%"[1:]177178 def format_bar(self):179 if self.length_known:180 bar_length = int(self.pct * self.width)
170 unmodified lines
351352 fd, filename = tempfile.mkstemp()353 os.close(fd)354 try:355 if (356 hasattr(os, "system")357 and os.system("more {}".format(shlex.quote(filename))) == 0358 ):355 if hasattr(os, "system") and os.system(f"more {shlex.quote(filename)}") == 0:356 return _pipepager(generator, "more", color)357 return _nullpager(stdout, generator, color)358 finally:359 os.unlink(filename)
10 unmodified lines
370 # If we're piping to less we might support colors under the371 # condition that372 cmd_detail = cmd.rsplit("/", 1)[-1].split()373 if color is None and cmd_detail[0] == "less":377 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:
41 unmodified lines
420 encoding = get_best_encoding(sys.stdout)421 with open_stream(filename, "wb")[0] as f:422 f.write(text.encode(encoding))423 try:427 os.system("{} {}".format(shlex.quote(cmd), shlex.quote(filename)))424 os.system(f"{shlex.quote(cmd)} {shlex.quote(filename)}")425 finally:426 os.unlink(filename)427428
36 unmodified lines
465 else:466 environ = None467 try:468 c = subprocess.Popen(472 "{} {}".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()
68 unmodified lines
542 null.close()543 elif WIN:544 if locate:545 url = _unquote_file(url)549 args = "explorer /select,{}".format(shlex.quote(url))546 args = f"explorer /select,{shlex.quote(url)}"547 else:551 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)556 args = "cygstart {}".format(shlex.quote(os.path.dirname(url)))553 args = f"cygstart {shlex.quote(os.path.dirname(url))}"554 else:558 args = "cygstart {} {}".format("-w" if wait else "", shlex.quote(url))555 args = f"cygstart {'-w' if wait else ''} {shlex.quote(url)}"556 return os.system(args)557558 try:559 if locate:
109 unmodified lines
modified:src/click/_textwrap.py+1 added-1 removed
31 unmodified lines
32 for idx, line in enumerate(text.splitlines()):33 indent = self.initial_indent34 if idx > 0:35 indent = self.subsequent_indent36 rv.append(indent + line)36 rv.append(f"{indent}{line}")37 return "\n".join(rv)
modified:src/click/_unicodefun.py+5 added-5 removed
53 unmodified lines
54 " export LANG=C.UTF-8"55 )56 else:57 extra += (58 "This system lists a couple of UTF-8 supporting locales"59 " that you can pick from. The following suitable"60 " locales were discovered: {}".format(", ".join(sorted(good_locales)))58 "This system lists some UTF-8 supporting locales that"59 " you can pick from. The following suitable locales"60 f" were discovered: {', '.join(sorted(good_locales))}"61 )6263 bad_locale = None64 for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):
5 unmodified lines
70 extra += (71 "\n\nClick discovered that you exported a UTF-8 locale"72 " but the locale system could not pick up from it"73 " because it does not exist. The exported locale is"74 " '{}' but it is not supported".format(bad_locale)74 f" {bad_locale!r} but it is not supported"75 )7677 raise RuntimeError(78 "Click will abort further execution because Python 3 was"79 " configured to use ASCII as encoding for the environment."80 " Consult https://click.palletsprojects.com/python3/ for"81 " mitigation steps.{}".format(extra)81 f" mitigation steps.{extra}"82 )
modified:src/click/_winconsole.py+1 added-3 removed
211 unmodified lines
212 def isatty(self):213 return self.buffer.isatty()214215 def __repr__(self):216 return "<ConsoleStream name={!r} encoding={!r}>".format(217 self.name, self.encoding218 )216 return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"217218219class WindowsChunkedWriter:220 """
88 unmodified lines
modified:src/click/core.py+28 added-33 removed
34 unmodified lines
35SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."36SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."3738DEPRECATED_HELP_NOTICE = " (DEPRECATED)"39DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command %(name)s is deprecated."39DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command {name} is deprecated."404142def _maybe_show_deprecated_notice(cmd):43 if cmd.deprecated:44 echo(style(DEPRECATED_INVOKE_NOTICE % {"name": cmd.name}, fg="red"), err=True)44 echo(style(DEPRECATED_INVOKE_NOTICE.format(name=cmd.name), fg="red"), err=True)454647def fast_exit(code):48 """Exit without garbage collection, this speeds up exit by about 10ms for
6 unmodified lines
5556def _bashcomplete(cmd, prog_name, complete_var=None):57 """Internal handler for the bash completion support."""58 if complete_var is None:59 complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())59 complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()60 complete_instr = os.environ.get(complete_var)61 if not complete_instr:62 return63
16 unmodified lines
80 "Found a multi command as subcommand to a multi command"81 " that is in chain mode. This is not supported."82 )83 raise RuntimeError(84 "{}. Command '{}' is set to chain and '{}' was added as"85 " subcommand but it in itself is a multi command. ('{}' is a {}"86 " within a chained {} named '{}').".format(87 hint,88 base_command.name,89 cmd_name,90 cmd_name,91 cmd.__class__.__name__,92 base_command.__class__.__name__,93 base_command.name,94 )84 f"{hint}. Command {base_command.name!r} is set to chain and"85 f" {cmd_name!r} was added as a subcommand but it in itself is a"86 f" multi command. ({cmd_name!r} is a {type(cmd).__name__}"87 f" within a chained {type(base_command).__name__} named"88 f" {base_command.name!r})."89 )909192def batch(iterable, batch_size):
59 unmodified lines
152 :param value: the string value to verify153 """154 if value not in cls.VALUES:155 raise ValueError(162 "Invalid ParameterSource value: '{}'. Valid "163 "values are: {}".format(value, ",".join(cls.VALUES))156 f"Invalid ParameterSource value: {value!r}. Valid"157 f" values are: {','.join(cls.VALUES)}"158 )159160161class Context:
212 unmodified lines
374 parent is not None375 and parent.auto_envvar_prefix is not None376 and self.info_name is not None377 ):384 auto_envvar_prefix = "{}_{}".format(385 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:
697 unmodified lines
1081 value, args = param.handle_parse_result(ctx, opts, args)10821083 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1084 ctx.fail(1091 "Got unexpected extra argument{} ({})".format(1092 "s" if len(args) != 1 else "", " ".join(map(make_str, args))1093 )1085 "Got unexpected extra"1086 f" argument{'s' if len(args) != 1 else ''}"1087 f" ({' '.join(map(make_str, args))})"1088 )10891090 ctx.args = args1091 return args
499 unmodified lines
1591 if self.type.is_composite:1592 if self.nargs <= 1:1593 raise TypeError(1594 "Attempted to invoke composite type but nargs has"1601 " been set to {}. This is not supported; nargs"1602 " 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)
255 unmodified lines
1856 raise TypeError("Could not determine name for option")18571858 if not opts and not secondary_opts:1859 raise TypeError(1866 "No options defined but a name was passed ({}). Did you"1867 " mean to declare an argument instead of an option?".format(name)1860 f"No options defined but a name was passed ({name})."1861 " Did you mean to declare an argument instead of an"1862 " option?"1863 )18641865 return name, opts, secondary_opts1866
51 unmodified lines
1918 if envvar is None:1919 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1920 envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"1921 if envvar is not None:1927 extra.append(1928 "env var: {}".format(1929 ", ".join(str(d) for d in envvar)1930 if isinstance(envvar, (list, tuple))1931 else envvar1922 var_str = (1923 ", ".join(str(d) for d in envvar)1924 if isinstance(envvar, (list, tuple))1925 else envvar1932 )1926 )1927 extra.append(f"env var: {var_str}")1928 if self.default is not None and (self.show_default or ctx.show_default):1929 if isinstance(self.show_default, str):1930 default_string = f"({self.show_default})"1931 elif isinstance(self.default, (list, tuple)):
6 unmodified lines
19381939 if self.required:1940 extra.append("required")1941 if extra:1948 help = "{}[{}]".format(f"{help} " if help else "", "; ".join(extra))1942 extra_str = ";".join(extra)1943 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"19441945 return ("; " if any_prefix_is_slash else " / ").join(rv), help19461947 def get_default(self, ctx):
107 unmodified lines
2055 name = name.replace("-", "_").lower()2056 else:2057 raise TypeError(2058 "Arguments take exactly one parameter declaration, got"2064 " {}".format(len(decls))2059 f" {len(decls)}."2060 )2061 return name, [arg], []20622063 def get_usage_pieces(self, ctx):
7 unmodified lines
modified:src/click/decorators.py+3 added-2 removed
64 unmodified lines
65 obj = ctx.find_object(object_type)66 if obj is None:67 raise RuntimeError(68 "Managed to invoke callback without a context"69 " object of type '{}' existing".format(object_type.__name__)69 f" object of type {object_type.__name__!r}"70 " existing."71 )72 return ctx.invoke(f, obj, *args, **kwargs)7374 return update_wrapper(new_func, f)
21 unmodified lines
96 return cls(97 name=name or f.__name__.lower().replace("_", "-"),98 callback=f,99 params=params,99 **attrs100 **attrs,101 )102103104def command(name=None, cls=None, **attrs):
227 unmodified lines
modified:src/click/exceptions.py+7 added-10 removed
51 unmodified lines
52 file = get_text_stderr()53 color = None54 hint = ""55 if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:56 hint = "Try '{} {}' for help.\n".format(57 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.color62 echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)
74 unmodified lines
137 msg += f". {msg_extra}"138 else:139 msg = msg_extra140140 return "Missing {}{}{}{}".format(141 param_type,142 f" {param_hint}" if param_hint else "",143 ". " if msg else ".",144 msg or "",145 )141 hint_str = f" {param_hint}" if param_hint else ""142 return f"Missing {param_type}{hint_str}.{' ' if msg else ''}{msg or ''}"143144 def __str__(self):145 if self.message is None:146 param_name = self.param.name if self.param else None
19 unmodified lines
166 def format_message(self):167 bits = [self.message]168 if self.possibilities:169 if len(self.possibilities) == 1:173 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)176 bits.append("(Possible options: {})".format(", ".join(possibilities)))173 bits.append(f"(Possible options: {', '.join(possibilities)})")174 return " ".join(bits)175176177class BadOptionUsage(UsageError):
56 unmodified lines
modified:src/click/formatting.py+5 added-9 removed
132 unmodified lines
133 :param prog: the program name.134 :param args: whitespace separated list of arguments.135 :param prefix: the prefix for the first line.136 """137 usage_prefix = "{:>{w}}{} ".format(prefix, prog, w=self.current_indent)137 usage_prefix = f"{prefix:>{self.current_indent}}{prog} "138 text_width = self.width - self.current_indent139140 if text_width >= (term_len(usage_prefix) + 20):141 # The arguments will fit to the right of the prefix.
20 unmodified lines
162 self.write("\n")163164 def write_heading(self, heading):165 """Writes a heading into the buffer."""166 self.write("{:>{w}}{}:\n".format("", heading, w=self.current_indent))166 self.write(f"{'':>{self.current_indent}}{heading}:\n")167168 def write_paragraph(self):169 """Writes a paragraph into the buffer."""170 if self.buffer:
32 unmodified lines
203204 first_col = min(widths[0], col_max) + col_spacing205206 for first, second in iter_rows(rows, len(widths)):207 self.write("{:>{w}}{}".format("", first, w=self.current_indent))207 self.write(f"{'':>{self.current_indent}}{first}")208 if not second:209 self.write("\n")210 continue211 if term_len(first) <= first_col - col_spacing:
6 unmodified lines
218 wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)219 lines = wrapped_text.splitlines()220221 if lines:222 self.write("{}\n".format(lines[0]))222 self.write(f"{lines[0]}\n")223224 for line in lines[1:]:225 self.write(226 "{:>{w}}{}\n".format(227 "", line, w=first_col + self.current_indent228 )229 )225 self.write(f"{'':>{first_col + self.current_indent}}{line}\n")226227 if len(lines) > 1:228 # separate long help from next option229 self.write("\n")
50 unmodified lines
modified:src/click/parser.py+3 added-3 removed
98 unmodified lines
99def normalize_opt(opt, ctx):100 if ctx is None or ctx.token_normalize_func is None:101 return opt102 prefix, opt = split_opt(opt)103 return prefix + ctx.token_normalize_func(opt)103 return f"{prefix}{ctx.token_normalize_func(opt)}"104105106def split_arg_string(string):107 """Given an argument string this attempts to split it into small parts."""
252 unmodified lines
360 prefix = arg[0]361 unknown_options = []362363 for ch in arg[1:]:364 opt = normalize_opt(prefix + ch, self.ctx)364 opt = normalize_opt(f"{prefix}{ch}", self.ctx)365 option = self._short_opt.get(opt)366 i += 1367368 if not option:
29 unmodified lines
398 # remaining options and re-attach the prefix, then report that399 # to the state as new larg. This way there is basic combinatorics400 # that can be achieved while still ignoring unknown arguments.401 if self.ignore_unknown_options and unknown_options:402 state.largs.append("{}{}".format(prefix, "".join(unknown_options)))402 state.largs.append(f"{prefix}{''.join(unknown_options)}")403404 def _process_opts(self, arg, state):405 explicit_value = None406 # Long option handling happens in two parts. The first part is
25 unmodified lines
modified:src/click/termui.py+12 added-12 removed
54 unmodified lines
55 text, suffix, show_default=False, default=None, show_choices=True, type=None56):57 prompt = text58 if type is not None and show_choices and isinstance(type, Choice):59 prompt += " ({})".format(", ".join(map(str, type.choices)))59 prompt += f" ({', '.join(map(str, type.choices))})"60 if default is not None and show_default:61 prompt = "{} [{}]".format(prompt, _format_default(default))62 return prompt + suffix61 prompt = f"{prompt} [{_format_default(default)}]"62 return f"{prompt}{suffix}"636465def _format_default(default):66 if isinstance(default, (io.IOBase, LazyFile)) and hasattr(default, "name"):
434 unmodified lines
501 """502 bits = []503 if fg:504 try:505 bits.append("\033[{}m".format(_ansi_colors[fg]))505 bits.append(f"\033[{_ansi_colors[fg]}m")506 except KeyError:507 raise TypeError(f"Unknown color '{fg}'")507 raise TypeError(f"Unknown color {fg!r}")508 if bg:509 try:510 bits.append("\033[{}m".format(_ansi_colors[bg] + 10))510 bits.append(f"\033[{_ansi_colors[bg] + 10}m")511 except KeyError:512 raise TypeError(f"Unknown color '{bg}'")512 raise TypeError(f"Unknown color {bg!r}")513 if bold is not None:514 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:516 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:518 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:520 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:522 bits.append("\033[{}m".format(7 if reverse else 27))522 bits.append(f"\033[{7 if reverse else 27}m")523 bits.append(text)524 if reset:525 bits.append(_ansi_reset_all)526 return "".join(bits)
162 unmodified lines
modified:src/click/testing.py+3 added-4 removed
97 unmodified lines
98 "\r\n", "\n"99 )100101 def __repr__(self):102 return "<{} {}>".format(103 type(self).__name__, repr(self.exception) if self.exception else "okay"104 )102 exc_str = repr(self.exception) if self.exception else "okay"103 return f"<{type(self).__name__} {exc_str}>"104105106class CliRunner:107 """The CLI runner provides functionality to invoke a Click command line
86 unmodified lines
194 sys.stdout.flush()195 return val196197 def hidden_input(prompt=None):199 sys.stdout.write("{}\n".format(prompt or ""))198 sys.stdout.write(f"{prompt or ''}\n")199 sys.stdout.flush()200 return input.readline().rstrip("\r\n")201202 def _getchar(echo):
160 unmodified lines
modified:src/click/types.py+20 added-45 removed
155 unmodified lines
156 self.choices = choices157 self.case_sensitive = case_sensitive158159 def get_metavar(self, param):160 return "[{}]".format("|".join(self.choices))160 return f"[{'|'.join(self.choices)}]"161162 def get_missing_message(self, param):163 return "Choose from:\n\t{}.".format(",\n\t".join(self.choices))163 choice_str = ",\n\t".join(self.choices)164 return f"Choose from:\n\t{choice_str}"165166 def convert(self, value, param, ctx):167 # Match through normalization and case sensitivity168 # first do token_normalize_func, then lowercase
19 unmodified lines
188 if normed_value in normed_choices:189 return normed_choices[normed_value]190191 self.fail(191 "invalid choice: {}. (choose from {})".format(192 value, ", ".join(self.choices)193 ),192 f"invalid choice: {value}. (choose from {', '.join(self.choices)})",193 param,194 ctx,195 )196197 def __repr__(self):199 return "Choice('{}')".format(list(self.choices))198 return f"Choice({list(self.choices)})"199200201class DateTime(ParamType):202 """The DateTime type converts date strings into `datetime` objects.
21 unmodified lines
224 def __init__(self, formats=None):225 self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]226227 def get_metavar(self, param):229 return "[{}]".format("|".join(self.formats))228 return f"[{'|'.join(self.formats)}]"229230 def _try_to_convert_date(self, value, format):231 try:232 return datetime.strptime(value, format)
7 unmodified lines
240 if dtime:241 return dtime242243 self.fail(245 "invalid datetime format: {}. (choose from {})".format(246 value, ", ".join(self.formats)247 )244 f"invalid datetime format: {value}. (choose from {', '.join(self.formats)})"245 )246247 def __repr__(self):248 return "DateTime"
42 unmodified lines
291 and rv > self.max292 ):293 if self.min is None:294 self.fail(298 "{} is bigger than the maximum valid value {}.".format(299 rv, self.max300 ),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(306 "{} is smaller than the minimum valid value {}.".format(307 rv, self.min308 ),301 f"{rv} is smaller than the minimum valid value {self.min}.",302 param,303 ctx,304 )305 else:306 self.fail(314 "{} is not in the valid range of {} to {}.".format(315 rv, self.min, self.max316 ),307 f"{rv} is not in the valid range of {self.min} to {self.max}.",308 param,309 ctx,310 )311 return rv
45 unmodified lines
357 and rv > self.max358 ):359 if self.min is None:360 self.fail(370 "{} is bigger than the maximum valid value {}.".format(371 rv, self.max372 ),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(378 "{} is smaller than the minimum valid value {}.".format(379 rv, self.min380 ),367 f"{rv} is smaller than the minimum valid value {self.min}.",368 param,369 ctx,370 )371 else:372 self.fail(386 "{} is not in the valid range of {} to {}.".format(387 rv, self.min, self.max388 ),373 f"{rv} is not in the valid range of {self.min} to {self.max}.",374 param,375 ctx,376 )377 return rv
112 unmodified lines
490 ctx.call_on_close(safecall(f.flush))491 return f492 except OSError as e: # noqa: B014493 self.fail(509 "Could not open file: {}: {}".format(510 filename_to_ui(value), get_strerror(e)511 ),494 f"Could not open file: {filename_to_ui(value)}: {get_strerror(e)}",495 param,496 ctx,497 )498
83 unmodified lines
582 except OSError:583 if not self.exists:584 return self.coerce_path_result(rv)585 self.fail(603 "{} '{}' does not exist.".format(604 self.path_type, filename_to_ui(value)605 ),586 f"{self.path_type} {filename_to_ui(value)!r} does not exist.",587 param,588 ctx,589 )590591 if not self.file_okay and stat.S_ISREG(st.st_mode):592 self.fail(612 "{} '{}' 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(618 "{} '{}' is a directory.".format(619 self.path_type, filename_to_ui(value)620 ),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(626 "{} '{}' is not writable.".format(627 self.path_type, filename_to_ui(value)628 ),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(634 "{} '{}' is not readable.".format(635 self.path_type, filename_to_ui(value)636 ),611 f"{self.path_type} {filename_to_ui(value)!r} is not readable.",612 param,613 ctx,614 )615
18 unmodified lines
634 self.types = [convert_type(ty) for ty in types]635636 @property637 def name(self):663 return "<{}>".format(" ".join(ty.name for ty in self.types))638 return f"<{' '.join(ty.name for ty in self.types)}>"639640 @property641 def arity(self):642 return len(self.types)
84 unmodified lines
modified:src/click/utils.py+1 added-1 removed
406 unmodified lines
407 if folder is None:408 folder = os.path.expanduser("~")409 return os.path.join(folder, app_name)410 if force_posix:411 return os.path.join(os.path.expanduser("~/.{}".format(_posixify(app_name))))411 return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))412 if sys.platform == "darwin":413 return os.path.join(414 os.path.expanduser("~/Library/Application Support"), app_name415 )
29 unmodified lines
modified:tests/test_arguments.py+7 added-5 removed
8 unmodified lines
9 @click.command()10 @click.argument("src", nargs=-1)11 @click.argument("dst")12 def copy(src, dst):13 click.echo("src={}".format("|".join(src)))13 click.echo(f"src={'|'.join(src)}")14 click.echo(f"dst={dst}")1516 result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])17 assert not result.exception
14 unmodified lines
32 @click.argument("name", nargs=1)33 @click.argument("point", nargs=2, type=click.INT)34 def copy(name, point):35 click.echo(f"name={name}")36 click.echo("point={0[0]}/{0[1]}".format(point))36 x, y = point37 click.echo(f"point={x}/{y}")3839 result = runner.invoke(copy, ["peter", "1", "2"])40 assert not result.exception41 assert result.output.splitlines() == ["name=peter", "point=1/2"]
11 unmodified lines
5354 @click.command()55 @click.argument("item", **opts)56 def copy(item):56 click.echo("name={0[0]} id={0[1]:d}".format(item))57 name, id = item58 click.echo(f"name={name} id={id:d}")5960 result = runner.invoke(copy, ["peter", "1"])61 assert not result.exception62 assert result.output.splitlines() == ["name=peter id=1"]
125 unmodified lines
188def test_empty_nargs(runner):189 @click.command()190 @click.argument("arg", nargs=-1)191 def cmd(arg):190 click.echo("arg:{}".format("|".join(arg)))192 click.echo(f"arg:{'|'.join(arg)}")193194 result = runner.invoke(cmd, [])195 assert result.exit_code == 0196 assert result.output == "arg:\n"197198 @click.command()199 @click.argument("arg", nargs=-1, required=True)200 def cmd2(arg):199 click.echo("arg:{}".format("|".join(arg)))201 click.echo(f"arg:{'|'.join(arg)}")202203 result = runner.invoke(cmd2, [])204 assert result.exit_code == 2205 assert "Missing argument 'ARG...'" in result.output
100 unmodified lines
modified:tests/test_basic.py+5 added-5 removed
106 unmodified lines
107def test_int_option(runner):108 @click.command()109 @click.option("--foo", default=42)110 def cli(foo):111 click.echo("FOO:[{}]".format(foo * 2))111 click.echo(f"FOO:[{foo * 2}]")112113 result = runner.invoke(cli, [])114 assert not result.exception115 assert "FOO:[84]" in result.output
75 unmodified lines
191 click.echo(flag)192193 result = runner.invoke(cli, ["--flag"])194 assert not result.exception195 assert result.output == "{}\n".format(not default)195 assert result.output == f"{not default}\n"196 result = runner.invoke(cli, [])197 assert not result.exception198 assert result.output == f"{default}\n"199
106 unmodified lines
306307 @click.command()308 @click.option("-f", type=click.Path(exists=True))309 def showtype(f):310 click.echo("is_file={}".format(os.path.isfile(f)))311 click.echo("is_dir={}".format(os.path.isdir(f)))310 click.echo(f"is_file={os.path.isfile(f)}")311 click.echo(f"is_dir={os.path.isdir(f)}")312313 with runner.isolated_filesystem():314 result = runner.invoke(showtype, ["-f", "xxx"])315 assert "does not exist" in result.output
4 unmodified lines
320321 @click.command()322 @click.option("-f", type=click.Path())323 def exists(f):324 click.echo("exists={}".format(os.path.exists(f)))324 click.echo(f"exists={os.path.exists(f)}")325326 with runner.isolated_filesystem():327 result = runner.invoke(exists, ["-f", "xxx"])328 assert "exists=False" in result.output
231 unmodified lines
modified:tests/test_chain.py+2 added-3 removed
5 unmodified lines
678def debug():9 click.echo(10 "{}={}".format(11 sys._getframe(1).f_code.co_name, "|".join(click.get_current_context().args)12 )10 f"{sys._getframe(1).f_code.co_name}"11 f"={'|'.join(click.get_current_context().args)}"12 )131415def test_basic_chaining(runner):
214 unmodified lines
modified:tests/test_commands.py+2 added-2 removed
208 unmodified lines
209210 @cli.command()211 @click.pass_context212 def sync(ctx):213 click.echo("Debug is {}".format("on" if ctx.obj["DEBUG"] else "off"))213 click.echo(f"Debug is {'on' if ctx.obj['DEBUG'] else 'off'}")214215 result = runner.invoke(cli, ["sync"])216 assert result.exception is None217 assert result.output == "Debug is off\n"
45 unmodified lines
263 @click.argument("args", nargs=-1, type=click.UNPROCESSED)264 @click.option("--verbose", "-v", count=True)265 def cli(verbose, args):266 click.echo(f"Verbosity: {verbose}")267 click.echo("Args: {}".format("|".join(args)))267 click.echo(f"Args: {'|'.join(args)}")268269 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])270 assert not result.exception271 assert result.output.splitlines() == [
29 unmodified lines
modified:tests/test_defaults.py+2 added-2 removed
30 unmodified lines
31 @click.option(32 "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT33 )34 def cli(arg):35 for item in arg:36 click.echo("<{0[0]:d}|{0[1]:d}>".format(item))35 for a, b in arg:36 click.echo(f"<{a:d}|{b:d}>")3738 result = runner.invoke(cli, [])39 assert not result.exception40 assert result.output.splitlines() == ["<1|2>", "<3|4>"]
modified:tests/test_options.py+7 added-6 removed
42 unmodified lines
43def test_nargs_tup_composite_mult(runner):44 @click.command()45 @click.option("--item", type=(str, int), multiple=True)46 def copy(item):47 for item in item:48 click.echo("name={0[0]} id={0[1]:d}".format(item))47 for name, id in item:48 click.echo(f"name={name} id={id:d}")4950 result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])51 assert not result.exception52 assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]
367 unmodified lines
420 pass421422 result = runner.invoke(cmd, ["--help"],)423 assert result.exit_code == 0424 i = " " * 21425 assert (426 " -C, --config PATH Configuration file to use.\n"426 "{i}\n"427 "{i}If not given, the environment variable CONFIG_FILE is\n"428 "{i}consulted and used if set. If neither are given, a default\n"429 "{i}configuration file is loaded.".format(i=" " * 21)427 f"{i}\n"428 f"{i}If not given, the environment variable CONFIG_FILE is\n"429 f"{i}consulted and used if set. If neither are given, a default\n"430 f"{i}configuration file is loaded."431 ) in result.output432433434def test_argument_custom_class(runner):
123 unmodified lines
modified:tests/test_termui.py+2 added-2 removed
245 unmodified lines
246 def cli(f):247 click.echo(f.name)248249 result = runner.invoke(cli)250 assert result.output == "file [{0}]: \n{0}\n".format(__file__)250 assert result.output == f"file [{__file__}]: \n{__file__}\n"251252253def test_secho(runner):254 with runner.isolation() as outstreams:
98 unmodified lines
353 monkeypatch.setattr(354 click._termui_impl.msvcrt, "getwch", lambda: ordered_inputs.pop()355 )356 monkeypatch.setattr(click.termui, "_getchar", None)357 assert click.getchar() == special_key_char + key_char357 assert click.getchar() == f"{special_key_char}{key_char}"358359360@pytest.mark.parametrize(361 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)],
8 unmodified lines
modified:tests/test_testing.py+2 added-2 removed
123 unmodified lines
124 assert result.output == "hello world\n"125 assert not result.exception126127 result = runner.invoke(cli, color=True)128 assert result.output == "{}\n".format(click.style("hello world", fg="blue"))128 assert result.output == f"{click.style('hello world', fg='blue')}\n"129 assert not result.exception130131132def test_with_color_but_pause_not_blocking():
79 unmodified lines
212213def test_env():214 @click.command()215 def cli_env():216 click.echo("ENV={}".format(os.environ["TEST_CLICK_ENV"]))216 click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")217218 runner = CliRunner()219220 env_orig = dict(os.environ)
77 unmodified lines