apply pyupgrade --py36-plus
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 62f84aa · Browse files · 35 files·+204 added−233 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
35 files+204 added−233 removed
- tests:+57 added−67 removed
- other:+147 added−166 removed
Provenance
- Commit
b444e63- Tree
08b29d2- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
62f84aa
35 files changed+204 added−233 removed
modified:examples/aliases/aliases.py+3 added-3 removed
2 unmodified lines3 4 import click5 6 7-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()108 unmodified lines120 @cli.command()121 @pass_config122 def status(config):123 """Shows the status."""124- 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)138- click.echo("Added '{}' as alias for '{}'".format(alias_, cmd))138+ click.echo(f"Added '{alias_}' as alias for '{cmd}'")modified:examples/bashcompletion/bashcompletion.py+2 added-2 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))21+ click.echo(f"Environment variable: {envvar}")22 click.echo("Value: {}".format(os.environ[envvar]))23 24 25 @click.group(help="A group that holds a subcommand")12 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/cli.py+2 added-4 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- mod = __import__(43- "complex.commands.cmd_{}".format(name), None, None, ["cli"]44- )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+19 added-24 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")22 unmodified lines243 @processor244 def emboss_cmd(images):245 """Embosses an image."""246 for image in images:251- click.echo("Embossing '{}'".format(image.filename))247+ click.echo(f"Embossing '{image.filename}'")248 yield copy_filename(image.filter(ImageFilter.EMBOSS), image)249 250 251 @cli.command("sharpen")3 unmodified lines255 @processor256 def sharpen_cmd(images, factor):257 """Sharpens an image."""258 for image in images:263- click.echo("Sharpen '{}' by {}".format(image.filename, factor))259+ click.echo(f"Sharpen '{image.filename}' by {factor}")260 enhancer = ImageEnhance.Sharpness(image)261 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)262 263 13 unmodified lines277 if image is not None:278 yield image279 return280 285- click.echo("Paste '{}' on '{}'".format(to_paste.filename, image.filename))281+ click.echo(f"Paste '{to_paste.filename}' on '{image.filename}'")282 mask = None283 if to_paste.mode == "RGBA" or "transparency" in to_paste.info:284 mask = to_paste285 image.paste(to_paste, (left, right), mask)290- image.filename += "+{}".format(to_paste.filename)286+ image.filename += f"+{to_paste.filename}"287 yield image288 293- for image in imageiter:294- yield image289+ 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+9 added-9 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 56 unmodified lines81 click.echo("Cloning repo {} to {}".format(src, os.path.abspath(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+7 added-8 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():30 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+3 added-3 removed
42 unmodified lines43 raise click.BadParameter(44 'If a value is provided it needs to be the value "wat".',45 param_hint=["--foo"],46 )47- click.echo("count: {}".format(count))48- click.echo("foo: {}".format(foo))49- click.echo("url: {!r}".format(url))47+ click.echo(f"count: {count}")48+ click.echo(f"foo: {foo}")49+ click.echo(f"url: {url!r}")modified:src/click/_bashcomplete.py+1 added-1 removed
92 unmodified lines93 script = _completion_scripts.get(shell, COMPLETION_SCRIPT_BASH)94 return (95 script96 % {97- "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() + ";"270 unmodified linesmodified:src/click/_compat.py+4 added-4 removed
78 unmodified lines79 # https://bitbucket.org/pypy/pypy/issue/180380 return self._stream.isatty()81 82 83-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 270 unmodified lines358 359 def _wrap_io_open(file, mode, encoding, errors):360 """Handles not passing ``encoding`` and ``errors`` in binary mode."""361 if "b" in mode:362- return io.open(file, mode)362+ return open(file, mode)363 364- return io.open(file, mode, encoding=encoding, errors=errors)364+ return open(file, mode, encoding=encoding, errors=errors)365 366 367 def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):368 binary = "b" in mode67 unmodified lines436 f = _wrap_io_open(fd, mode, encoding, errors)437 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True438 439 440-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_filename167 unmodified linesmodified:src/click/_termui_impl.py+14 added-16 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.41 unmodified lines46 return None47 return hint48 49 51-class ProgressBar(object):50+class ProgressBar:51 def __init__(52 self,53 iterable,54 length=None,105 unmodified lines160 t //= 60161 hours = t % 24162 t //= 24163 if t > 0:165- return "{}d {:02}:{:02}:{:02}".format(t, hours, minutes, seconds)164+ return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"165 else:167- 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:173- pos += "/{}".format(self.length)172+ pos += f"/{self.length}"173 return pos174 175 def format_pct(self):176 return "{: 4}%".format(int(self.pct * 100))[1:]142 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:324- for rv in self.iter:325- yield rv323+ yield from self.iter324 else:325 for rv in self.iter:326 self.current_item = rv327 yield rv60 unmodified lines388 if not color:389 text = strip_ansi(text)390 391 c.stdin.write(text.encode(encoding, "replace"))394- except (IOError, KeyboardInterrupt):392+ except (OSError, KeyboardInterrupt):393 pass394 else:395 c.stdin.close()396 39 unmodified lines436 text = strip_ansi(text)437 stream.write(text)438 439 442-class Editor(object):440+class Editor:441 def __init__(self, editor=None, env=None, require_save=True, extension=".txt"):442 self.editor = editor443 self.env = env444 self.require_save = require_save8 unmodified lines453 return rv454 if WIN:455 return "notepad"456 for editor in "sensible-editor", "vim", "nano":459- if os.system("which {} >/dev/null 2>&1".format(editor)) == 0:457+ if os.system(f"which {editor} >/dev/null 2>&1") == 0:458 return editor459 return "vi"460 461 def edit_file(self, filename):12 unmodified lines474 shell=True,475 )476 exit_code = c.wait()477 if exit_code != 0:480- raise ClickException("{}: Editing failed!".format(editor))478+ raise ClickException(f"{editor}: Editing failed!")479 except OSError as e:482- raise ClickException("{}: Editing failed: {}".format(editor, e))480+ raise ClickException(f"{editor}: Editing failed: {e}")481 482 def edit(self, text):483 import tempfile484 91 unmodified lines576 return 1577 578 579 def _translate_ch_to_exc(ch):582- if ch == u"\x03":580+ if ch == "\x03":581 raise KeyboardInterrupt()584- if ch == u"\x04" and not WIN: # Unix-like, Ctrl+D582+ if ch == "\x04" and not WIN: # Unix-like, Ctrl+D583 raise EOFError()586- if ch == u"\x1a" and WIN: # Windows, Ctrl+Z584+ if ch == "\x1a" and WIN: # Windows, Ctrl+Z585 raise EOFError()586 587 588 if WIN:38 unmodified lines627 else:628 func = msvcrt.getwch629 630 rv = func()633- if rv in (u"\x00", u"\xe0"):631+ if rv in ("\x00", "\xe0"):632 # \x00 and \xe0 are control characters that indicate special key,633 # see above.634 rv += func()635 _translate_ch_to_exc(rv)36 unmodified linesmodified:src/click/_winconsole.py+4 added-5 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 #139 unmodified lines144 if GetLastError() == ERROR_OPERATION_ABORTED:145 # wait for KeyboardInterrupt146 time.sleep(0.1)147 if not rv:149- 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"166- 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 188-class ConsoleStream(object):187+class ConsoleStream:188 def __init__(self, text_stream, byte_stream):189 self._text_stream = text_stream190 self.buffer = byte_stream191 25 unmodified lines217 self.name, self.encoding218 )219 220 222-class WindowsChunkedWriter(object):221+class WindowsChunkedWriter:222 """223 Wraps a stream (such as stdout), acting as a transparent proxy for all224 attribute access apart from method 'write()' which we wrap to write in225 limited chunks due to a Windows limitation on binary console streams.85 unmodified linesmodified:src/click/core.py+21 added-23 removed
130 unmodified lines131 132 return sorted(declaration_order, key=sort_key)133 134 135-class ParameterSource(object):135+class ParameterSource:136 """This is an enum that indicates the source of a command line parameter.137 138 The enum has one of the following values: COMMANDLINE,139 ENVIRONMENT, DEFAULT, DEFAULT_MAP. The DEFAULT indicates that the23 unmodified lines163 "values are: {}".format(value, ",".join(cls.VALUES))164 )165 166 167-class Context(object):167+class Context:168 """The context is a special internal object that holds state relevant169 for the script execution at every single level. It's normally invisible170 to commands unless they opt-in to getting access to it.171 340 unmodified lines512 rv = ""513 if self.info_name is not None:514 rv = self.info_name515 if self.parent is not None:516- rv = "{} {}".format(self.parent.command_path, rv)516+ rv = f"{self.parent.command_path} {rv}"517 return rv.lstrip()518 519 def find_root(self):520 """Finds the outermost context."""144 unmodified lines665 """666 return self._source_by_paramname[name]667 668 669-class BaseCommand(object):669+class BaseCommand:670 """The base command implements the minimal API contract of commands.671 Most code will never use this as it does not implement a lot of useful672 functionality but it can act as the direct subclass of alternative673 parsing methods that do not depend on the Click parser.32 unmodified lines706 #: an optional dictionary with defaults passed to the context.707 self.context_settings = context_settings708 709 def __repr__(self):710- return "<{} {}>".format(self.__class__.__name__, self.name)710+ return f"<{self.__class__.__name__} {self.name}>"711 712 def get_usage(self, ctx):713 raise NotImplementedError("Base commands cannot get usage")714 41 unmodified lines756 args=None,757 prog_name=None,758 complete_var=None,759 standalone_mode=True,760- **extra760+ **extra,761 ):762 """This is the way to invoke a script with all the bells and763 whistles as a command line application. This will always terminate764 the application after a call. If this is not wanted, ``SystemExit``66 unmodified lines831 if not standalone_mode:832 raise833 e.show()834 sys.exit(e.exit_code)835- except IOError as e:835+ except OSError as e:836 if e.errno == errno.EPIPE:837 sys.stdout = PacifyFlushWrapper(sys.stdout)838 sys.stderr = PacifyFlushWrapper(sys.stderr)839 sys.exit(1)94 unmodified lines934 self.hidden = hidden935 self.deprecated = deprecated936 937 def __repr__(self):938- return "<{} {}>".format(self.__class__.__name__, self.name)938+ return f"<{self.__class__.__name__} {self.name}>"939 940 def get_usage(self, ctx):941 """Formats the usage line into a string and returns it.942 196 unmodified lines1139 no_args_is_help=None,1140 subcommand_metavar=None,1141 chain=False,1142 result_callback=None,1143- **attrs1143+ **attrs,1144 ):1145 Command.__init__(self, name, **attrs)1146 if no_args_is_help is None:1147 no_args_is_help = not invoke_without_command201 unmodified lines1349 # place.1350 if cmd is None and not ctx.resilient_parsing:1351 if split_opt(cmd_name)[0]:1352 self.parse_args(ctx, ctx.args)1353- ctx.fail("No such command '{}'.".format(original_cmd_name))1353+ ctx.fail(f"No such command '{original_cmd_name}'.")1354 1355 return cmd_name, cmd, args[1:]1356 1357 def get_command(self, ctx, cmd_name):98 unmodified lines1456 rv.update(source.list_commands(ctx))1457 return sorted(rv)1458 1459 1460-class Parameter(object):1460+class Parameter:1461 r"""A parameter to a command comes in two versions: they are either1462 :class:`Option`\s or :class:`Argument`\s. Other subclasses are currently1463 not supported by design as some of the internals for parsing are1464 intentionally not finalized.79 unmodified lines1544 self.envvar = envvar1545 self.autocompletion = autocompletion1546 1547 def __repr__(self):1548- return "<{} {}>".format(self.__class__.__name__, self.name)1548+ return f"<{self.__class__.__name__} {self.name}>"1549 1550 @property1551 def human_readable_name(self):1552 """Returns the human readable name of this parameter. This is the201 unmodified lines1754 help=None,1755 hidden=False,1756 show_choices=True,1757 show_envvar=False,1758- **attrs1758+ **attrs,1759 ):1760 default_is_missing = attrs.get("default", _missing) is _missing1761 Parameter.__init__(self, param_decls, type=type, **attrs)1762 121 unmodified lines1884 action = "store"1885 1886 if self.is_flag:1887 kwargs.pop("nargs", None)1888- action_const = "{}_const".format(action)1888+ action_const = f"{action}_const"1889 if self.is_bool_flag and self.secondary_opts:1890 parser.add_option(self.opts, action=action_const, const=True, **kwargs)1891 parser.add_option(1892 self.secondary_opts, action=action_const, const=False, **kwargs15 unmodified lines1908 rv, any_slashes = join_options(opts)1909 if any_slashes:1910 any_prefix_is_slash[:] = [True]1911 if not self.is_flag and not self.count:1912- rv += " {}".format(self.make_metavar())1912+ rv += f" {self.make_metavar()}"1913 return rv1914 1915 rv = [_write_opts(self.opts)]1916 if self.secondary_opts:4 unmodified lines1921 if self.show_envvar:1922 envvar = self.envvar1923 if envvar is None:1924 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1925- envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())1925+ envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"1926 if envvar is not None:1927 extra.append(1928 "env var: {}".format(1929 ", ".join(str(d) for d in envvar)2 unmodified lines1932 )1933 )1934 if self.default is not None and (self.show_default or ctx.show_default):1935 if isinstance(self.show_default, str):1936- default_string = "({})".format(self.show_default)1936+ default_string = f"({self.show_default})"1937 elif isinstance(self.default, (list, tuple)):1938 default_string = ", ".join(str(d) for d in self.default)1939 elif inspect.isfunction(self.default):1940 default_string = "(dynamic)"1941 else:1942 default_string = self.default1943- extra.append("default: {}".format(default_string))1943+ extra.append(f"default: {default_string}")1944 1945 if self.required:1946 extra.append("required")1947 if extra:1948- help = "{}[{}]".format(1949- "{} ".format(help) if help else "", "; ".join(extra)1950- )1948+ help = "{}[{}]".format(f"{help} " if help else "", "; ".join(extra))1949 1950 return ("; " if any_prefix_is_slash else " / ").join(rv), help1951 1952 def get_default(self, ctx):36 unmodified lines1989 rv = Parameter.resolve_envvar_value(self, ctx)1990 if rv is not None:1991 return rv1992 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1995- envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())1993+ envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"1994 return os.environ.get(envvar)1995 1996 def value_from_envvar(self, ctx):1997 rv = self.resolve_envvar_value(ctx)46 unmodified lines2044 var = self.type.get_metavar(self)2045 if not var:2046 var = self.name.upper()2047 if not self.required:2050- var = "[{}]".format(var)2048+ var = f"[{var}]"2049 if self.nargs != 1:2050 var += "..."2051 return var2052 23 unmodified linesmodified:src/click/exceptions.py+10 added-10 removed
26 unmodified lines27 28 def show(self, file=None):29 if file is None:30 file = get_text_stderr()31- 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 typically21 unmodified lines57 self.ctx.command_path, self.ctx.help_option_names[0]58 )59 if self.ctx is not None:60 color = self.ctx.color61- echo("{}\n{}".format(self.ctx.get_usage(), hint), file=file, color=color)62- echo("Error: {}".format(self.format_message()), file=file, color=color)61+ echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)62+ echo(f"Error: {self.format_message()}", file=file, color=color)63 64 65 class BadParameter(UsageError):66 """An exception that formats out a standardized error message for a23 unmodified lines90 param_hint = self.param_hint91 elif self.param is not None:92 param_hint = self.param.get_error_hint(self.ctx)93 else:94- return "Invalid value: {}".format(self.message)94+ return f"Invalid value: {self.message}"95 param_hint = _join_param_hints(param_hint)96 97- return "Invalid value for {}: {}".format(param_hint, self.message)97+ return f"Invalid value for {param_hint}: {self.message}"98 99 100 class MissingParameter(BadParameter):101 """Raised if click required an option or argument but it was not30 unmodified lines132 if self.param is not None:133 msg_extra = self.param.type.get_missing_message(self.param)134 if msg_extra:135 if msg:136- msg += ". {}".format(msg_extra)136+ msg += f". {msg_extra}"137 else:138 msg = msg_extra139 140 return "Missing {}{}{}{}".format(141 param_type,142- " {}".format(param_hint) if param_hint else "",142+ f" {param_hint}" if param_hint else "",143 ". " if msg else ".",144 msg or "",145 )146 147 def __str__(self):148 if self.message is None:149 param_name = self.param.name if self.param else None150- return "missing parameter: {}".format(param_name)150+ return f"missing parameter: {param_name}"151 else:152 return self.message153 154 5 unmodified lines160 """161 162 def __init__(self, option_name, message=None, possibilities=None, ctx=None):163 if message is None:164- message = "no such option: {}".format(option_name)164+ message = f"no such option: {option_name}"165 UsageError.__init__(self, message, ctx)166 self.option_name = option_name167 self.possibilities = possibilities168 46 unmodified lines215 self.ui_filename = ui_filename216 self.filename = filename217 218 def format_message(self):219- return "Could not open file {}: {}".format(self.ui_filename, self.message)219+ return f"Could not open file {self.ui_filename}: {self.message}"220 221 222 class Abort(RuntimeError):223 """An internal signalling exception that signals Click to abort."""13 unmodified linesmodified:src/click/formatting.py+1 added-1 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 185 unmodified linesmodified:src/click/parser.py+10 added-11 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]29 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 77 unmodified linesmodified:src/click/termui.py+3 added-3 removed
151 unmodified lines152 return default153 try:154 result = value_proc(value)155 except UsageError as e:156- 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:342 unmodified lines503 if fg:504 try:505 bits.append("\033[{}m".format(_ansi_colors[fg]))506 except KeyError:507- raise TypeError("Unknown color '{}'".format(fg))507+ raise TypeError(f"Unknown color '{fg}'")508 if bg:509 try:510 bits.append("\033[{}m".format(_ansi_colors[bg] + 10))511 except KeyError:512- raise TypeError("Unknown color '{}'".format(bg))512+ raise TypeError(f"Unknown color '{bg}'")513 if bold is not None:514 bits.append("\033[{}m".format(1 if bold else 22))515 if dim is not None:516 bits.append("\033[{}m".format(2 if dim else 22))172 unmodified linesmodified:src/click/testing.py+6 added-6 removed
10 unmodified lines11 from . import utils12 from ._compat import _find_binary_reader13 14 15-class EchoingStdin(object):15+class EchoingStdin:16 def __init__(self, input, output):17 self._input = input18 self._output = output19 37 unmodified lines57 58 return io.BytesIO(input)59 60 61-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=None37 unmodified lines103 type(self).__name__, repr(self.exception) if self.exception else "okay"104 )105 106 107-class CliRunner(object):107+class CliRunner:108 """The CLI runner provides functionality to invoke a Click command line109 script for unittesting purposes in a isolated environment. This only110 works in single-threaded systems without any concurrency as it changes the111 global interpreter state.78 unmodified lines190 191 def visible_input(prompt=None):192 sys.stdout.write(prompt or "")193 val = input.readline().rstrip("\r\n")194- sys.stdout.write("{}\n".format(val))194+ sys.stdout.write(f"{val}\n")195 sys.stdout.flush()196 return val197 198 def hidden_input(prompt=None):61 unmodified lines260 input=None,261 env=None,262 catch_exceptions=True,263 color=False,264- **extra264+ **extra,265 ):266 """Invokes a command in an isolated environment. The arguments are267 forwarded directly to the command line script, the `extra` keyword268 arguments are passed to the :meth:`~clickpkg.Command.main` function of89 unmodified lines358 finally:359 os.chdir(cwd)360 try:361 shutil.rmtree(t)362- except (OSError, IOError): # noqa: B014362+ except OSError: # noqa: B014363 passmodified:src/click/types.py+9 added-11 removed
10 unmodified lines11 from .utils import LazyFile12 from .utils import safecall13 14 15-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 name237 unmodified lines257 def convert(self, value, param, ctx):258 try:259 return int(value)260 except ValueError:261- self.fail("{} is not a valid integer".format(value), param, ctx)261+ self.fail(f"{value} is not a valid integer", param, ctx)262 263 def __repr__(self):264 return "INT"265 53 unmodified lines319 )320 return rv321 322 def __repr__(self):323- return "IntRange({}, {})".format(self.min, self.max)323+ return f"IntRange({self.min}, {self.max})"324 325 326 class FloatParamType(ParamType):327 name = "float"1 unmodified line329 def convert(self, value, param, ctx):330 try:331 return float(value)332 except ValueError:333- self.fail(334- "{} is not a valid floating point value".format(value), param, ctx335- )333+ self.fail(f"{value} is not a valid floating point value", param, ctx)334 335 def __repr__(self):336 return "FLOAT"337 53 unmodified lines391 )392 return rv393 394 def __repr__(self):397- return "FloatRange({}, {})".format(self.min, self.max)395+ return f"FloatRange({self.min}, {self.max})"396 397 398 class BoolParamType(ParamType):399 name = "boolean"5 unmodified lines405 if value in ("true", "t", "1", "yes", "y"):406 return True407 elif value in ("false", "f", "0", "no", "n"):408 return False411- self.fail("{} is not a valid boolean".format(value), param, ctx)409+ self.fail(f"{value} is not a valid boolean", param, ctx)410 411 def __repr__(self):412 return "BOOL"413 6 unmodified lines420 421 try:422 return uuid.UUID(value)423 except ValueError:426- self.fail("{} is not a valid UUID value".format(value), param, ctx)424+ self.fail(f"{value} is not a valid UUID value", param, ctx)425 426 def __repr__(self):427 return "UUID"428 74 unmodified lines503 ctx.call_on_close(safecall(f.close))504 else:505 ctx.call_on_close(safecall(f.flush))506 return f509- except (IOError, OSError) as e: # noqa: B014507+ except OSError as e: # noqa: B014508 self.fail(509 "Could not open file: {}: {}".format(510 filename_to_ui(value), get_strerror(e)511 ),198 unmodified lines710 if __debug__:711 try:712 if issubclass(ty, ParamType):713 raise AssertionError(716- "Attempted to use an uninstantiated parameter type ({}).".format(ty)714+ f"Attempted to use an uninstantiated parameter type ({ty})."715 )716 except TypeError:717 pass718 return FuncParamType(ty)33 unmodified linesmodified:src/click/utils.py+10 added-10 removed
70 unmodified lines71 72 return "".join(result)73 74 75-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)108- 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 )121- except (IOError, OSError) as e: # noqa: E402121+ except OSError as e: # noqa: E402122 from .exceptions import FileError123 124 raise FileError(self.name, hint=get_strerror(e))125 self._f = rv21 unmodified lines147 self.open()148 return iter(self._f)149 150 151-class KeepOpenFile(object):151+class KeepOpenFile:152 def __init__(self, file):153 self._file = file154 155 def __getattr__(self, name):69 unmodified lines225 if message is not None and not isinstance(message, echo_native_types):226 message = str(message)227 228 if nl:229- message = message or u""229+ message = message or ""230 if isinstance(message, str):231- message += u"\n"231+ message += "\n"232 else:233 message += b"\n"234 235 # If there is a message and the value looks like bytes, we manually39 unmodified lines275 ``'stdout'`` and ``'stderr'``276 """277 opener = binary_streams.get(name)278 if opener is None:279- raise TypeError("Unknown standard stream '{}'".format(name))279+ raise TypeError(f"Unknown standard stream '{name}'")280 return opener()281 282 283 def get_text_stream(name, encoding=None, errors="strict"):8 unmodified lines292 :param errors: overrides the default error mode.293 """294 opener = text_streams.get(name)295 if opener is None:296- raise TypeError("Unknown standard stream '{}'".format(name))296+ raise TypeError(f"Unknown standard stream '{name}'")297 return opener(encoding, errors)298 299 300 def open_file(117 unmodified lines418 _posixify(app_name),419 )420 421 422-class PacifyFlushWrapper(object):422+class PacifyFlushWrapper:423 """This wrapper is used to catch and suppress BrokenPipeErrors resulting424 from ``.flush()`` being called on broken pipe during the shutdown/final-GC425 of the Python interpreter. Notably ``.flush()`` is always called on426 ``sys.stdout`` and ``sys.stderr``. So as to have minimal impact on any6 unmodified lines433 434 def flush(self):435 try:436 self.wrapped.flush()437- except IOError as e:437+ except OSError as e:438 import errno439 440 if e.errno != errno.EPIPE:441 raise3 unmodified linesmodified:tests/test_arguments.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 import sys2 3 import pytest4 5 unmodified lines10 @click.argument("src", nargs=-1)11 @click.argument("dst")12 def copy(src, dst):13 click.echo("src={}".format("|".join(src)))15- click.echo("dst={}".format(dst))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):36- click.echo("name={}".format(name))35+ click.echo(f"name={name}")36 click.echo("point={0[0]}/{0[1]}".format(point))37 38 result = runner.invoke(copy, ["peter", "1", "2"])39 assert not result.exception49 unmodified lines89 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")90 91 runner.invoke(92 from_bytes,94- [u"Something outside of ASCII range: 林".encode("UTF-8")],93+ ["Something outside of ASCII range: 林".encode()],94 catch_exceptions=False,95 )96 97 108 unmodified lines206 def test_missing_arg(runner):207 @click.command()208 @click.argument("arg")209 def cmd(arg):211- click.echo("arg:{}".format(arg))210+ click.echo(f"arg:{arg}")211 212 result = runner.invoke(cmd, [])213 assert result.exit_code == 2214 assert "Missing argument 'ARG'." in result.output89 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+8 added-9 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()20 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()5 unmodified lines194 assert not result.exception195 assert result.output == "{}\n".format(not default)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()334 unmodified linesmodified:tests/test_chain.py+5 added-5 removed
75 unmodified lines76 77 @cli.command("sdist")78 @click.option("--format")79 def sdist(format):80- click.echo("sdist called {}".format(format))80+ click.echo(f"sdist called {format}")81 82 @cli.command("bdist")83 @click.option("--format")84 def bdist(format):85- click.echo("bdist called {}".format(format))85+ click.echo(f"bdist called {format}")86 87 result = runner.invoke(cli, ["bdist", "--format=1", "sdist", "--format=2"])88 assert not result.exception89 assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]6 unmodified lines96 97 @cli.command("sdist")98 @click.argument("format")99 def sdist(format):100- click.echo("sdist called {}".format(format))100+ click.echo(f"sdist called {format}")101 102 @cli.command("bdist")103 @click.argument("format")104 def bdist(format):105- click.echo("bdist called {}".format(format))105+ click.echo(f"bdist called {format}")106 107 result = runner.invoke(cli, ["bdist", "1", "sdist", "2"])108 assert not result.exception109 assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]81 unmodified lines191 192 @click.group(chain=True)193 @click.argument("arg")194 def cli(arg):195- click.echo("cli:{}".format(arg))195+ click.echo(f"cli:{arg}")196 197 @cli.command()198 def a():199 click.echo("a")31 unmodified linesmodified:tests/test_commands.py+3 added-4 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")153 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))266+ click.echo(f"Verbosity: {verbose}")267 click.echo("Args: {}".format("|".join(args)))268 269 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])270 assert not result.exception30 unmodified linesmodified:tests/test_compat.py+1 added-1 removed
21 unmodified lines22 23 24 @pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")25 def test_is_jupyter_kernel_output():26- 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+1 added-1 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.output27 unmodified linesmodified: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_options.py+5 added-6 removed
1-# -*- coding: utf-8 -*-1 import os2 import re3 4 import pytest5 unmodified lines10 @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):15- 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"36 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):60- 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.exception89- 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):111- 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",148- 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 405 unmodified linesmodified:tests/test_termui.py+8 added-9 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 159 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 )6 unmodified lines357 assert click.getchar() == special_key_char + key_char358 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+2 added-2 removed
57 unmodified lines58 def test_prompts():59 @click.command()60 @click.option("--foo", prompt=True)61 def test(foo):62- 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):72- 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.exception221 unmodified linesmodified:tests/test_utils.py+10 added-12 removed
10 unmodified lines11 12 13 def test_echo(runner):14 with runner.isolation() as outstreams:15- 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)17 unmodified lines37 def test_echo_custom_file():38 import io39 40 f = io.StringIO()41- click.echo(u"hello", file=f)42- 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"83- assert click.format_filename(u"/x/foo.txt") == "/x/foo.txt"84- 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:88- assert (89- click.format_filename(b"/x/foo\xff.txt", shorten=True) == u"foo\ufffd.txt"90- )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()195- assert out == "{}\n".format(text)193+ assert out == f"{text}\n"194 195 click.echo(styled_text, color=True)196 out, err = capfd.readouterr()199- 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()204- 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()209- 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):167 unmodified linesmodified:.pre-commit-config.yaml+1 added
1 unmodified line2 - repo: https://github.com/asottile/pyupgrade3 rev: v2.2.04 hooks:5 - id: pyupgrade6+ args: ["--py36-plus"]7 - repo: https://github.com/asottile/reorder_python_imports8 rev: v2.2.09 hooks:10 - id: reorder-python-imports18 unmodified lines