Skip to content
Myr

apply pyupgrade

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 30b82bf · Browse files · 18 files+89 added−80 removed
This commit

State

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

Diff stats

18 files+89 added−80 removed

  • tests:+25 added−27 removed
  • other:+64 added−53 removed

18 files+89 added−80 removed

modified:examples/aliases/aliases.py+1 added-1 removed
137 unmodified lines
138def alias(config, alias_, cmd, config_file):139 """Adds an alias to the specified configuration file."""140 config.add_alias(alias_, cmd)141 config.write_config(config_file)142 click.echo("Added %s as alias for %s" % (alias_, cmd))142 click.echo("Added {} as alias for {}".format(alias_, cmd))
modified:examples/imagepipe/imagepipe.py+8 added-6 removed
95 unmodified lines
96 else:97 img = Image.open(image)98 yield img99 except Exception as e:100 click.echo('Could not open image "%s": %s' % (image, e), err=True)100 click.echo('Could not open image "{}": {}'.format(image, e), err=True)101102103@cli.command("save")104@click.option(
8 unmodified lines
113 """Saves all processed images to a series of files."""114 for idx, image in enumerate(images):115 try:116 fn = filename % (idx + 1)117 click.echo('Saving "%s" as "%s"' % (image.filename, fn))117 click.echo('Saving "{}" as "{}"'.format(image.filename, fn))118 yield image.save(fn)119 except Exception as e:120 click.echo('Could not save image "%s": %s' % (image.filename, e), err=True)120 click.echo(121 'Could not save image "{}": {}'.format(image.filename, e), err=True122 )123124125@cli.command("display")126@processor
77 unmodified lines
204 click.echo('Rotate "%s" by %ddeg' % (image.filename, degrees))205 image = copy_filename(image.transpose(mode), image)206 if flip is not None:207 mode, direction = flip206 click.echo('Flip "%s" %s' % (image.filename, direction))208 click.echo('Flip "{}" {}'.format(image.filename, direction))209 image = copy_filename(image.transpose(mode), image)210 yield image211212
45 unmodified lines
258@processor259def sharpen_cmd(images, factor):260 """Sharpens an image."""261 for image in images:260 click.echo('Sharpen "%s" by %f' % (image.filename, factor))262 click.echo('Sharpen "{}" by {:f}'.format(image.filename, factor))263 enhancer = ImageEnhance.Sharpness(image)264 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)265266
13 unmodified lines
280 if image is not None:281 yield image282 return283282 click.echo('Paste "%s" on "%s"' % (to_paste.filename, image.filename))284 click.echo('Paste "{}" on "{}"'.format(to_paste.filename, image.filename))285 mask = None286 if to_paste.mode == "RGBA" or "transparency" in to_paste.info:287 mask = to_paste288 image.paste(to_paste, (left, right), mask)
5 unmodified lines
modified:examples/naval/naval.py+4 added-4 removed
29 unmodified lines
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 %s to %s,%s with speed %s" % (ship, x, y, speed))34 click.echo("Moving ship {} to {},{} with speed {}".format(ship, x, y, 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 %s fires to %s,%s" % (ship, x, y))43 click.echo("Ship {} fires to {},{}".format(ship, 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 %s mine at %s,%s" % (ty, x, y))64 click.echo("Set {} mine at {},{}".format(ty, 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 %s,%s" % (x, y))72 click.echo("Removed mine at {},{}".format(x, y))
modified:examples/repo/repo.py+4 added-4 removed
12 unmodified lines
1314 def set_config(self, key, value):15 self.config[key] = value16 if self.verbose:17 click.echo(" config[%s] = %s" % (key, value), file=sys.stderr)17 click.echo(" config[{}] = {}".format(key, value), file=sys.stderr)1819 def __repr__(self):20 return "<Repo %r>" % self.home21
55 unmodified lines
77 of SRC and create that folder.78 """79 if dest is None:80 dest = posixpath.split(src)[-1] or "."81 click.echo("Cloning repo %s to %s" % (src, os.path.abspath(dest)))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 %s" % rev)
60 unmodified lines
146 click.echo("Aborted! Empty commit message")147 return148 else:149 msg = "\n".join(message)150 click.echo("Files to be committed: %s" % (files,))150 click.echo("Files to be committed: {}".format(files))151 click.echo("Commit message:\n" + msg)152153154@cli.command(short_help="Copies files.")
7 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 %s -> %s" % (fn, dst))166 click.echo("Copy from {} -> {}".format(fn, dst))
modified:src/click/_bashcomplete.py+1 added-1 removed
347 unmodified lines
348 args = cwords[1:]349350 for item in get_choices(cli, prog_name, args, incomplete):351 if item[1]:352 echo("%(arg)s\t%(desc)s" % {"arg": item[0], "desc": item[1]})352 echo("{arg}\t{desc}".format(arg=item[0], desc=item[1]))353 else:354 echo(item[0])355356 return True
19 unmodified lines
modified:src/click/_compat.py+1 added-1 removed
563 unmodified lines
564565 while True:566 tmp_filename = os.path.join(567 os.path.dirname(filename),568 ".__atomic-write%08x" % (random.randrange(1 << 32),),568 ".__atomic-write{:08x}".format(random.randrange(1 << 32)),569 )570 try:571 fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)572 break
218 unmodified lines
modified:src/click/_termui_impl.py+7 added-7 removed
414 unmodified lines
415 encoding = get_best_encoding(sys.stdout)416 with open_stream(filename, "wb")[0] as f:417 f.write(text.encode(encoding))418 try:419 os.system("%s %s" % (shlex_quote(cmd), shlex_quote(filename)))419 os.system("{} {}".format(shlex_quote(cmd), shlex_quote(filename)))420 finally:421 os.unlink(filename)422423
36 unmodified lines
460 else:461 environ = None462 try:463 c = subprocess.Popen(464 "%s %s" % (shlex_quote(editor), shlex_quote(filename)),464 "{} {}".format(shlex_quote(editor), shlex_quote(filename)),465 env=environ,466 shell=True,467 )468 exit_code = c.wait()469 if exit_code != 0:470 raise ClickException("%s: Editing failed!" % editor)471 except OSError as e:472 raise ClickException("%s: Editing failed: %s" % (editor, e))472 raise ClickException("{}: Editing failed: {}".format(editor, e))473474 def edit(self, text):475 import tempfile476
56 unmodified lines
533 null.close()534 elif WIN:535 if locate:536 url = _unquote_file(url)537 args = "explorer /select,%s" % (shlex_quote(url),)537 args = "explorer /select,{}".format(shlex_quote(url))538 else:539 args = 'start %s "" %s' % ("/WAIT" if wait else "", shlex_quote(url))539 args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex_quote(url))540 return os.system(args)541 elif CYGWIN:542 if locate:543 url = _unquote_file(url)544 args = "cygstart %s" % (shlex_quote(os.path.dirname(url)),)544 args = "cygstart {}".format(shlex_quote(os.path.dirname(url)))545 else:546 args = "cygstart %s %s" % ("-w" if wait else "", shlex_quote(url))546 args = "cygstart {} {}".format("-w" if wait else "", shlex_quote(url))547 return os.system(args)548549 try:550 if locate:
109 unmodified lines
modified:src/click/_winconsole.py+3 added-1 removed
221 unmodified lines
222 def isatty(self):223 return self.buffer.isatty()224225 def __repr__(self):226 return "<ConsoleStream name=%r encoding=%r>" % (self.name, self.encoding,)226 return "<ConsoleStream name={!r} encoding={!r}>".format(227 self.name, self.encoding228 )229230231class WindowsChunkedWriter(object):232 """
138 unmodified lines
modified:src/click/core.py+7 added-8 removed
377 unmodified lines
378 parent is not None379 and parent.auto_envvar_prefix is not None380 and self.info_name is not None381 ):382 auto_envvar_prefix = "%s_%s" % (383 parent.auto_envvar_prefix,384 self.info_name.upper(),382 auto_envvar_prefix = "{}_{}".format(383 parent.auto_envvar_prefix, self.info_name.upper(),384 )385 else:386 auto_envvar_prefix = auto_envvar_prefix.upper()387 if auto_envvar_prefix is not None:
286 unmodified lines
674 #: an optional dictionary with defaults passed to the context.675 self.context_settings = context_settings676677 def __repr__(self):679 return "<%s %s>" % (self.__class__.__name__, self.name)678 return "<{} {}>".format(self.__class__.__name__, self.name)679680 def get_usage(self, ctx):681 raise NotImplementedError("Base commands cannot get usage")682
825 unmodified lines
1508 self.envvar = envvar1509 self.autocompletion = autocompletion15101511 def __repr__(self):1513 return "<%s %s>" % (self.__class__.__name__, self.name)1512 return "<{} {}>".format(self.__class__.__name__, self.name)15131514 @property1515 def human_readable_name(self):1516 """Returns the human readable name of this parameter. This is the
364 unmodified lines
1881 if self.show_envvar:1882 envvar = self.envvar1883 if envvar is None:1884 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1886 envvar = "%s_%s" % (ctx.auto_envvar_prefix, self.name.upper())1885 envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())1886 if envvar is not None:1887 extra.append(1888 "env var: %s"1889 % (
15 unmodified lines
19051906 if self.required:1907 extra.append("required")1908 if extra:1910 help = "%s[%s]" % (help and help + " " or "", "; ".join(extra))1909 help = "{}[{}]".format(help and help + " " or "", "; ".join(extra))19101911 return ((any_prefix_is_slash and "; " or " / ").join(rv), help)19121913 def get_default(self, ctx):
36 unmodified lines
1950 rv = Parameter.resolve_envvar_value(self, ctx)1951 if rv is not None:1952 return rv1953 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1955 envvar = "%s_%s" % (ctx.auto_envvar_prefix, self.name.upper())1954 envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())1955 return os.environ.get(envvar)19561957 def value_from_envvar(self, ctx):1958 rv = self.resolve_envvar_value(ctx)
78 unmodified lines
modified:src/click/exceptions.py+5 added-6 removed
62 unmodified lines
63 file = get_text_stderr()64 color = None65 hint = ""66 if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:67 hint = 'Try "%s %s" for help.\n' % (68 self.ctx.command_path,69 self.ctx.help_option_names[0],67 hint = 'Try "{} {}" for help.\n'.format(68 self.ctx.command_path, self.ctx.help_option_names[0],69 )70 if self.ctx is not None:71 color = self.ctx.color72 echo(self.ctx.get_usage() + "\n%s" % hint, file=file, color=color)
31 unmodified lines
104 else:105 return "Invalid value: %s" % self.message106 param_hint = _join_param_hints(param_hint)107109 return "Invalid value for %s: %s" % (param_hint, self.message)108 return "Invalid value for {}: {}".format(param_hint, self.message)109110111class MissingParameter(BadParameter):112 """Raised if click required an option or argument but it was not
34 unmodified lines
147 msg += ". " + msg_extra148 else:149 msg = msg_extra150152 return "Missing %s%s%s%s" % (151 return "Missing {}{}{}{}".format(152 param_type,153 param_hint and " %s" % param_hint or "",154 msg and ". " or ".",155 msg or "",
76 unmodified lines
232 self.ui_filename = ui_filename233 self.filename = filename234235 def format_message(self):237 return "Could not open file %s: %s" % (self.ui_filename, self.message)236 return "Could not open file {}: {}".format(self.ui_filename, self.message)237238239class Abort(RuntimeError):240 """An internal signalling exception that signals Click to abort."""
13 unmodified lines
modified:src/click/parser.py+1 added-1 removed
223 unmodified lines
224 self.allow_interspersed_args = ctx.allow_interspersed_args225 self.ignore_unknown_options = ctx.ignore_unknown_options226 self._short_opt = {}227 self._long_opt = {}228 self._opt_prefixes = set(["-", "--"])228 self._opt_prefixes = {"-", "--"}229 self._args = []230231 def add_option(self, opts, dest, action=None, nargs=1, const=None, obj=None):232 """Adds a new option named `dest` to the parser. The destination
196 unmodified lines
modified:src/click/termui.py+1 added-1 removed
59 unmodified lines
60 prompt = text61 if type is not None and show_choices and isinstance(type, Choice):62 prompt += " (" + ", ".join(map(str, type.choices)) + ")"63 if default is not None and show_default:64 prompt = "%s [%s]" % (prompt, _format_default(default))64 prompt = "{} [{}]".format(prompt, _format_default(default))65 return prompt + suffix666768def _format_default(default):
613 unmodified lines
modified:src/click/testing.py+2 added-3 removed
106 unmodified lines
107 "\r\n", "\n"108 )109110 def __repr__(self):111 return "<%s %s>" % (112 type(self).__name__,113 self.exception and repr(self.exception) or "okay",111 return "<{} {}>".format(112 type(self).__name__, self.exception and repr(self.exception) or "okay",113 )114115116class CliRunner(object):
266 unmodified lines
modified:src/click/types.py+18 added-8 removed
192 unmodified lines
193 if normed_value in normed_choices:194 return normed_choices[normed_value]195196 self.fail(197 "invalid choice: %s. (choose from %s)" % (value, ", ".join(self.choices)),197 "invalid choice: {}. (choose from {})".format(198 value, ", ".join(self.choices)199 ),200 param,201 ctx,202 )203
96 unmodified lines
300 and rv > self.max301 ):302 if self.min is None:303 self.fail(302 "%s is bigger than the maximum valid value %s." % (rv, self.max),304 "{} is bigger than the maximum valid value {}.".format(305 rv, self.max306 ),307 param,308 ctx,309 )310 elif self.max is None:
12 unmodified lines
323 )324 return rv325326 def __repr__(self):323 return "IntRange(%r, %r)" % (self.min, self.max)327 return "IntRange({!r}, {!r})".format(self.min, self.max)328329330class FloatParamType(ParamType):331 name = "float"
38 unmodified lines
370 and rv > self.max371 ):372 if self.min is None:373 self.fail(370 "%s is bigger than the maximum valid value %s." % (rv, self.max),374 "{} is bigger than the maximum valid value {}.".format(375 rv, self.max376 ),377 param,378 ctx,379 )380 elif self.max is None:
12 unmodified lines
393 )394 return rv395396 def __repr__(self):391 return "FloatRange(%r, %r)" % (self.min, self.max)397 return "FloatRange({!r}, {!r})".format(self.min, self.max)398399400class BoolParamType(ParamType):401 name = "boolean"
200 unmodified lines
602 except OSError:603 if not self.exists:604 return self.coerce_path_result(rv)605 self.fail(600 '%s "%s" does not exist.' % (self.path_type, filename_to_ui(value)),606 '{} "{}" does not exist.'.format(607 self.path_type, filename_to_ui(value)608 ),609 param,610 ctx,611 )612613 if not self.file_okay and stat.S_ISREG(st.st_mode):614 self.fail(607 '%s "%s" is a file.' % (self.path_type, filename_to_ui(value)),615 '{} "{}" is a file.'.format(self.path_type, filename_to_ui(value)),616 param,617 ctx,618 )619 if not self.dir_okay and stat.S_ISDIR(st.st_mode):620 self.fail(613 '%s "%s" is a directory.' % (self.path_type, filename_to_ui(value)),621 '{} "{}" is a directory.'.format(622 self.path_type, filename_to_ui(value)623 ),624 param,625 ctx,626 )627 if self.writable and not os.access(value, os.W_OK):
126 unmodified lines
modified:src/click/utils.py+1 added-1 removed
111 unmodified lines
112113 def __repr__(self):114 if self._f is not None:115 return repr(self._f)116 return "<unopened file %r %s>" % (self.name, self.mode)116 return "<unopened file {!r} {}>".format(self.name, self.mode)117118 def open(self):119 """Opens the file if it's not yet open. This call might fail with120 a :exc:`FileError`. Not handling this error will produce an error
335 unmodified lines
modified:tests/test_imports.py+22 added-24 removed
27 unmodified lines
28import json29click.echo(json.dumps(rv))30"""3132ALLOWED_IMPORTS = set(33 [34 "weakref",35 "os",36 "struct",37 "collections",38 "sys",39 "contextlib",40 "functools",41 "stat",42 "re",43 "codecs",44 "inspect",45 "itertools",46 "io",47 "threading",48 "colorama",49 "errno",50 "fcntl",51 "datetime",52 "pipes",53 "shlex",54 ]32ALLOWED_IMPORTS = {33 "weakref",34 "os",35 "struct",36 "collections",37 "sys",38 "contextlib",39 "functools",40 "stat",41 "re",42 "codecs",43 "inspect",44 "itertools",45 "io",46 "threading",47 "colorama",48 "errno",49 "fcntl",50 "datetime",51 "pipes",52 "shlex",53}55)5455if WIN:56 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"])57
15 unmodified lines
modified:tests/test_options.py+2 added-2 removed
11 unmodified lines
12 @click.command()13 @click.option("++foo", is_flag=True, help="das foo")14 @click.option("--bar", is_flag=True, help="das bar")15 def cli(foo, bar):16 click.echo("foo=%s bar=%s" % (foo, bar))16 click.echo("foo={} bar={}".format(foo, bar))1718 result = runner.invoke(cli, ["++foo", "--bar"])19 assert not result.exception20 assert result.output == "foo=True bar=True\n"
68 unmodified lines
89 pass9091 result = runner.invoke(cli, [unknown_flag])92 assert result.exception93 assert "no such option: {0}".format(unknown_flag) in result.output93 assert "no such option: {}".format(unknown_flag) in result.output949596def test_multiple_required(runner):97 @click.command()
464 unmodified lines
modified:tests/test_termui.py+1 added-1 removed
121 unmodified lines
122def test_progressbar_format_pos(runner, pos, length):123 with _create_progress(length, length_known=length != 0, pos=pos) as progress:124 result = progress.format_pos()125 if progress.length_known:126 assert result == "%s/%s" % (pos, length)126 assert result == "{}/{}".format(pos, length)127 else:128 assert result == str(pos)129130
192 unmodified lines