Skip to content
Myr

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

35 files+204 added−233 removed

modified:examples/aliases/aliases.py+3 added-3 removed
2 unmodified lines
34import click567class Config(object):7class Config:8 """The config in this example only holds aliases."""910 def __init__(self):11 self.path = os.getcwd()
108 unmodified lines
120@cli.command()121@pass_config122def status(config):123 """Shows the status."""124 click.echo("Status for {}".format(config.path))124 click.echo(f"Status for {config.path}")125126127@cli.command()128@pass_config
5 unmodified lines
134def alias(config, alias_, cmd, config_file):135 """Adds an alias to the specified configuration file."""136 config.add_alias(alias_, cmd)137 config.write_config(config_file)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 lines
1718@cli.command(help="A command to print environment variables")19@click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20def cmd1(envvar):21 click.echo("Environment variable: {}".format(envvar))21 click.echo(f"Environment variable: {envvar}")22 click.echo("Value: {}".format(os.environ[envvar]))232425@click.group(help="A group that holds a subcommand")
12 unmodified lines
3839@group.command(help="Choose a user")40@click.argument("user", type=click.STRING, autocompletion=list_users)41def subcmd(user):42 click.echo("Chosen user is {}".format(user))42 click.echo(f"Chosen user is {user}")434445cli.add_command(group)
modified:examples/colors/colors.py+3 added-7 removed
28 unmodified lines
2930 Give it a try!31 """32 for color in all_colors:33 click.echo(click.style("I am colored {}".format(color), fg=color))33 click.echo(click.style(f"I am colored {color}", fg=color))34 for color in all_colors:35 click.echo(36 click.style("I am colored {} and bold".format(color), fg=color, bold=True)37 )35 click.echo(click.style(f"I am colored {color} and bold", fg=color, bold=True))36 for color in all_colors:39 click.echo(40 click.style("I am reverse colored {}".format(color), fg=color, reverse=True)41 )37 click.echo(click.style(f"I am reverse colored {color}", fg=color, reverse=True))3839 click.echo(click.style("I am blinking", blink=True))40 click.echo(click.style("I am underlined", underline=True))
modified:examples/complex/complex/cli.py+2 added-4 removed
5 unmodified lines
67CONTEXT_SETTINGS = dict(auto_envvar_prefix="COMPLEX")8910class Environment(object):10class Environment:11 def __init__(self):12 self.verbose = False13 self.home = os.getcwd()14
23 unmodified lines
38 return rv3940 def get_command(self, ctx, name):41 try:42 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 lines
modified:examples/imagepipe/imagepipe.py+19 added-24 removed
58 unmodified lines
59 """6061 @processor62 def new_func(stream, *args, **kwargs):63 for item in stream:64 yield item65 for item in f(*args, **kwargs):66 yield item63 yield from stream64 yield from f(*args, **kwargs)6566 return update_wrapper(new_func, f)6768
17 unmodified lines
86 can be specified multiple times to load more than one image.87 """88 for image in images:89 try:92 click.echo("Opening '{}'".format(image))90 click.echo(f"Opening '{image}'")91 if image == "-":92 img = Image.open(click.get_binary_stdin())93 img.filename = "-"94 else:95 img = Image.open(image)96 yield img97 except Exception as e:100 click.echo("Could not open image '{}': {}".format(image, e), err=True)98 click.echo(f"Could not open image '{image}': {e}", err=True)99100101@cli.command("save")102@click.option(
8 unmodified lines
111 """Saves all processed images to a series of files."""112 for idx, image in enumerate(images):113 try:114 fn = filename.format(idx + 1)117 click.echo("Saving '{}' as '{}'".format(image.filename, fn))115 click.echo(f"Saving '{image.filename}' as '{fn}'")116 yield image.save(fn)117 except Exception as e:120 click.echo(121 "Could not save image '{}': {}".format(image.filename, e), err=True122 )118 click.echo(f"Could not save image '{image.filename}': {e}", err=True)119120121@cli.command("display")122@processor123def display_cmd(images):124 """Opens all images in an image viewer."""125 for image in images:130 click.echo("Displaying '{}'".format(image.filename))126 click.echo(f"Displaying '{image.filename}'")127 image.show()128 yield image129130
6 unmodified lines
137 the aspect ratio.138 """139 for image in images:140 w, h = (width or image.size[0], height or image.size[1])145 click.echo("Resizing '{}' to {}x{}".format(image.filename, w, h))141 click.echo(f"Resizing '{image.filename}' to {w}x{h}")142 image.thumbnail((w, h))143 yield image144145
9 unmodified lines
155156 if border is not None:157 for idx, val in enumerate(box):158 box[idx] = max(0, val - border)163 click.echo("Cropping '{}' by {}px".format(image.filename, border))159 click.echo(f"Cropping '{image.filename}' by {border}px")160 yield copy_filename(image.crop(box), image)161 else:162 yield image163
7 unmodified lines
171 if value in ("180", "-180"):172 return (Image.ROTATE_180, 180)173 if value in ("-90", "270", "l", "left"):174 return (Image.ROTATE_270, 270)179 raise click.BadParameter("invalid rotation '{}'".format(value))175 raise click.BadParameter(f"invalid rotation '{value}'")176177178def convert_flip(ctx, param, value):179 if value is None:
2 unmodified lines
182 if value in ("lr", "leftright"):183 return (Image.FLIP_LEFT_RIGHT, "left to right")184 if value in ("tb", "topbottom", "upsidedown", "ud"):185 return (Image.FLIP_LEFT_RIGHT, "top to bottom")190 raise click.BadParameter("invalid flip '{}'".format(value))186 raise click.BadParameter(f"invalid flip '{value}'")187188189@cli.command("transpose")190@click.option(
5 unmodified lines
196 """Transposes an image by either rotating or flipping it."""197 for image in images:198 if rotate is not None:199 mode, degrees = rotate204 click.echo("Rotate '{}' by {}deg".format(image.filename, degrees))200 click.echo(f"Rotate '{image.filename}' by {degrees}deg")201 image = copy_filename(image.transpose(mode), image)202 if flip is not None:203 mode, direction = flip208 click.echo("Flip '{}' {}".format(image.filename, direction))204 click.echo(f"Flip '{image.filename}' {direction}")205 image = copy_filename(image.transpose(mode), image)206 yield image207208
3 unmodified lines
212def blur_cmd(images, radius):213 """Applies gaussian blur."""214 blur = ImageFilter.GaussianBlur(radius)215 for image in images:220 click.echo("Blurring '{}' by {}px".format(image.filename, radius))216 click.echo(f"Blurring '{image.filename}' by {radius}px")217 yield copy_filename(image.filter(blur), image)218219220@cli.command("smoothen")
22 unmodified lines
243@processor244def 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)249250251@cli.command("sharpen")
3 unmodified lines
255@processor256def 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)262263
13 unmodified lines
277 if image is not None:278 yield image279 return280285 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 image288293 for image in imageiter:294 yield image289 yield from imageiter
modified:examples/naval/naval.py+5 added-5 removed
19 unmodified lines
20@ship.command("new")21@click.argument("name")22def ship_new(name):23 """Creates a new ship."""24 click.echo("Created ship {}".format(name))24 click.echo(f"Created ship {name}")252627@ship.command("move")28@click.argument("ship")
1 unmodified line
30@click.argument("y", type=float)31@click.option("--speed", metavar="KN", default=10, help="Speed in knots.")32def ship_move(ship, x, y, speed):33 """Moves SHIP to the new location X,Y."""34 click.echo("Moving ship {} to {},{} with speed {}".format(ship, x, y, speed))34 click.echo(f"Moving ship {ship} to {x},{y} with speed {speed}")353637@ship.command("shoot")38@click.argument("ship")39@click.argument("x", type=float)40@click.argument("y", type=float)41def ship_shoot(ship, x, y):42 """Makes SHIP fire to X,Y."""43 click.echo("Ship {} fires to {},{}".format(ship, x, y))43 click.echo(f"Ship {ship} fires to {x},{y}")444546@cli.group("mine")47def mine():
12 unmodified lines
60)61@click.option("ty", "--drifting", flag_value="drifting", help="Drifting mine.")62def mine_set(x, y, ty):63 """Sets a mine at a specific coordinate."""64 click.echo("Set {} mine at {},{}".format(ty, x, y))64 click.echo(f"Set {ty} mine at {x},{y}")656667@mine.command("remove")68@click.argument("x", type=float)69@click.argument("y", type=float)70def mine_remove(x, y):71 """Removes a mine at a specific coordinate."""72 click.echo("Removed mine at {},{}".format(x, y))72 click.echo(f"Removed mine at {x},{y}")
modified:examples/repo/repo.py+9 added-9 removed
3 unmodified lines
45import click678class Repo(object):8class Repo:9 def __init__(self, home):10 self.home = home11 self.config = {}12 self.verbose = False1314 def set_config(self, key, value):15 self.config[key] = value16 if self.verbose:17 click.echo(" config[{}] = {}".format(key, value), file=sys.stderr)17 click.echo(f" config[{key}] = {value}", file=sys.stderr)1819 def __repr__(self):20 return "<Repo {}>".format(self.home)20 return f"<Repo {self.home}>"212223pass_repo = click.make_pass_decorator(Repo)24
56 unmodified lines
81 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}")868788@cli.command()89@click.confirmation_option()
2 unmodified lines
92 """Deletes a repository.9394 This will throw away the current repository.95 """96 click.echo("Destroying repo {}".format(repo.home))96 click.echo(f"Destroying repo {repo.home}")97 click.echo("Deleted!")9899100@cli.command()
34 unmodified lines
135 if not message:136 marker = "# Files to be committed:"137 hint = ["", "", marker, "#"]138 for file in files:139 hint.append("# U {}".format(file))139 hint.append(f"# U {file}")140 message = click.edit("\n".join(hint))141 if message is None:142 click.echo("Aborted!")143 return
2 unmodified lines
146 click.echo("Aborted! Empty commit message")147 return148 else:149 msg = "\n".join(message)150 click.echo("Files to be committed: {}".format(files))151 click.echo("Commit message:\n{}".format(msg))150 click.echo(f"Files to be committed: {files}")151 click.echo(f"Commit message:\n{msg}")152153154@cli.command(short_help="Copies files.")155@click.option(
6 unmodified lines
162 """Copies one or multiple files to a new location. This copies all163 files from SRC to DST.164 """165 for fn in src:166 click.echo("Copy from {} -> {}".format(fn, dst))166 click.echo(f"Copy from {fn} -> {dst}")
modified:examples/termui/termui.py+7 added-8 removed
1# coding: utf-81import math2import random3import time4
9 unmodified lines
14@cli.command()15def colordemo():16 """Demonstrates ANSI color support."""17 for color in "red", "green", "blue":19 click.echo(click.style("I am colored {}".format(color), fg=color))20 click.echo(click.style("I am background colored {}".format(color), bg=color))18 click.echo(click.style(f"I am colored {color}", fg=color))19 click.echo(click.style(f"I am background colored {color}", bg=color))202122@cli.command()23def pager():
30 unmodified lines
54 process_slowly(item)5556 def show_item(item):57 if item is not None:59 return "Item #{}".format(item)58 return f"Item #{item}"5960 with click.progressbar(61 filter(items),62 label="Committing transaction",
6 unmodified lines
69 with click.progressbar(70 length=count,71 label="Counting",72 bar_template="%(label)s %(bar)s | %(info)s",74 fill_char=click.style(u"█", fg="cyan"),73 fill_char=click.style("█", fg="cyan"),74 empty_char=" ",75 ) as bar:76 for item in bar:77 process_slowly(item)
14 unmodified lines
92 with click.progressbar(93 length=count,94 show_percent=False,95 label="Slowing progress bar",97 fill_char=click.style(u"█", fg="green"),96 fill_char=click.style("█", fg="green"),97 ) as bar:98 for item in steps:99 time.sleep(item)100 bar.update(item)
16 unmodified lines
117@cli.command()118def edit():119 """Opens an editor with some text in it."""120 MARKER = "# Everything below is ignored\n"122 message = click.edit("\n\n{}".format(MARKER))121 message = click.edit(f"\n\n{MARKER}")122 if message is not None:123 msg = message.split(MARKER, 1)[0].rstrip("\n")124 if not msg:125 click.echo("Empty message!")126 else:128 click.echo("Message:\n{}".format(msg))127 click.echo(f"Message:\n{msg}")128 else:129 click.echo("You did not enter anything!")130131
38 unmodified lines
modified:examples/validation/validation.py+3 added-3 removed
42 unmodified lines
43 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 lines
93 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 lines
modified:src/click/_compat.py+4 added-4 removed
78 unmodified lines
79 # https://bitbucket.org/pypy/pypy/issue/180380 return self._stream.isatty()818283class _FixupStream(object):83class _FixupStream:84 """The new io interface needs more from streams than streams85 traditionally implement. As such, this fix-up code is necessary in86 some circumstances.87
270 unmodified lines
358359def _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)363364 return io.open(file, mode, encoding=encoding, errors=errors)364 return open(file, mode, encoding=encoding, errors=errors)365366367def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):368 binary = "b" in mode
67 unmodified lines
436 f = _wrap_io_open(fd, mode, encoding, errors)437 return _AtomicFile(f, tmp_filename, os.path.realpath(filename)), True438439440class _AtomicFile(object):440class _AtomicFile:441 def __init__(self, f, tmp_filename, real_filename):442 self._f = f443 self._tmp_filename = tmp_filename444 self._real_filename = real_filename
167 unmodified lines
modified:src/click/_termui_impl.py+14 added-16 removed
1# -*- coding: utf-8 -*-1"""2This module contains implementations for the termui module. To keep the3import time of Click down, some infrequently used functionality is4placed in this module and only imported as needed.
41 unmodified lines
46 return None47 return hint484951class ProgressBar(object):50class ProgressBar:51 def __init__(52 self,53 iterable,54 length=None,
105 unmodified lines
160 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 ""168169 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 pos174175 def format_pct(self):176 return "{: 4}%".format(int(self.pct * 100))[1:]
142 unmodified lines
319 if not self.entered:320 raise RuntimeError("You need to use progress bars in a with block.")321322 if self.is_hidden: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 rv
60 unmodified lines
388 if not color:389 text = strip_ansi(text)390391 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 lines
436 text = strip_ansi(text)437 stream.write(text)438439442class Editor(object):440class 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_save
8 unmodified lines
453 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"460461 def edit_file(self, filename):
12 unmodified lines
474 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}")481482 def edit(self, text):483 import tempfile484
91 unmodified lines
576 return 1577578579def _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()586587588if WIN:
38 unmodified lines
627 else:628 func = msvcrt.getwch629630 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 lines
modified: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 lines
144 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()}")149150 if buffer[0] == EOF:151 return 0152 return 2 * code_units_read.value
8 unmodified lines
161 if errno == ERROR_SUCCESS:162 return "ERROR_SUCCESS"163 elif errno == ERROR_NOT_ENOUGH_MEMORY:164 return "ERROR_NOT_ENOUGH_MEMORY"166 return "Windows error {}".format(errno)165 return f"Windows error {errno}"166167 def write(self, b):168 bytes_to_be_written = len(b)169 buf = get_buffer(b)
13 unmodified lines
183 raise OSError(self._get_error_message(GetLastError()))184 return bytes_written185186188class ConsoleStream(object):187class ConsoleStream:188 def __init__(self, text_stream, byte_stream):189 self._text_stream = text_stream190 self.buffer = byte_stream191
25 unmodified lines
217 self.name, self.encoding218 )219220222class WindowsChunkedWriter(object):221class 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 lines
modified:src/click/core.py+21 added-23 removed
130 unmodified lines
131132 return sorted(declaration_order, key=sort_key)133134135class ParameterSource(object):135class ParameterSource:136 """This is an enum that indicates the source of a command line parameter.137138 The enum has one of the following values: COMMANDLINE,139 ENVIRONMENT, DEFAULT, DEFAULT_MAP. The DEFAULT indicates that the
23 unmodified lines
163 "values are: {}".format(value, ",".join(cls.VALUES))164 )165166167class Context(object):167class 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 lines
512 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()518519 def find_root(self):520 """Finds the outermost context."""
144 unmodified lines
665 """666 return self._source_by_paramname[name]667668669class BaseCommand(object):669class 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 lines
706 #: an optional dictionary with defaults passed to the context.707 self.context_settings = context_settings708709 def __repr__(self):710 return "<{} {}>".format(self.__class__.__name__, self.name)710 return f"<{self.__class__.__name__} {self.name}>"711712 def get_usage(self, ctx):713 raise NotImplementedError("Base commands cannot get usage")714
41 unmodified lines
756 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 lines
831 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 lines
934 self.hidden = hidden935 self.deprecated = deprecated936937 def __repr__(self):938 return "<{} {}>".format(self.__class__.__name__, self.name)938 return f"<{self.__class__.__name__} {self.name}>"939940 def get_usage(self, ctx):941 """Formats the usage line into a string and returns it.942
196 unmodified lines
1139 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_command
201 unmodified lines
1349 # 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}'.")13541355 return cmd_name, cmd, args[1:]13561357 def get_command(self, ctx, cmd_name):
98 unmodified lines
1456 rv.update(source.list_commands(ctx))1457 return sorted(rv)145814591460class Parameter(object):1460class 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 lines
1544 self.envvar = envvar1545 self.autocompletion = autocompletion15461547 def __repr__(self):1548 return "<{} {}>".format(self.__class__.__name__, self.name)1548 return f"<{self.__class__.__name__} {self.name}>"15491550 @property1551 def human_readable_name(self):1552 """Returns the human readable name of this parameter. This is the
201 unmodified lines
1754 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 lines
1884 action = "store"18851886 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, **kwargs
15 unmodified lines
1908 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 rv19141915 rv = [_write_opts(self.opts)]1916 if self.secondary_opts:
4 unmodified lines
1921 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 lines
1932 )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}")19441945 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))19491950 return ("; " if any_prefix_is_slash else " / ").join(rv), help19511952 def get_default(self, ctx):
36 unmodified lines
1989 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)19951996 def value_from_envvar(self, ctx):1997 rv = self.resolve_envvar_value(ctx)
46 unmodified lines
2044 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 lines
modified:src/click/exceptions.py+10 added-10 removed
26 unmodified lines
2728 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)323334class UsageError(ClickException):35 """An internal exception that signals a usage error. This typically
21 unmodified lines
57 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)636465class BadParameter(UsageError):66 """An exception that formats out a standardized error message for a
23 unmodified lines
90 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)9697 return "Invalid value for {}: {}".format(param_hint, self.message)97 return f"Invalid value for {param_hint}: {self.message}"9899100class MissingParameter(BadParameter):101 """Raised if click required an option or argument but it was not
30 unmodified lines
132 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_extra139140 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 )146147 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.message153154
5 unmodified lines
160 """161162 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 lines
215 self.ui_filename = ui_filename216 self.filename = filename217218 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}"220221222class Abort(RuntimeError):223 """An internal signalling exception that signals Click to abort."""
13 unmodified lines
modified:src/click/formatting.py+1 added-1 removed
89 unmodified lines
9091 return "\n\n".join(rv)929394class HelpFormatter(object):94class HelpFormatter:95 """This class helps with formatting text-based help pages. It's96 usually just needed for very special internal cases, but it's also97 exposed so that developers can write their own fancy outputs.98
185 unmodified lines
modified:src/click/parser.py+10 added-11 removed
1# -*- coding: utf-8 -*-1"""2This module started out as largely a copy paste from the stdlib's3optparse module with the features removed that we do not need from4optparse because we implement them in Click on a higher level (for
77 unmodified lines
828384def _error_opt_args(nargs, opt):85 if nargs == 1:87 raise BadOptionUsage(opt, "{} option requires an argument".format(opt))88 raise BadOptionUsage(opt, "{} option requires {} arguments".format(opt, nargs))86 raise BadOptionUsage(opt, f"{opt} option requires an argument")87 raise BadOptionUsage(opt, f"{opt} option requires {nargs} arguments")888990def split_opt(opt):91 first = opt[:1]
29 unmodified lines
121 rv.append(arg)122 return rv123124126class Option(object):125class Option:126 def __init__(self, opts, dest, action=None, nargs=1, const=None, obj=None):127 self._short_opts = []128 self._long_opts = []129 self.prefixes = set()130131 for opt in opts:132 prefix, value = split_opt(opt)133 if not prefix:135 raise ValueError("Invalid start character for option ({})".format(opt))134 raise ValueError(f"Invalid start character for option ({opt})")135 self.prefixes.add(prefix[0])136 if len(prefix) == 1 and len(value) == 1:137 self._short_opts.append(opt)138 else:
24 unmodified lines
163 state.opts.setdefault(self.dest, []).append(self.const)164 elif self.action == "count":165 state.opts[self.dest] = state.opts.get(self.dest, 0) + 1166 else:168 raise ValueError("unknown action '{}'".format(self.action))167 raise ValueError(f"unknown action '{self.action}'")168 state.order.append(self.obj)169170172class Argument(object):171class Argument:172 def __init__(self, dest, nargs=1, obj=None):173 self.dest = dest174 self.nargs = nargs175 self.obj = obj
4 unmodified lines
180 if holes == len(value):181 value = None182 elif holes != 0:183 raise BadArgumentUsage(185 "argument {} takes {} values".format(self.dest, self.nargs)184 f"argument {self.dest} takes {self.nargs} values"185 )186 state.opts[self.dest] = value187 state.order.append(self.obj)188189191class ParsingState(object):190class ParsingState:191 def __init__(self, rargs):192 self.opts = {}193 self.largs = []194 self.rargs = rargs195 self.order = []196197199class OptionParser(object):198class OptionParser:199 """The option parser is an internal class that is ultimately used to200 parse options and arguments. It's modelled after optparse and brings201 a similar but vastly simplified API. It should generally not be used202 directly as the high level Click classes wrap it for you.
143 unmodified lines
346 value = tuple(state.rargs[:nargs])347 del state.rargs[:nargs]348349 elif explicit_value is not None:351 raise BadOptionUsage(opt, "{} option does not take a value".format(opt))350 raise BadOptionUsage(opt, f"{opt} option does not take a value")351352 else:353 value = None354
77 unmodified lines
modified:src/click/termui.py+3 added-3 removed
151 unmodified lines
152 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 lines
503 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 lines
modified:src/click/testing.py+6 added-6 removed
10 unmodified lines
11from . import utils12from ._compat import _find_binary_reader131415class EchoingStdin(object):15class EchoingStdin:16 def __init__(self, input, output):17 self._input = input18 self._output = output19
37 unmodified lines
5758 return io.BytesIO(input)596061class Result(object):61class Result:62 """Holds the captured result of an invoked CLI script."""6364 def __init__(65 self, runner, stdout_bytes, stderr_bytes, exit_code, exception, exc_info=None
37 unmodified lines
103 type(self).__name__, repr(self.exception) if self.exception else "okay"104 )105106107class CliRunner(object):107class 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 lines
190191 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 val197198 def hidden_input(prompt=None):
61 unmodified lines
260 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 of
89 unmodified lines
358 finally:359 os.chdir(cwd)360 try:361 shutil.rmtree(t)362 except (OSError, IOError): # noqa: B014362 except OSError: # noqa: B014363 pass
modified:src/click/types.py+9 added-11 removed
10 unmodified lines
11from .utils import LazyFile12from .utils import safecall131415class ParamType(object):15class ParamType:16 """Helper for converting values through types. The following is17 necessary for a valid type:1819 * it needs a name
237 unmodified lines
257 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)262263 def __repr__(self):264 return "INT"265
53 unmodified lines
319 )320 return rv321322 def __repr__(self):323 return "IntRange({}, {})".format(self.min, self.max)323 return f"IntRange({self.min}, {self.max})"324325326class FloatParamType(ParamType):327 name = "float"
1 unmodified line
329 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)334335 def __repr__(self):336 return "FLOAT"337
53 unmodified lines
391 )392 return rv393394 def __repr__(self):397 return "FloatRange({}, {})".format(self.min, self.max)395 return f"FloatRange({self.min}, {self.max})"396397398class BoolParamType(ParamType):399 name = "boolean"
5 unmodified lines
405 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)410411 def __repr__(self):412 return "BOOL"413
6 unmodified lines
420421 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)425426 def __repr__(self):427 return "UUID"428
74 unmodified lines
503 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 lines
710 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 lines
modified:src/click/utils.py+10 added-10 removed
70 unmodified lines
7172 return "".join(result)737475class LazyFile(object):75class LazyFile:76 """A lazy file works like a regular file but it does not fully open77 the file but it does perform some basic checks early to see if the78 filename parameter does make sense. This is useful for safely opening79 files for writing.
24 unmodified lines
104105 def __repr__(self):106 if self._f is not None:107 return repr(self._f)108 return "<unopened file '{}' {}>".format(self.name, self.mode)108 return f"<unopened file '{self.name}' {self.mode}>"109110 def open(self):111 """Opens the file if it's not yet open. This call might fail with112 a :exc:`FileError`. Not handling this error will produce an error
4 unmodified lines
117 try:118 rv, self.should_close = open_stream(119 self.name, self.mode, self.encoding, self.errors, atomic=self.atomic120 )121 except (IOError, OSError) as e: # noqa: E402121 except OSError as e: # noqa: E402122 from .exceptions import FileError123124 raise FileError(self.name, hint=get_strerror(e))125 self._f = rv
21 unmodified lines
147 self.open()148 return iter(self._f)149150151class KeepOpenFile(object):151class KeepOpenFile:152 def __init__(self, file):153 self._file = file154155 def __getattr__(self, name):
69 unmodified lines
225 if message is not None and not isinstance(message, echo_native_types):226 message = str(message)227228 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"234235 # If there is a message and the value looks like bytes, we manually
39 unmodified lines
275 ``'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()281282283def get_text_stream(name, encoding=None, errors="strict"):
8 unmodified lines
292 :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)298299300def open_file(
117 unmodified lines
418 _posixify(app_name),419 )420421422class PacifyFlushWrapper(object):422class 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 any
6 unmodified lines
433434 def flush(self):435 try:436 self.wrapped.flush()437 except IOError as e:437 except OSError as e:438 import errno439440 if e.errno != errno.EPIPE:441 raise
3 unmodified lines
modified:tests/test_arguments.py+4 added-5 removed
1# -*- coding: utf-8 -*-1import sys23import pytest4
5 unmodified lines
10 @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}")1516 result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])17 assert not result.exception18 assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]
12 unmodified lines
31 @click.command()32 @click.argument("name", nargs=1)33 @click.argument("point", nargs=2, type=click.INT)34 def copy(name, point):36 click.echo("name={}".format(name))35 click.echo(f"name={name}")36 click.echo("point={0[0]}/{0[1]}".format(point))3738 result = runner.invoke(copy, ["peter", "1", "2"])39 assert not result.exception
49 unmodified lines
89 monkeypatch.setattr(sys, "getdefaultencoding", lambda: "utf-8")9091 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 )9697
108 unmodified lines
206def 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}")211212 result = runner.invoke(cmd, [])213 assert result.exit_code == 2214 assert "Missing argument 'ARG'." in result.output
89 unmodified lines
modified:tests/test_bashcomplete.py-1 removed
1# -*- coding: utf-8 -*-1import pytest23import click4from click._bashcomplete import get_choices
495 unmodified lines
modified:tests/test_basic.py+8 added-9 removed
1# -*- coding: utf-8 -*-1import os2import uuid34import click
75 unmodified lines
80def test_basic_option(runner):81 @click.command()82 @click.option("--foo", default="no value")83 def cli(foo):85 click.echo(u"FOO:[{}]".format(foo))84 click.echo(f"FOO:[{foo}]")8586 result = runner.invoke(cli, [])87 assert not result.exception88 assert "FOO:[no value]" in result.output
9 unmodified lines
98 result = runner.invoke(cli, ["--foo="])99 assert not result.exception100 assert "FOO:[]" in result.output101103 result = runner.invoke(cli, [u"--foo=\N{SNOWMAN}"])102 result = runner.invoke(cli, ["--foo=\N{SNOWMAN}"])103 assert not result.exception105 assert u"FOO:[\N{SNOWMAN}]" in result.output104 assert "FOO:[\N{SNOWMAN}]" in result.output105106107def test_int_option(runner):108 @click.command()
20 unmodified lines
129 "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID130 )131 def cli(u):132 assert type(u) is uuid.UUID134 click.echo("U:[{}]".format(u))133 click.echo(f"U:[{u}]")134135 result = runner.invoke(cli, [])136 assert not result.exception137 assert "U:[ba122011-349f-423b-873b-9d6a79c688ab]" in result.output
11 unmodified lines
149 @click.command()150 @click.option("--foo", default=42, type=click.FLOAT)151 def cli(foo):152 assert type(foo) is float154 click.echo("FOO:[{}]".format(foo))153 click.echo(f"FOO:[{foo}]")154155 result = runner.invoke(cli, [])156 assert not result.exception157 assert "FOO:[42.0]" in result.output
22 unmodified lines
180 assert not result.exception181 assert result.output == "False\n"182 result = runner.invoke(cli, [])183 assert not result.exception185 assert result.output == "{}\n".format(default)184 assert result.output == f"{default}\n"185186 for default in True, False:187188 @click.command()
5 unmodified lines
194 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"199200201def test_boolean_conversion(runner):202 for default in True, False:
14 unmodified lines
217 assert result.output == "False\n"218219 result = runner.invoke(cli, [])220 assert not result.exception222 assert result.output == "{}\n".format(default)221 assert result.output == f"{default}\n"222223224def test_file_option(runner):225 @click.command()
334 unmodified lines
modified:tests/test_chain.py+5 added-5 removed
75 unmodified lines
7677 @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}")8182 @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}")8687 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 lines
9697 @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}")101102 @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}")106107 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 lines
191192 @click.group(chain=True)193 @click.argument("arg")194 def cli(arg):195 click.echo("cli:{}".format(arg))195 click.echo(f"cli:{arg}")196197 @cli.command()198 def a():199 click.echo("a")
31 unmodified lines
modified:tests/test_commands.py+3 added-4 removed
1# -*- coding: utf-8 -*-1import re23import click4
19 unmodified lines
2425 @cli.command()26 @click.option("--count", default=1)27 def test(count):29 click.echo("Count: {:d}".format(count))28 click.echo(f"Count: {count:d}")2930 @cli.command()31 @click.option("--count", default=1)32 @click.pass_context
67 unmodified lines
100def test_group_with_args(runner):101 @click.group()102 @click.argument("obj")103 def cli(obj):105 click.echo("obj={}".format(obj))104 click.echo(f"obj={obj}")105106 @cli.command()107 def move():108 click.echo("move")
153 unmodified lines
262 @click.command(context_settings=dict(ignore_unknown_options=True))263 @click.argument("args", nargs=-1, type=click.UNPROCESSED)264 @click.option("--verbose", "-v", count=True)265 def cli(verbose, args):267 click.echo("Verbosity: {}".format(verbose))266 click.echo(f"Verbosity: {verbose}")267 click.echo("Args: {}".format("|".join(args)))268269 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])270 assert not result.exception
30 unmodified lines
modified:tests/test_compat.py+1 added-1 removed
21 unmodified lines
222324@pytest.mark.xfail(WIN, reason="Jupyter not tested/supported on Windows")25def test_is_jupyter_kernel_output():26 class JupyterKernelFakeStream(object):26 class JupyterKernelFakeStream:27 pass2829 # implementation detail, aka cheapskate test30 JupyterKernelFakeStream.__module__ = "ipykernel.faked"
1 unmodified line
modified:tests/test_context.py+6 added-7 removed
1# -*- coding: utf-8 -*-1import pytest23import click4from click.core import ParameterSource567def test_ensure_context_objects(runner):9 class Foo(object):8 class Foo:9 def __init__(self):10 self.title = "default"1112 pass_foo = click.make_pass_decorator(Foo, ensure=True)
13 unmodified lines
26 assert result.output == "default\n"272829def test_get_context_objects(runner):31 class Foo(object):30 class Foo:31 def __init__(self):32 self.title = "default"3334 pass_foo = click.make_pass_decorator(Foo, ensure=True)
14 unmodified lines
49 assert result.output == "test\n"505152def test_get_context_objects_no_ensuring(runner):54 class Foo(object):53 class Foo:54 def __init__(self):55 self.title = "default"5657 pass_foo = click.make_pass_decorator(Foo)
14 unmodified lines
72 assert result.output == "test\n"737475def test_get_context_objects_missing(runner):77 class Foo(object):76 class Foo:77 pass7879 pass_foo = click.make_pass_decorator(Foo)80
49 unmodified lines
130 assert click.get_current_context(silent=True) is None131132133def test_context_meta(runner):135 LANG_KEY = "{}.lang".format(__name__)134 LANG_KEY = f"{__name__}.lang"135136 def set_language(value):137 click.get_current_context().meta[LANG_KEY] = value138
78 unmodified lines
217 Test to check that make_pass_decorator doesn't consume arguments based on218 invocation order.219 """220222 class Foo(object):221 class Foo:222 title = "foocmd"223224 pass_foo = click.make_pass_decorator(Foo)225
102 unmodified lines
modified:tests/test_defaults.py+1 added-1 removed
4 unmodified lines
5 @click.command()6 @click.option("--foo", default=42, type=click.FLOAT)7 def cli(foo):8 assert type(foo) is float9 click.echo("FOO:[{}]".format(foo))9 click.echo(f"FOO:[{foo}]")1011 result = runner.invoke(cli, [])12 assert not result.exception13 assert "FOO:[42.0]" in result.output
27 unmodified lines
modified:tests/test_formatting.py+4 added-5 removed
1# -*- coding: utf-8 -*-1import click234def test_basic_functionality(runner):
144 unmodified lines
149def test_formatting_usage_error(runner):150 @click.command()151 @click.argument("arg")152 def cmd(arg):154 click.echo("arg:{}".format(arg))153 click.echo(f"arg:{arg}")154155 result = runner.invoke(cmd, [])156 assert result.exit_code == 2157 assert result.output.splitlines() == [
48 unmodified lines
206207 @cmd.command()208 @click.argument("bar")209 def foo(bar):211 click.echo("foo:{}".format(bar))210 click.echo(f"foo:{bar}")211212 result = runner.invoke(cmd, ["foo"])213 assert result.exit_code == 2214 assert result.output.splitlines() == [
7 unmodified lines
222def test_formatting_usage_error_no_help(runner):223 @click.command(add_help_option=False)224 @click.argument("arg")225 def cmd(arg):227 click.echo("arg:{}".format(arg))226 click.echo(f"arg:{arg}")227228 result = runner.invoke(cmd, [])229 assert result.exit_code == 2230 assert result.output.splitlines() == [
6 unmodified lines
237def test_formatting_usage_custom_help(runner):238 @click.command(context_settings=dict(help_option_names=["--man"]))239 @click.argument("arg")240 def cmd(arg):242 click.echo("arg:{}".format(arg))241 click.echo(f"arg:{arg}")242243 result = runner.invoke(cmd, [])244 assert result.exit_code == 2245 assert result.output.splitlines() == [
107 unmodified lines
modified:tests/test_options.py+5 added-6 removed
1# -*- coding: utf-8 -*-1import os2import re34import pytest
5 unmodified lines
10 @click.command()11 @click.option("++foo", is_flag=True, help="das foo")12 @click.option("--bar", is_flag=True, help="das bar")13 def cli(foo, bar):15 click.echo("foo={} bar={}".format(foo, bar))14 click.echo(f"foo={foo} bar={bar}")1516 result = runner.invoke(cli, ["++foo", "--bar"])17 assert not result.exception18 assert result.output == "foo=True bar=True\n"
36 unmodified lines
55def test_counting(runner):56 @click.command()57 @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))58 def cli(v):60 click.echo("verbosity={:d}".format(v))59 click.echo(f"verbosity={v:d}")6061 result = runner.invoke(cli, ["-vvv"])62 assert not result.exception63 assert result.output == "verbosity=3\n"
20 unmodified lines
84 pass8586 result = runner.invoke(cli, [unknown_flag])87 assert result.exception89 assert "no such option: {}".format(unknown_flag) in result.output88 assert f"no such option: {unknown_flag}" in result.output899091def test_multiple_required(runner):92 @click.command()
13 unmodified lines
106def test_empty_envvar(runner):107 @click.command()108 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")109 def cli(mypath):111 click.echo("mypath: {}".format(mypath))110 click.echo(f"mypath: {mypath}")111112 result = runner.invoke(cli, [], env={"MYPATH": ""})113 assert result.exit_code == 0114 assert result.output == "mypath: None\n"
28 unmodified lines
143 result = runner.invoke(144 cmd,145 [],146 auto_envvar_prefix="TEST",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 lines
modified:tests/test_termui.py+8 added-9 removed
1# -*- coding: utf-8 -*-1import time23import pytest45import click._termui_impl6from click._compat import WIN7810class FakeClock(object):9class FakeClock:10 def __init__(self):11 self.now = time.time()1213 def advance_time(self, seconds=1):
26 unmodified lines
40 assert label in runner.invoke(cli, []).output414243def test_progressbar_length_hint(runner, monkeypatch):45 class Hinted(object):44 class Hinted:45 def __init__(self, n):46 self.items = list(range(n))4748 def __length_hint__(self):
72 unmodified lines
121def test_progressbar_format_pos(runner, pos, length):122 with _create_progress(length, length_known=length != 0, pos=pos) as progress:123 result = progress.format_pos()124 if progress.length_known:126 assert result == "{}/{}".format(pos, length)125 assert result == f"{pos}/{length}"126 else:127 assert result == str(pos)128129
159 unmodified lines
289290 @click.command()291 def cli():292 with click.progressbar(294 range(4), item_show_func=lambda x: "Custom {}".format(x)293 range(4), item_show_func=lambda x: f"Custom {x}"294 ) as progress:295 for _ in progress:296 fake_clock.advance_time()297 print("")
15 unmodified lines
313314 @click.command()315 def cli():316 with click.progressbar(318 length=6, item_show_func=lambda x: "Custom {}".format(x)317 length=6, item_show_func=lambda x: f"Custom {x}"318 ) as progress:319 while not progress.finished:320 fake_clock.advance_time()321 progress.update(2, progress.pos)
9 unmodified lines
331 assert "Custom 2" in lines[1]332 assert "Custom 4" in lines[2]333334336@pytest.mark.parametrize("key_char", (u"h", u"H", u"é", u"À", u" ", u"字", u"àH", u"àR"))335@pytest.mark.parametrize("key_char", ("h", "H", "é", "À", " ", "字", "àH", "àR"))336@pytest.mark.parametrize("echo", [True, False])337@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")338def test_getchar_windows(runner, monkeypatch, key_char, echo):339 monkeypatch.setattr(click._termui_impl.msvcrt, "getwche", lambda: key_char)
2 unmodified lines
342 assert click.getchar(echo) == key_char343344345@pytest.mark.parametrize(347 "special_key_char, key_char", [(u"\x00", "a"), (u"\x00", "b"), (u"\xe0", "c")]346 "special_key_char, key_char", [("\x00", "a"), ("\x00", "b"), ("\xe0", "c")]347)348@pytest.mark.skipif(349 not WIN, reason="Tests special character inputs using the msvcrt module."350)
6 unmodified lines
357 assert click.getchar() == special_key_char + key_char358359360@pytest.mark.parametrize(362 ("key_char", "exc"), [(u"\x03", KeyboardInterrupt), (u"\x1a", EOFError)],361 ("key_char", "exc"), [("\x03", KeyboardInterrupt), ("\x1a", EOFError)],362)363@pytest.mark.skipif(not WIN, reason="Tests user-input using the msvcrt module.")364def test_getchar_windows_exceptions(runner, monkeypatch, key_char, exc):365 monkeypatch.setattr(click._termui_impl.msvcrt, "getwch", lambda: key_char)
4 unmodified lines
modified:tests/test_testing.py+2 added-2 removed
57 unmodified lines
58def 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}")6364 runner = CliRunner()65 result = runner.invoke(test, input="wau wau\n")66 assert not result.exception
1 unmodified line
6869 @click.command()70 @click.option("--foo", prompt=True, hide_input=True)71 def test(foo):72 click.echo("foo={}".format(foo))72 click.echo(f"foo={foo}")7374 runner = CliRunner()75 result = runner.invoke(test, input="wau wau\n")76 assert not result.exception
221 unmodified lines
modified:tests/test_utils.py+10 added-12 removed
10 unmodified lines
111213def 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 lines
37def test_echo_custom_file():38 import io3940 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"434445@pytest.mark.parametrize(46 ("styles", "ref"),
32 unmodified lines
7980def test_filename_formatting():81 assert click.format_filename(b"foo.txt") == "foo.txt"82 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"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"8586 # 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"899091def test_prompts(runner):92 @click.command()
96 unmodified lines
189 assert styled_text == "\x1b[31mfoo\x1b[0m"190191 click.echo(styled_text, color=False)192 out, err = capfd.readouterr()195 assert out == "{}\n".format(text)193 assert out == f"{text}\n"194195 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"198199 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"203204 isatty = False205 click.echo(styled_text)206 out, err = capfd.readouterr()209 assert out == "{}\n".format(text)207 assert out == f"{text}\n"208209210@pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")211def test_echo_writing_to_standard_error(capfd, monkeypatch):
167 unmodified lines
modified:.pre-commit-config.yaml+1 added
1 unmodified line
2 - 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-imports
18 unmodified lines