manual cleanup
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 f8f02bf · Browse files · 34 files·+346 added−390 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
34 files+346 added−390 removed
- tests:+103 added−164 removed
- other:+243 added−226 removed
Provenance
- Commit
718485b- Tree
0fa1b49- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
f8f02bf
34 files changed+346 added−390 removed
modified:examples/aliases/aliases.py+3 added-3 removed
67 unmodified lines68 if not matches:69 return None70 elif len(matches) == 1:71 return click.Group.get_command(self, ctx, matches[0])72- ctx.fail("Too many matches: %s" % ", ".join(sorted(matches)))72+ ctx.fail("Too many matches: {}".format(", ".join(sorted(matches))))73 74 75 def read_config(ctx, param, value):76 """Callback that is used whenever --config is passed. We use this to47 unmodified lines124 @cli.command()125 @pass_config126 def status(config):127 """Shows the status."""128- click.echo("Status for %s" % config.path)128+ click.echo("Status for {}".format(config.path))129 130 131 @cli.command()132 @pass_config5 unmodified lines138 def 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 {} as alias for {}".format(alias_, cmd))142+ click.echo("Added '{}' as alias for '{}'".format(alias_, cmd))modified:examples/bashcompletion/bashcompletion.py+3 added-3 removed
16 unmodified lines17 18 @cli.command(help="A command to print environment variables")19 @click.argument("envvar", type=click.STRING, autocompletion=get_env_vars)20 def cmd1(envvar):21- click.echo("Environment variable: %s" % envvar)22- click.echo("Value: %s" % os.environ[envvar])21+ click.echo("Environment variable: {}".format(envvar))22+ click.echo("Value: {}".format(os.environ[envvar]))23 24 25 @click.group(help="A group that holds a subcommand")26 def group():11 unmodified lines38 39 @group.command(help="Choose a user")40 @click.argument("user", type=click.STRING, autocompletion=list_users)41 def subcmd(user):42- click.echo("Chosen user is %s" % user)42+ click.echo("Chosen user is {}".format(user))43 44 45 cli.add_command(group)modified:examples/colors/colors.py+5 added-3 removed
28 unmodified lines29 30 Give it a try!31 """32 for color in all_colors:33- click.echo(click.style("I am colored %s" % color, fg=color))33+ click.echo(click.style("I am colored {}".format(color), fg=color))34 for color in all_colors:35- click.echo(click.style("I am colored %s and bold" % color, fg=color, bold=True))35+ click.echo(36+ click.style("I am colored {} and bold".format(color), fg=color, bold=True)37+ )38 for color in all_colors:39 click.echo(38- click.style("I am reverse colored %s" % color, fg=color, reverse=True)40+ click.style("I am reverse colored {}".format(color), fg=color, reverse=True)41 )42 43 click.echo(click.style("I am blinking", blink=True))44 click.echo(click.style("I am underlined", underline=True))modified:examples/complex/complex/cli.py+3 added-1 removed
39 unmodified lines40 def get_command(self, ctx, name):41 try:42 if sys.version_info[0] == 2:43 name = name.encode("ascii", "replace")44- mod = __import__("complex.commands.cmd_" + name, None, None, ["cli"])44+ mod = __import__(45+ "complex.commands.cmd_{}".format(name), None, None, ["cli"]46+ )47 except ImportError:48 return49 return mod.cli50 14 unmodified linesmodified:examples/imagepipe/imagepipe.py+21 added-20 removed
87 unmodified lines88 can be specified multiple times to load more than one image.89 """90 for image in images:91 try:92- click.echo('Opening "%s"' % image)92+ click.echo("Opening '{}'".format(image))93 if image == "-":94 img = Image.open(click.get_binary_stdin())95 img.filename = "-"96 else:97 img = Image.open(image)98 yield img99 except Exception as e:100- click.echo('Could not open image "{}": {}'.format(image, e), err=True)100+ click.echo("Could not open image '{}': {}".format(image, e), err=True)101 102 103 @cli.command("save")104 @click.option(105 "--filename",106- default="processed-%04d.png",106+ default="processed-{:04}.png",107 type=click.Path(),108 help="The format for the filename.",109 show_default=True,110 )1 unmodified line112 def save_cmd(images, filename):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 "{}" as "{}"'.format(image.filename, fn))116+ fn = filename.format(idx + 1)117+ click.echo("Saving '{}' as '{}'".format(image.filename, fn))118 yield image.save(fn)119 except Exception as e:120 click.echo(121- 'Could not save image "{}": {}'.format(image.filename, e), err=True121+ "Could not save image '{}': {}".format(image.filename, e), err=True122 )123 124 125 @cli.command("display")126 @processor127 def display_cmd(images):128 """Opens all images in an image viewer."""129 for image in images:130- click.echo('Displaying "%s"' % image.filename)130+ click.echo("Displaying '{}'".format(image.filename))131 image.show()132 yield image133 134 6 unmodified lines141 the aspect ratio.142 """143 for image in images:144 w, h = (width or image.size[0], height or image.size[1])145- click.echo('Resizing "%s" to %dx%d' % (image.filename, w, h))145+ click.echo("Resizing '{}' to {}x{}".format(image.filename, w, h))146 image.thumbnail((w, h))147 yield image148 149 9 unmodified lines159 160 if border is not None:161 for idx, val in enumerate(box):162 box[idx] = max(0, val - border)163- click.echo('Cropping "%s" by %dpx' % (image.filename, border))163+ click.echo("Cropping '{}' by {}px".format(image.filename, border))164 yield copy_filename(image.crop(box), image)165 else:166 yield image167 7 unmodified lines175 if value in ("180", "-180"):176 return (Image.ROTATE_180, 180)177 if value in ("-90", "270", "l", "left"):178 return (Image.ROTATE_270, 270)179- raise click.BadParameter('invalid rotation "%s"' % value)179+ raise click.BadParameter("invalid rotation '{}'".format(value))180 181 182 def convert_flip(ctx, param, value):183 if value is None:2 unmodified lines186 if value in ("lr", "leftright"):187 return (Image.FLIP_LEFT_RIGHT, "left to right")188 if value in ("tb", "topbottom", "upsidedown", "ud"):189 return (Image.FLIP_LEFT_RIGHT, "top to bottom")190- raise click.BadParameter('invalid flip "%s"' % value)190+ raise click.BadParameter("invalid flip '{}'".format(value))191 192 193 @cli.command("transpose")194 @click.option(5 unmodified lines200 """Transposes an image by either rotating or flipping it."""201 for image in images:202 if rotate is not None:203 mode, degrees = rotate204- click.echo('Rotate "%s" by %ddeg' % (image.filename, degrees))204+ click.echo("Rotate '{}' by {}deg".format(image.filename, degrees))205 image = copy_filename(image.transpose(mode), image)206 if flip is not None:207 mode, direction = flip208- click.echo('Flip "{}" {}'.format(image.filename, direction))208+ click.echo("Flip '{}' {}".format(image.filename, direction))209 image = copy_filename(image.transpose(mode), image)210 yield image211 212 3 unmodified lines216 def blur_cmd(images, radius):217 """Applies gaussian blur."""218 blur = ImageFilter.GaussianBlur(radius)219 for image in images:220- click.echo('Blurring "%s" by %dpx' % (image.filename, radius))220+ click.echo("Blurring '{}' by {}px".format(image.filename, radius))221 yield copy_filename(image.filter(blur), image)222 223 224 @cli.command("smoothen")8 unmodified lines233 def smoothen_cmd(images, iterations):234 """Applies a smoothening filter."""235 for image in images:236 click.echo(237- 'Smoothening "%s" %d time%s'238- % (image.filename, iterations, iterations != 1 and "s" or "",)237+ "Smoothening '{}' {} time{}".format(238+ image.filename, iterations, "s" if iterations != 1 else ""239+ )240 )241 for _ in range(iterations):242 image = copy_filename(image.filter(ImageFilter.BLUR), image)243 yield image3 unmodified lines247 @processor248 def emboss_cmd(images):249 """Embosses an image."""250 for image in images:250- click.echo('Embossing "%s"' % image.filename)251+ click.echo("Embossing '{}'".format(image.filename))252 yield copy_filename(image.filter(ImageFilter.EMBOSS), image)253 254 255 @cli.command("sharpen")3 unmodified lines259 @processor260 def sharpen_cmd(images, factor):261 """Sharpens an image."""262 for image in images:262- click.echo('Sharpen "{}" by {:f}'.format(image.filename, factor))263+ click.echo("Sharpen '{}' by {}".format(image.filename, factor))264 enhancer = ImageEnhance.Sharpness(image)265 yield copy_filename(enhancer.enhance(max(1.0, factor)), image)266 267 13 unmodified lines281 if image is not None:282 yield image283 return284 284- click.echo('Paste "{}" on "{}"'.format(to_paste.filename, image.filename))285+ click.echo("Paste '{}' on '{}'".format(to_paste.filename, image.filename))286 mask = None287 if to_paste.mode == "RGBA" or "transparency" in to_paste.info:288 mask = to_paste289 image.paste(to_paste, (left, right), mask)289- image.filename += "+" + to_paste.filename290+ image.filename += "+{}".format(to_paste.filename)291 yield image292 293 for image in imageiter:294 yield imagemodified:examples/naval/naval.py+1 added-1 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 %s" % name)24+ click.echo("Created ship {}".format(name))25 26 27 @ship.command("move")28 @click.argument("ship")44 unmodified linesmodified:examples/repo/repo.py+7 added-7 removed
15 unmodified lines16 if self.verbose:17 click.echo(" config[{}] = {}".format(key, value), file=sys.stderr)18 19 def __repr__(self):20- return "<Repo %r>" % self.home20+ return "<Repo {}>".format(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 %s" % rev)85+ click.echo("Checking out revision {}".format(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 %s" % repo.home)96+ click.echo("Destroying repo {}".format(repo.home))97 click.echo("Deleted!")98 99 100 @cli.command()16 unmodified lines117 @click.option(118 "--message",119 "-m",120 multiple=True,121- help="The commit message. If provided multiple times each "122- "argument gets converted into a new line.",121+ help="The commit message. If provided multiple times each"122+ " argument gets converted into a new line.",123 )124 @click.argument("files", nargs=-1, type=click.Path())125 @pass_repo126 def commit(repo, files, message):8 unmodified lines135 if not message:136 marker = "# Files to be committed:"137 hint = ["", "", marker, "#"]138 for file in files:139- hint.append("# U %s" % file)139+ hint.append("# U {}".format(file))140 message = click.edit("\n".join(hint))141 if message is None:142 click.echo("Aborted!")143 return3 unmodified lines147 return148 else:149 msg = "\n".join(message)150 click.echo("Files to be committed: {}".format(files))151- click.echo("Commit message:\n" + msg)151+ click.echo("Commit message:\n{}".format(msg))152 153 154 @cli.command(short_help="Copies files.")155 @click.option(11 unmodified linesmodified:examples/termui/termui.py+6 added-6 removed
14 unmodified lines15 @cli.command()16 def colordemo():17 """Demonstrates ANSI color support."""18 for color in "red", "green", "blue":19- click.echo(click.style("I am colored %s" % color, fg=color))20- click.echo(click.style("I am background colored %s" % color, bg=color))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))21 22 23 @cli.command()24 def pager():25 """Demonstrates using the pager."""26 lines = []27 for x in range(200):28- lines.append("%s. Hello World!" % click.style(str(x), fg="green"))28+ lines.append("{}. Hello World!".format(click.style(str(x), fg="green")))29 click.echo_via_pager("\n".join(lines))30 31 32 @cli.command()22 unmodified lines55 process_slowly(item)56 57 def show_item(item):58 if item is not None:59- return "Item #%d" % item59+ return "Item #{}".format(item)60 61 with click.progressbar(62 filter(items),63 label="Committing transaction",54 unmodified lines118 @cli.command()119 def edit():120 """Opens an editor with some text in it."""121 MARKER = "# Everything below is ignored\n"122- message = click.edit("\n\n" + MARKER)122+ message = click.edit("\n\n{}".format(MARKER))123 if message is not None:124 msg = message.split(MARKER, 1)[0].rstrip("\n")125 if not msg:126 click.echo("Empty message!")127 else:128- click.echo("Message:\n" + msg)128+ click.echo("Message:\n{}".format(msg))129 else:130 click.echo("You did not enter anything!")131 132 38 unmodified linesmodified:examples/validation/validation.py+5 added-5 removed
18 unmodified lines19 if not isinstance(value, tuple):20 value = urlparse.urlparse(value)21 if value.scheme not in ("http", "https"):22 self.fail(23- "invalid URL scheme (%s). Only HTTP URLs are "24- "allowed" % value.scheme,23+ "invalid URL scheme ({}). Only HTTP URLs are"24+ " allowed".format(value.scheme),25 param,26 ctx,27 )28 return value17 unmodified lines46 raise click.BadParameter(47 'If a value is provided it needs to be the value "wat".',48 param_hint=["--foo"],49 )50- click.echo("count: %s" % count)51- click.echo("foo: %s" % foo)52- click.echo("url: %s" % repr(url))50+ click.echo("count: {}".format(count))51+ click.echo("foo: {}".format(foo))52+ click.echo("url: {!r}".format(url))modified:src/click/_bashcomplete.py+1 added-1 removed
96 unmodified lines97 script = _completion_scripts.get(shell, COMPLETION_SCRIPT_BASH)98 return (99 script100 % {101- "complete_func": "_%s_completion" % cf_name,101+ "complete_func": "_{}_completion".format(cf_name),102 "script_names": prog_name,103 "autocomplete_var": complete_var,104 }105 ).strip() + ";"270 unmodified linesmodified:src/click/_compat.py+5 added-5 removed
508 unmodified lines509 510 if not PY2 or binary:511 return io.open(file, mode, **kwargs)512 513- f = io.open(file, "b" + mode.replace("t", ""))513+ f = io.open(file, "{}b".format(mode.replace("t", "")))514 return _make_text_stream(f, **kwargs)515 516 517 def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False):16 unmodified lines534 535 # Some usability stuff for atomic writes536 if "a" in mode:537 raise ValueError(538- "Appending to an existing file is not supported, because that "539- "would involve an expensive `copy`-operation to a temporary "540- "file. Open the file in normal `w`-mode and copy explicitly "541- "if that's what you're after."538+ "Appending to an existing file is not supported, because that"539+ " would involve an expensive `copy`-operation to a temporary"540+ " file. Open the file in normal `w`-mode and copy explicitly"541+ " if that's what you're after."542 )543 if "x" in mode:544 raise ValueError("Use the `overwrite`-parameter instead.")545 if "w" not in mode:245 unmodified linesmodified:src/click/_termui_impl.py+11 added-9 removed
165 unmodified lines166 t //= 60167 hours = t % 24168 t //= 24169 if t > 0:170- days = t171- return "%dd %02d:%02d:%02d" % (days, hours, minutes, seconds)170+ return "{}d {:02}:{:02}:{:02}".format(t, hours, minutes, seconds)171 else:173- return "%02d:%02d:%02d" % (hours, minutes, seconds)172+ return "{:02}:{:02}:{:02}".format(hours, minutes, seconds)173 return ""174 175 def format_pos(self):176 pos = str(self.pos)177 if self.length_known:179- pos += "/%s" % self.length178+ pos += "/{}".format(self.length)179 return pos180 181 def format_pct(self):183- return ("% 4d%%" % int(self.pct * 100))[1:]182+ return "{: 4}%".format(int(self.pct * 100))[1:]183 184 def format_bar(self):185 if self.length_known:186 bar_length = int(self.pct * self.width)158 unmodified lines345 346 fd, filename = tempfile.mkstemp()347 os.close(fd)348 try:350- if hasattr(os, "system") and os.system("more %s" % shlex_quote(filename)) == 0:349+ if (350+ hasattr(os, "system")351+ and os.system("more {}".format(shlex_quote(filename))) == 0352+ ):353 return _pipepager(generator, "more", color)354 return _nullpager(stdout, generator, color)355 finally:356 os.unlink(filename)10 unmodified lines367 # If we're piping to less we might support colors under the368 # condition that369 cmd_detail = cmd.rsplit("/", 1)[-1].split()370 if color is None and cmd_detail[0] == "less":369- less_flags = os.environ.get("LESS", "") + " ".join(cmd_detail[1:])371+ less_flags = "{}{}".format(os.environ.get("LESS", ""), " ".join(cmd_detail[1:]))372 if not less_flags:373 env["LESS"] = "-R"374 color = True375 elif "r" in less_flags or "R" in less_flags:71 unmodified lines447 return rv448 if WIN:449 return "notepad"450 for editor in "sensible-editor", "vim", "nano":449- if os.system("which %s >/dev/null 2>&1" % editor) == 0:451+ if os.system("which {} >/dev/null 2>&1".format(editor)) == 0:452 return editor453 return "vi"454 455 def edit_file(self, filename):12 unmodified lines468 shell=True,469 )470 exit_code = c.wait()471 if exit_code != 0:470- raise ClickException("%s: Editing failed!" % editor)472+ raise ClickException("{}: Editing failed!".format(editor))473 except OSError as e:474 raise ClickException("{}: Editing failed: {}".format(editor, e))475 476 def edit(self, text):185 unmodified linesmodified:src/click/_unicodefun.py+24 added-23 removed
36 unmodified lines37 from warnings import warn38 39 warn(40 Warning(41- "Click detected the use of the unicode_literals "42- "__future__ import. This is heavily discouraged "43- "because it can introduce subtle bugs in your "44- 'code. You should instead use explicit u"" literals '45- "for your unicode strings. For more information see "46- "https://click.palletsprojects.com/en/7.x/python3/"41+ "Click detected the use of the unicode_literals __future__"42+ " import. This is heavily discouraged because it can"43+ " introduce subtle bugs in your code. You should instead"44+ ' use explicit u"" literals for your unicode strings. For'45+ " more information see"46+ " https://click.palletsprojects.com/python3/"47 ),48 stacklevel=bad_frame,49 )50 37 unmodified lines88 89 extra += "\n\n"90 if not good_locales:91 extra += (92- "Additional information: on this system no suitable UTF-8\n"93- "locales were discovered. This most likely requires resolving\n"94- "by reconfiguring the locale system."92+ "Additional information: on this system no suitable"93+ " UTF-8 locales were discovered. This most likely"94+ " requires resolving by reconfiguring the locale"95+ " system."96 )97 elif has_c_utf8:98 extra += (98- "This system supports the C.UTF-8 locale which is recommended.\n"99- "You might be able to resolve your issue by exporting the\n"100- "following environment variables:\n\n"99+ "This system supports the C.UTF-8 locale which is"100+ " recommended. You might be able to resolve your issue"101+ " by exporting the following environment variables:\n\n"102 " export LC_ALL=C.UTF-8\n"103 " export LANG=C.UTF-8"104 )105 else:106 extra += (106- "This system lists a couple of UTF-8 supporting locales that\n"107- "you can pick from. The following suitable locales were\n"108- "discovered: %s"109- ) % ", ".join(sorted(good_locales))107+ "This system lists a couple of UTF-8 supporting locales"108+ " that you can pick from. The following suitable"109+ " locales were discovered: {}".format(", ".join(sorted(good_locales)))110+ )111 112 bad_locale = None113 for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):114 if locale and locale.lower().endswith((".utf-8", ".utf8")):1 unmodified line116 if locale is not None:117 break118 if bad_locale is not None:119 extra += (119- "\n\nClick discovered that you exported a UTF-8 locale\n"120- "but the locale system could not pick up from it because\n"121- 'it does not exist. The exported locale is "%s" but it\n'122- "is not supported"123- ) % bad_locale120+ "\n\nClick discovered that you exported a UTF-8 locale"121+ " but the locale system could not pick up from it"122+ " because it does not exist. The exported locale is"123+ " '{}' but it is not supported".format(bad_locale)124+ )125 126 raise RuntimeError(127 "Click will abort further execution because Python 3 was"128 " configured to use ASCII as encoding for the environment."128- " Consult https://click.palletsprojects.com/en/7.x/python3/ for"129- " mitigation steps." + extra129+ " Consult https://click.palletsprojects.com/python3/ for"130+ " mitigation steps.{}".format(extra)131 )modified:src/click/_winconsole.py+2 added-2 removed
153 unmodified lines154 if GetLastError() == ERROR_OPERATION_ABORTED:155 # wait for KeyboardInterrupt156 time.sleep(0.1)157 if not rv:158- raise OSError("Windows error: %s" % GetLastError())158+ raise OSError("Windows error: {}".format(GetLastError()))159 160 if buffer[0] == EOF:161 return 0162 return 2 * code_units_read.value8 unmodified lines171 if errno == ERROR_SUCCESS:172 return "ERROR_SUCCESS"173 elif errno == ERROR_NOT_ENOUGH_MEMORY:174 return "ERROR_NOT_ENOUGH_MEMORY"175- return "Windows error %s" % errno175+ return "Windows error {}".format(errno)176 177 def write(self, b):178 bytes_to_be_written = len(b)179 buf = get_buffer(b)191 unmodified linesmodified:src/click/core.py+49 added-52 removed
60 unmodified lines61 62 def _bashcomplete(cmd, prog_name, complete_var=None):63 """Internal handler for the bash completion support."""64 if complete_var is None:65- complete_var = "_%s_COMPLETE" % (prog_name.replace("-", "_")).upper()65+ complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())66 complete_instr = os.environ.get(complete_var)67 if not complete_instr:68 return69 7 unmodified lines77 if not base_command.chain or not isinstance(cmd, MultiCommand):78 return79 if register:80 hint = (81- "It is not possible to add multi commands as children to "82- "another multi command that is in chain mode"81+ "It is not possible to add multi commands as children to"82+ " another multi command that is in chain mode."83 )84 else:85 hint = (86- "Found a multi command as subcommand to a multi command "87- "that is in chain mode. This is not supported"86+ "Found a multi command as subcommand to a multi command"87+ " that is in chain mode. This is not supported."88 )89 raise RuntimeError(90- '%s. Command "%s" is set to chain and "%s" was '91- "added as subcommand but it in itself is a "92- 'multi command. ("%s" is a %s within a chained '93- '%s named "%s").'94- % (90+ "{}. Command '{}' is set to chain and '{}' was added as"91+ " subcommand but it in itself is a multi command. ('{}' is a {}"92+ " within a chained {} named '{}').".format(93 hint,94 base_command.name,95 cmd_name,96 cmd_name,17 unmodified lines114 from warnings import warn115 116 warn(117 Warning(120- 'Invoked legacy parameter callback "%s". The new '121- "signature for such callbacks starting with "122- "click 2.0 is (ctx, param, value)." % callback118+ "Invoked legacy parameter callback '{}'. The new"119+ " signature for such callbacks starting with Click 2.0"120+ " is (ctx, param, value).".format(callback)121 ),122 stacklevel=3,123 )124 return callback(ctx, value)1 unmodified line126 127 128 @contextmanager129 def augment_usage_errors(ctx, param=None):132- """Context manager that attaches extra information to exceptions that133- fly.134- """130+ """Context manager that attaches extra information to exceptions."""131 try:132 yield133 except BadParameter as e:134 if e.ctx is None:240 unmodified lines375 and parent.auto_envvar_prefix is not None376 and self.info_name is not None377 ):378 auto_envvar_prefix = "{}_{}".format(383- parent.auto_envvar_prefix, self.info_name.upper(),379+ parent.auto_envvar_prefix, self.info_name.upper()380 )381 else:382 auto_envvar_prefix = auto_envvar_prefix.upper()383 if auto_envvar_prefix is not None:74 unmodified lines458 the system.459 460 Example usage::461 466- LANG_KEY = __name__ + '.lang'462+ LANG_KEY = f'{__name__}.lang'463 464 def set_language(value):465 ctx = get_current_context()466 ctx.meta[LANG_KEY] = value38 unmodified lines505 rv = ""506 if self.info_name is not None:507 rv = self.info_name508 if self.parent is not None:513- rv = self.parent.command_path + " " + rv509+ rv = "{} {}".format(self.parent.command_path, rv)510 return rv.lstrip()511 512 def find_root(self):513 """Finds the outermost context."""254 unmodified lines768 else:769 args = list(args)770 771 if prog_name is None:776- prog_name = make_str(os.path.basename(sys.argv and sys.argv[0] or __file__))772+ prog_name = make_str(773+ os.path.basename(sys.argv[0] if sys.argv else __file__)774+ )775 776 # Hook for the Bash completion. This only activates if the Bash777 # completion is actually enabled, otherwise this is quite a fast778 # noop.271 unmodified lines1050 value, args = param.handle_parse_result(ctx, opts, args)1051 1052 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1053 ctx.fail(1056- "Got unexpected extra argument%s (%s)"1057- % (len(args) != 1 and "s" or "", " ".join(map(make_str, args)))1054+ "Got unexpected extra argument{} ({})".format(1055+ "s" if len(args) != 1 else "", " ".join(map(make_str, args))1056+ )1057 )1058 1059 ctx.args = args1060 return args63 unmodified lines1124 if self.chain:1125 for param in self.params:1126 if isinstance(param, Argument) and not param.required:1127 raise RuntimeError(1129- "Multi commands in chain mode cannot "1130- "have optional arguments."1128+ "Multi commands in chain mode cannot have"1129+ " optional arguments."1130 )1131 1132 def collect_usage_pieces(self, ctx):1133 rv = Command.collect_usage_pieces(self, ctx)131 unmodified lines1265 # know the subcommands yet, the invoked subcommand attribute is1266 # set to ``*`` to inform the command that subcommands are executed1267 # but nothing else.1268 with ctx:1270- ctx.invoked_subcommand = args and "*" or None1269+ ctx.invoked_subcommand = "*" if args else None1270 Command.invoke(self, ctx)1271 1272 # Otherwise we make every single context and invoke them in a1273 # chain. In that case the return value to the result processor38 unmodified lines1312 # place.1313 if cmd is None and not ctx.resilient_parsing:1314 if split_opt(cmd_name)[0]:1315 self.parse_args(ctx, ctx.args)1317- ctx.fail('No such command "%s".' % original_cmd_name)1316+ ctx.fail("No such command '{}'.".format(original_cmd_name))1317 1318 return cmd_name, cmd, args[1:]1319 1320 def get_command(self, ctx, cmd_name):233 unmodified lines1554 """1555 if self.type.is_composite:1556 if self.nargs <= 1:1557 raise TypeError(1559- "Attempted to invoke composite type "1560- "but nargs has been set to %s. This is "1561- "not supported; nargs needs to be set to "1562- "a fixed value > 1." % self.nargs1558+ "Attempted to invoke composite type but nargs has"1559+ " been set to {}. This is not supported; nargs"1560+ " needs to be set to a fixed value > 1.".format(self.nargs)1561 )1562 if self.multiple:1563 return tuple(self.type(x or (), self, ctx) for x in value or ())1564 return self.type(value or (), self, ctx)84 unmodified lines1649 """Get a stringified version of the param for use in error messages to1650 indicate which param caused the error.1651 """1652 hint_list = self.opts or [self.human_readable_name]1655- return " / ".join('"%s"' % x for x in hint_list)1653+ return " / ".join(repr(x) for x in hint_list)1654 1655 1656 class Option(Parameter):1657 """Options are usually optional values on the command line and133 unmodified lines1791 if name is not None:1792 raise TypeError("Name defined twice")1793 name = decl1794 else:1797- split_char = decl[:1] == "/" and ";" or "/"1795+ split_char = ";" if decl[:1] == "/" else "/"1796 if split_char in decl:1797 first, second = decl.split(split_char, 1)1798 first = first.rstrip()1799 if first:18 unmodified lines1818 raise TypeError("Could not determine name for option")1819 1820 if not opts and not secondary_opts:1821 raise TypeError(1824- "No options defined but a name was passed (%s). "1825- "Did you mean to declare an argument instead "1826- "of an option?" % name1822+ "No options defined but a name was passed ({}). Did you"1823+ " mean to declare an argument instead of an option?".format(name)1824 )1825 1826 return name, opts, secondary_opts1827 12 unmodified lines1840 action = "store"1841 1842 if self.is_flag:1843 kwargs.pop("nargs", None)1844+ action_const = "{}_const".format(action)1845 if self.is_bool_flag and self.secondary_opts:1846+ parser.add_option(self.opts, action=action_const, const=True, **kwargs)1847 parser.add_option(1849- self.opts, action=action + "_const", const=True, **kwargs1848+ self.secondary_opts, action=action_const, const=False, **kwargs1849 )1851- parser.add_option(1852- self.secondary_opts, action=action + "_const", const=False, **kwargs1853- )1850 else:1851 parser.add_option(1856- self.opts, action=action + "_const", const=self.flag_value, **kwargs1852+ self.opts, action=action_const, const=self.flag_value, **kwargs1853 )1854 else:1855 kwargs["action"] = action1856 parser.add_option(self.opts, **kwargs)7 unmodified lines1864 rv, any_slashes = join_options(opts)1865 if any_slashes:1866 any_prefix_is_slash[:] = [True]1867 if not self.is_flag and not self.count:1872- rv += " " + self.make_metavar()1868+ rv += " {}".format(self.make_metavar())1869 return rv1870 1871 rv = [_write_opts(self.opts)]1872 if self.secondary_opts:7 unmodified lines1880 if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:1881 envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper())1882 if envvar is not None:1883 extra.append(1888- "env var: %s"1889- % (1890- ", ".join("%s" % d for d in envvar)1884+ "env var: {}".format(1885+ ", ".join(str(d) for d in envvar)1886 if isinstance(envvar, (list, tuple))1892- else envvar,1887+ else envvar1888 )1889 )1890 if self.default is not None and (self.show_default or ctx.show_default):1891 if isinstance(self.show_default, string_types):1892 default_string = "({})".format(self.show_default)1893 elif isinstance(self.default, (list, tuple)):1899- default_string = ", ".join("%s" % d for d in self.default)1894+ default_string = ", ".join(str(d) for d in self.default)1895 elif inspect.isfunction(self.default):1896 default_string = "(dynamic)"1897 else:1898 default_string = self.default1 unmodified line1900 1901 if self.required:1902 extra.append("required")1903 if extra:1909- help = "{}[{}]".format(help and help + " " or "", "; ".join(extra))1904+ help = "{}[{}]".format(1905+ "{} ".format(help) if help else "", "; ".join(extra)1906+ )1907 1911- return ((any_prefix_is_slash and "; " or " / ").join(rv), help)1908+ return ("; " if any_prefix_is_slash else " / ").join(rv), help1909 1910 def get_default(self, ctx):1911 # If we're a non boolean flag our default is more complex because1912 # we need to look at all flags in the same group to figure out89 unmodified lines2002 var = self.type.get_metavar(self)2003 if not var:2004 var = self.name.upper()2005 if not self.required:2009- var = "[%s]" % var2006+ var = "[{}]".format(var)2007 if self.nargs != 1:2008 var += "..."2009 return var2010 6 unmodified lines2017 name = arg = decls[0]2018 name = name.replace("-", "_").lower()2019 else:2020 raise TypeError(2024- "Arguments take exactly one "2025- "parameter declaration, got %d" % len(decls)2021+ "Arguments take exactly one parameter declaration, got"2022+ " {}".format(len(decls))2023 )2024 return name, [arg], []2025 2026 def get_usage_pieces(self, ctx):2027 return [self.make_metavar()]2028 2029 def get_error_hint(self, ctx):2033- return '"%s"' % self.make_metavar()2030+ return repr(self.make_metavar())2031 2032 def add_to_parser(self, parser, ctx):2033 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)modified:src/click/decorators.py+2 added-2 removed
65 unmodified lines66 else:67 obj = ctx.find_object(object_type)68 if obj is None:69 raise RuntimeError(70- "Managed to invoke callback without a "71- "context object of type %r existing" % object_type.__name__70+ "Managed to invoke callback without a context"71+ " object of type '{}' existing".format(object_type.__name__)72 )73 return ctx.invoke(f, obj, *args, **kwargs)74 75 return update_wrapper(new_func, f)258 unmodified linesmodified:src/click/exceptions.py+14 added-14 removed
4 unmodified lines5 6 7 def _join_param_hints(param_hint):8 if isinstance(param_hint, (tuple, list)):9- return " / ".join('"%s"' % x for x in param_hint)9+ return " / ".join(repr(x) for x in param_hint)10 return param_hint11 12 13 class ClickException(Exception):24 unmodified lines38 39 def show(self, file=None):40 if file is None:41 file = get_text_stderr()42- echo("Error: %s" % self.format_message(), file=file)42+ echo("Error: {}".format(self.format_message(), file=file))43 44 45 class UsageError(ClickException):46 """An internal exception that signals a usage error. This typically8 unmodified lines55 56 def __init__(self, message, ctx=None):57 ClickException.__init__(self, message)58 self.ctx = ctx59- self.cmd = self.ctx and self.ctx.command or None59+ self.cmd = self.ctx.command if self.ctx else None60 61 def show(self, file=None):62 if file is None: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 "{} {}" for help.\n'.format(68- self.ctx.command_path, 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)73- echo("Error: %s" % self.format_message(), file=file, color=color)72+ echo("{}\n{}".format(self.ctx.get_usage(), hint), file=file, color=color)73+ echo("Error: {}".format(self.format_message()), file=file, color=color)74 75 76 class BadParameter(UsageError):77 """An exception that formats out a standardized error message for a23 unmodified lines101 param_hint = self.param_hint102 elif self.param is not None:103 param_hint = self.param.get_error_hint(self.ctx)104 else:105- return "Invalid value: %s" % self.message105+ return "Invalid value: {}".format(self.message)106 param_hint = _join_param_hints(param_hint)107 108 return "Invalid value for {}: {}".format(param_hint, self.message)109 33 unmodified lines143 if self.param is not None:144 msg_extra = self.param.type.get_missing_message(self.param)145 if msg_extra:146 if msg:147- msg += ". " + msg_extra147+ msg += ". {}".format(msg_extra)148 else:149 msg = msg_extra150 151 return "Missing {}{}{}{}".format(152 param_type,153- param_hint and " %s" % param_hint or "",154- msg and ". " or ".",153+ " {}".format(param_hint) if param_hint else "",154+ ". " if msg else ".",155 msg or "",156 )157 158 def __str__(self):18 unmodified lines177 """178 179 def __init__(self, option_name, message=None, possibilities=None, ctx=None):180 if message is None:181- message = "no such option: %s" % option_name181+ message = "no such option: {}".format(option_name)182 UsageError.__init__(self, message, ctx)183 self.option_name = option_name184 self.possibilities = possibilities185 186 def format_message(self):187 bits = [self.message]188 if self.possibilities:189 if len(self.possibilities) == 1:190- bits.append("Did you mean %s?" % self.possibilities[0])190+ bits.append("Did you mean {}?".format(self.possibilities[0]))191 else:192 possibilities = sorted(self.possibilities)193- bits.append("(Possible options: %s)" % ", ".join(possibilities))193+ bits.append("(Possible options: {})".format(", ".join(possibilities)))194 return " ".join(bits)195 196 197 class BadOptionUsage(UsageError):56 unmodified linesmodified:src/click/formatting.py+9 added-5 removed
132 unmodified lines133 :param prog: the program name.134 :param args: whitespace separated list of arguments.135 :param prefix: the prefix for the first line.136 """137- usage_prefix = "%*s%s " % (self.current_indent, prefix, prog)137+ usage_prefix = "{:>{w}}{} ".format(prefix, prog, w=self.current_indent)138 text_width = self.width - self.current_indent139 140 if text_width >= (term_len(usage_prefix) + 20):141 # The arguments will fit to the right of the prefix.20 unmodified lines162 self.write("\n")163 164 def write_heading(self, heading):165 """Writes a heading into the buffer."""166- self.write("%*s%s:\n" % (self.current_indent, "", heading))166+ self.write("{:>{w}}{}:\n".format("", heading, w=self.current_indent))167 168 def write_paragraph(self):169 """Writes a paragraph into the buffer."""170 if self.buffer:32 unmodified lines203 204 first_col = min(widths[0], col_max) + col_spacing205 206 for first, second in iter_rows(rows, len(widths)):207- self.write("%*s%s" % (self.current_indent, "", first))207+ self.write("{:>{w}}{}".format("", first, w=self.current_indent))208 if not second:209 self.write("\n")210 continue211 if term_len(first) <= first_col - col_spacing:6 unmodified lines218 wrapped_text = wrap_text(second, text_width, preserve_paragraphs=True)219 lines = wrapped_text.splitlines()220 221 if lines:222- self.write(lines[0] + "\n")222+ self.write("{}\n".format(lines[0]))223 224 for line in lines[1:]:225- self.write("%*s%s\n" % (first_col + self.current_indent, "", line))225+ self.write(226+ "{:>{w}}{}\n".format(227+ "", line, w=first_col + self.current_indent228+ )229+ )230 231 if len(lines) > 1:232 # separate long help from next option233 self.write("\n")50 unmodified linesmodified:src/click/parser.py+7 added-7 removed
78 unmodified lines79 80 81 def _error_opt_args(nargs, opt):82 if nargs == 1:83- raise BadOptionUsage(opt, "%s option requires an argument" % opt)84- raise BadOptionUsage(opt, "%s option requires %d arguments" % (opt, nargs))83+ raise BadOptionUsage(opt, "{} option requires an argument".format(opt))84+ raise BadOptionUsage(opt, "{} option requires {} arguments".format(opt, nargs))85 86 87 def split_opt(opt):88 first = opt[:1]38 unmodified lines127 128 for opt in opts:129 prefix, value = split_opt(opt)130 if not prefix:131- raise ValueError("Invalid start character for option (%s)" % opt)131+ raise ValueError("Invalid start character for option ({})".format(opt))132 self.prefixes.add(prefix[0])133 if len(prefix) == 1 and len(value) == 1:134 self._short_opts.append(opt)135 else:24 unmodified lines160 state.opts.setdefault(self.dest, []).append(self.const)161 elif self.action == "count":162 state.opts[self.dest] = state.opts.get(self.dest, 0) + 1163 else:164- raise ValueError("unknown action %r" % self.action)164+ raise ValueError("unknown action '{}'".format(self.action))165 state.order.append(self.obj)166 167 168 class Argument(object):8 unmodified lines177 if holes == len(value):178 value = None179 elif holes != 0:180 raise BadArgumentUsage(181- "argument %s takes %d values" % (self.dest, self.nargs)181+ "argument {} takes {} values".format(self.dest, self.nargs)182 )183 state.opts[self.dest] = value184 state.order.append(self.obj)185 157 unmodified lines343 value = tuple(state.rargs[:nargs])344 del state.rargs[:nargs]345 346 elif explicit_value is not None:347- raise BadOptionUsage(opt, "%s option does not take a value" % opt)347+ raise BadOptionUsage(opt, "{} option does not take a value".format(opt))348 349 else:350 value = None351 43 unmodified lines395 # remaining options and re-attach the prefix, then report that396 # to the state as new larg. This way there is basic combinatorics397 # that can be achieved while still ignoring unknown arguments.398 if self.ignore_unknown_options and unknown_options:399- state.largs.append(prefix + "".join(unknown_options))399+ state.largs.append("{}{}".format(prefix, "".join(unknown_options)))400 401 def _process_opts(self, arg, state):402 explicit_value = None403 # Long option handling happens in two parts. The first part is25 unmodified linesmodified:src/click/termui.py+13 added-13 removed
57 unmodified lines58 text, suffix, show_default=False, default=None, show_choices=True, type=None59 ):60 prompt = text61 if type is not None and show_choices and isinstance(type, Choice):62- prompt += " (" + ", ".join(map(str, type.choices)) + ")"62+ prompt += " ({})".format(", ".join(map(str, type.choices)))63 if default is not None and show_default:64 prompt = "{} [{}]".format(prompt, _format_default(default))65 return prompt + suffix66 53 unmodified lines120 """121 result = None122 123 def prompt_func(text):124- f = hide_input and hidden_prompt_func or visible_prompt_func124+ f = hidden_prompt_func if hide_input else visible_prompt_func125 try:126 # Write the prompt separately so that we get nice127 # coloring through colorama on Windows128 echo(text, nl=False, err=err)26 unmodified lines155 return default156 try:157 result = value_proc(value)158 except UsageError as e:159- echo("Error: %s" % e.message, err=err) # noqa: B306159+ echo("Error: {}".format(e.message), err=err) # noqa: B306160 continue161 if not confirmation_prompt:162 return result163 while 1:25 unmodified lines189 :param err: if set to true the file defaults to ``stderr`` instead of190 ``stdout``, the same as with echo.191 """192 prompt = _build_prompt(193- text, prompt_suffix, show_default, default and "Y/n" or "y/N"193+ text, prompt_suffix, show_default, "Y/n" if default else "y/N"194 )195 while 1:196 try:197 # Write the prompt separately so that we get nice296 unmodified lines494 """495 bits = []496 if fg:497 try:498- bits.append("\033[%dm" % (_ansi_colors[fg]))498+ bits.append("\033[{}m".format(_ansi_colors[fg]))499 except KeyError:500- raise TypeError("Unknown color %r" % fg)500+ raise TypeError("Unknown color '{}'".format(fg))501 if bg:502 try:503- bits.append("\033[%dm" % (_ansi_colors[bg] + 10))503+ bits.append("\033[{}m".format(_ansi_colors[bg] + 10))504 except KeyError:505- raise TypeError("Unknown color %r" % bg)505+ raise TypeError("Unknown color '{}'".format(bg))506 if bold is not None:507- bits.append("\033[%dm" % (1 if bold else 22))507+ bits.append("\033[{}m".format(1 if bold else 22))508 if dim is not None:509- bits.append("\033[%dm" % (2 if dim else 22))509+ bits.append("\033[{}m".format(2 if dim else 22))510 if underline is not None:511- bits.append("\033[%dm" % (4 if underline else 24))511+ bits.append("\033[{}m".format(4 if underline else 24))512 if blink is not None:513- bits.append("\033[%dm" % (5 if blink else 25))513+ bits.append("\033[{}m".format(5 if blink else 25))514 if reverse is not None:515- bits.append("\033[%dm" % (7 if reverse else 27))515+ bits.append("\033[{}m".format(7 if reverse else 27))516 bits.append(text)517 if reset:518 bits.append(_ansi_reset_all)519 return "".join(bits)162 unmodified linesmodified:src/click/testing.py+3 added-3 removed
107 unmodified lines108 )109 110 def __repr__(self):111 return "<{} {}>".format(112- type(self).__name__, self.exception and repr(self.exception) or "okay",112+ type(self).__name__, repr(self.exception) if self.exception else "okay"113 )114 115 116 class CliRunner(object):92 unmodified lines209 210 def visible_input(prompt=None):211 sys.stdout.write(prompt or "")212 val = input.readline().rstrip("\r\n")213- sys.stdout.write(val + "\n")213+ sys.stdout.write("{}\n".format(val))214 sys.stdout.flush()215 return val216 217 def hidden_input(prompt=None):218- sys.stdout.write((prompt or "") + "\n")218+ sys.stdout.write("{}\n".format(prompt or ""))219 sys.stdout.flush()220 return input.readline().rstrip("\r\n")221 222 def _getchar(echo):160 unmodified linesmodified:src/click/types.py+41 added-32 removed
156 unmodified lines157 self.choices = choices158 self.case_sensitive = case_sensitive159 160 def get_metavar(self, param):161- return "[%s]" % "|".join(self.choices)161+ return "[{}]".format("|".join(self.choices))162 163 def get_missing_message(self, param):164- return "Choose from:\n\t%s." % ",\n\t".join(self.choices)164+ return "Choose from:\n\t{}.".format(",\n\t".join(self.choices))165 166 def convert(self, value, param, ctx):167 # Match through normalization and case sensitivity168 # first do token_normalize_func, then lowercase32 unmodified lines201 ctx,202 )203 204 def __repr__(self):205- return "Choice(%r)" % list(self.choices)205+ return "Choice('{}')".format(list(self.choices))206 207 208 class DateTime(ParamType):209 """The DateTime type converts date strings into `datetime` objects.53 unmodified lines263 def convert(self, value, param, ctx):264 try:265 return int(value)266 except ValueError:267- self.fail("%s is not a valid integer" % value, param, ctx)267+ self.fail("{} is not a valid integer".format(value), param, ctx)268 269 def __repr__(self):270 return "INT"271 36 unmodified lines308 ctx,309 )310 elif self.max is None:311 self.fail(312- "%s is smaller than the minimum valid value "313- "%s." % (rv, self.min),312+ "{} is smaller than the minimum valid value {}.".format(313+ rv, self.min314+ ),315 param,316 ctx,317 )318 else:319 self.fail(319- "%s is not in the valid range of %s to %s."320- % (rv, self.min, self.max),320+ "{} is not in the valid range of {} to {}.".format(321+ rv, self.min, self.max322+ ),323 param,324 ctx,325 )326 return rv327 328 def __repr__(self):327- return "IntRange({!r}, {!r})".format(self.min, self.max)329+ return "IntRange({}, {})".format(self.min, self.max)330 331 332 class FloatParamType(ParamType):333 name = "float"1 unmodified line335 def convert(self, value, param, ctx):336 try:337 return float(value)338 except ValueError:337- self.fail("%s is not a valid floating point value" % value, param, ctx)339+ self.fail(340+ "{} is not a valid floating point value".format(value), param, ctx341+ )342 343 def __repr__(self):344 return "FLOAT"345 36 unmodified lines382 ctx,383 )384 elif self.max is None:385 self.fail(382- "%s is smaller than the minimum valid value "383- "%s." % (rv, self.min),386+ "{} is smaller than the minimum valid value {}.".format(387+ rv, self.min388+ ),389 param,390 ctx,391 )392 else:393 self.fail(389- "%s is not in the valid range of %s to %s."390- % (rv, self.min, self.max),394+ "{} is not in the valid range of {} to {}.".format(395+ rv, self.min, self.max396+ ),397 param,398 ctx,399 )400 return rv401 402 def __repr__(self):397- return "FloatRange({!r}, {!r})".format(self.min, self.max)403+ return "FloatRange({}, {})".format(self.min, self.max)404 405 406 class BoolParamType(ParamType):407 name = "boolean"5 unmodified lines413 if value in ("true", "t", "1", "yes", "y"):414 return True415 elif value in ("false", "f", "0", "no", "n"):416 return False411- self.fail("%s is not a valid boolean" % value, param, ctx)417+ self.fail("{} is not a valid boolean".format(value), param, ctx)418 419 def __repr__(self):420 return "BOOL"421 8 unmodified lines430 if PY2 and isinstance(value, text_type):431 value = value.encode("ascii")432 return uuid.UUID(value)433 except ValueError:428- self.fail("%s is not a valid UUID value" % value, param, ctx)434+ self.fail("{} is not a valid UUID value".format(value), param, ctx)435 436 def __repr__(self):437 return "UUID"438 76 unmodified lines515 ctx.call_on_close(safecall(f.flush))516 return f517 except (IOError, OSError) as e: # noqa: B014518 self.fail(513- "Could not open file: %s: %s"514- % (filename_to_ui(value), get_streerror(e),),519+ "Could not open file: {}: {}".format(520+ filename_to_ui(value), get_streerror(e)521+ ),522 param,523 ctx,524 )525 83 unmodified lines609 except OSError:610 if not self.exists:611 return self.coerce_path_result(rv)612 self.fail(606- '{} "{}" does not exist.'.format(613+ "{} '{}' does not exist.".format(614 self.path_type, filename_to_ui(value)615 ),616 param,617 ctx,618 )619 620 if not self.file_okay and stat.S_ISREG(st.st_mode):621 self.fail(615- '{} "{}" is a file.'.format(self.path_type, filename_to_ui(value)),622+ "{} '{}' is a file.".format(self.path_type, filename_to_ui(value)),623 param,624 ctx,625 )626 if not self.dir_okay and stat.S_ISDIR(st.st_mode):627 self.fail(621- '{} "{}" is a directory.'.format(628+ "{} '{}' is a directory.".format(629 self.path_type, filename_to_ui(value)630 ),631 param,632 ctx,633 )634 if self.writable and not os.access(value, os.W_OK):635 self.fail(629- '%s "%s" is not writable.'630- % (self.path_type, filename_to_ui(value)),636+ "{} '{}' is not writable.".format(637+ self.path_type, filename_to_ui(value)638+ ),639 param,640 ctx,641 )642 if self.readable and not os.access(value, os.R_OK):643 self.fail(636- '%s "%s" is not readable.'637- % (self.path_type, filename_to_ui(value)),644+ "{} '{}' is not readable.".format(645+ self.path_type, filename_to_ui(value)646+ ),647 param,648 ctx,649 )650 18 unmodified lines669 self.types = [convert_type(ty) for ty in types]670 671 @property672 def name(self):664- return "<" + " ".join(ty.name for ty in self.types) + ">"673+ return "<{}>".format(" ".join(ty.name for ty in self.types))674 675 @property676 def arity(self):677 return len(self.types)678 679 def convert(self, value, param, ctx):680 if len(value) != len(self.types):681 raise TypeError(673- "It would appear that nargs is set to conflict "674- "with the composite type arity."682+ "It would appear that nargs is set to conflict with the"683+ " composite type arity."684 )685 return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value))686 687 688 def convert_type(ty, default=None):680- """Converts a callable or python ty into the most appropriate param681- ty.689+ """Converts a callable or python type into the most appropriate690+ param type.691 """692 guessed_type = False693 if ty is None and default is not None:694 if isinstance(default, tuple):25 unmodified lines720 if __debug__:721 try:722 if issubclass(ty, ParamType):723 raise AssertionError(715- "Attempted to use an uninstantiated parameter type (%s)." % ty724+ "Attempted to use an uninstantiated parameter type ({}).".format(ty)725 )726 except TypeError:727 pass728 return FuncParamType(ty)34 unmodified linesmodified:src/click/utils.py+6 added-6 removed
63 unmodified lines64 65 for word in words:66 if word[-1:] == ".":67 done = True68- new_length = result and 1 + len(word) or len(word)68+ new_length = 1 + len(word) if result else len(word)69 if total_length + new_length > max_length:70 result.append("...")71 done = True72 else:39 unmodified lines112 113 def __repr__(self):114 if self._f is not None:115 return repr(self._f)116- return "<unopened file {!r} {}>".format(self.name, self.mode)116+ return "<unopened file '{}' {}>".format(self.name, self.mode)117 118 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 error163 unmodified lines284 ``'stdout'`` and ``'stderr'``285 """286 opener = binary_streams.get(name)287 if opener is None:288- raise TypeError("Unknown standard stream %r" % name)288+ raise TypeError("Unknown standard stream '{}'".format(name))289 return opener()290 291 292 def get_text_stream(name, encoding=None, errors="strict"):8 unmodified lines301 :param errors: overrides the default error mode.302 """303 opener = text_streams.get(name)304 if opener is None:305- raise TypeError("Unknown standard stream %r" % name)305+ raise TypeError("Unknown standard stream '{}'".format(name))306 return opener(encoding, errors)307 308 309 def open_file(102 unmodified lines412 dot instead of the XDG config home or darwin's413 application support folder.414 """415 if WIN:416- key = roaming and "APPDATA" or "LOCALAPPDATA"416+ key = "APPDATA" if roaming else "LOCALAPPDATA"417 folder = os.environ.get(key)418 if folder is None:419 folder = os.path.expanduser("~")420 return os.path.join(folder, app_name)421 if force_posix:422- return os.path.join(os.path.expanduser("~/." + _posixify(app_name)))422+ return os.path.join(os.path.expanduser("~/.{}".format(_posixify(app_name))))423 if sys.platform == "darwin":424 return os.path.join(425 os.path.expanduser("~/Library/Application Support"), app_name426 )29 unmodified linesmodified:tests/test_arguments.py+18 added-38 removed
11 unmodified lines12 @click.command()13 @click.argument("src", nargs=-1)14 @click.argument("dst")15 def copy(src, dst):16- click.echo("src=%s" % "|".join(src))17- click.echo("dst=%s" % dst)16+ click.echo("src={}".format("|".join(src)))17+ click.echo("dst={}".format(dst))18 19 result = runner.invoke(copy, ["foo.txt", "bar.txt", "dir"])20 assert not result.exception21- assert result.output.splitlines() == [22- "src=foo.txt|bar.txt",23- "dst=dir",24- ]21+ assert result.output.splitlines() == ["src=foo.txt|bar.txt", "dst=dir"]22 23 24 def test_nargs_default(runner):25 with pytest.raises(TypeError, match="nargs=-1"):8 unmodified lines34 @click.command()35 @click.argument("name", nargs=1)36 @click.argument("point", nargs=2, type=click.INT)37 def copy(name, point):41- click.echo("name=%s" % name)42- click.echo("point=%d/%d" % point)38+ click.echo("name={}".format(name))39+ click.echo("point={0[0]}/{0[1]}".format(point))40 41 result = runner.invoke(copy, ["peter", "1", "2"])42 assert not result.exception46- assert result.output.splitlines() == [47- "name=peter",48- "point=1/2",49- ]43+ assert result.output.splitlines() == ["name=peter", "point=1/2"]44 45 46 def test_nargs_tup_composite(runner):47 variations = [7 unmodified lines55 56 @click.command()57 @click.argument("item", **opts)58 def copy(item):65- click.echo("name=%s id=%d" % item)59+ click.echo("name={0[0]} id={0[1]:d}".format(item))60 61 result = runner.invoke(copy, ["peter", "1"])62 assert not result.exception69- assert result.output.splitlines() == [70- "name=peter id=1",71- ]63+ assert result.output.splitlines() == ["name=peter id=1"]64 65 66 def test_nargs_err(runner):67 @click.command()126 unmodified lines194 def test_empty_nargs(runner):195 @click.command()196 @click.argument("arg", nargs=-1)197 def cmd(arg):206- click.echo("arg:" + "|".join(arg))198+ click.echo("arg:{}".format("|".join(arg)))199 200 result = runner.invoke(cmd, [])201 assert result.exit_code == 0202 assert result.output == "arg:\n"203 204 @click.command()205 @click.argument("arg", nargs=-1, required=True)206 def cmd2(arg):215- click.echo("arg:" + "|".join(arg))207+ click.echo("arg:{}".format("|".join(arg)))208 209 result = runner.invoke(cmd2, [])210 assert result.exit_code == 2219- assert 'Missing argument "ARG..."' in result.output211+ assert "Missing argument 'ARG...'" in result.output212 213 214 def test_missing_arg(runner):215 @click.command()216 @click.argument("arg")217 def cmd(arg):226- click.echo("arg:" + arg)218+ click.echo("arg:{}".format(arg))219 220 result = runner.invoke(cmd, [])221 assert result.exit_code == 2230- assert 'Missing argument "ARG".' in result.output222+ assert "Missing argument 'ARG'." in result.output223 224 225 def test_missing_argument_string_cast():226 ctx = click.Context(click.Command(""))24 unmodified lines251 click.echo(filename)252 click.echo(f)253 254 result = runner.invoke(cmd, ["--", "-foo", "bar"])263- assert result.output.splitlines() == [264- "-foo",265- "bar",266- "",267- ]255+ assert result.output.splitlines() == ["-foo", "bar", ""]256 257 result = runner.invoke(cmd, ["-f", "-x", "--", "-foo", "bar"])270- assert result.output.splitlines() == [271- "-foo",272- "bar",273- "-x",274- ]258+ assert result.output.splitlines() == ["-foo", "bar", "-x"]259 260 261 def test_nargs_star_ordering(runner):262 @click.command()4 unmodified lines267 for arg in (a, b, c):268 click.echo(arg)269 270 result = runner.invoke(cmd, ["a", "b", "c"])287- assert result.output.splitlines() == [288- PY2 and "(u'a',)" or "('a',)",289- "b",290- "c",291- ]271+ assert result.output.splitlines() == ["(u'a',)" if PY2 else "('a',)", "b", "c"]272 273 274 def test_nargs_specified_plus_star_ordering(runner):275 @click.command()5 unmodified lines281 click.echo(arg)282 283 result = runner.invoke(cmd, ["a", "b", "c", "d", "e", "f"])284 assert result.output.splitlines() == [305- PY2 and "(u'a', u'b', u'c')" or "('a', 'b', 'c')",285+ "(u'a', u'b', u'c')" if PY2 else "('a', 'b', 'c')",286 "d",307- PY2 and "(u'e', u'f')" or "('e', 'f')",287+ "(u'e', u'f')" if PY2 else "('e', 'f')",288 ]289 290 291 def test_defaults_for_nargs(runner):24 unmodified linesmodified:tests/test_basic.py+25 added-30 removed
80 unmodified lines81 def test_basic_option(runner):82 @click.command()83 @click.option("--foo", default="no value")84 def cli(foo):85- click.echo("FOO:[%s]" % foo)85+ click.echo(u"FOO:[{}]".format(foo))86 87 result = runner.invoke(cli, [])88 assert not result.exception89 assert "FOO:[no value]" in result.output18 unmodified lines108 def test_int_option(runner):109 @click.command()110 @click.option("--foo", default=42)111 def cli(foo):112- click.echo("FOO:[%s]" % (foo * 2))112+ click.echo("FOO:[{}]".format(foo * 2))113 114 result = runner.invoke(cli, [])115 assert not result.exception116 assert "FOO:[84]" in result.output3 unmodified lines120 assert "FOO:[46]" in result.output121 122 result = runner.invoke(cli, ["--foo=bar"])123 assert result.exception124- assert 'Invalid value for "--foo": bar is not a valid integer' in result.output124+ assert "Invalid value for '--foo': bar is not a valid integer" in result.output125 126 127 def test_uuid_option(runner):128 @click.command()1 unmodified line130 "--u", default="ba122011-349f-423b-873b-9d6a79c688ab", type=click.UUID131 )132 def cli(u):133 assert type(u) is uuid.UUID134- click.echo("U:[%s]" % u)134+ click.echo("U:[{}]".format(u))135 136 result = runner.invoke(cli, [])137 assert not result.exception138 assert "U:[ba122011-349f-423b-873b-9d6a79c688ab]" in result.output3 unmodified lines142 assert "U:[821592c1-c50e-4971-9cd6-e89dc6832f86]" in result.output143 144 result = runner.invoke(cli, ["--u=bar"])145 assert result.exception146- assert 'Invalid value for "--u": bar is not a valid UUID value' in result.output146+ assert "Invalid value for '--u': bar is not a valid UUID value" in result.output147 148 149 def test_float_option(runner):150 @click.command()151 @click.option("--foo", default=42, type=click.FLOAT)152 def cli(foo):153 assert type(foo) is float154- click.echo("FOO:[%s]" % foo)154+ click.echo("FOO:[{}]".format(foo))155 156 result = runner.invoke(cli, [])157 assert not result.exception158 assert "FOO:[42.0]" in result.output3 unmodified lines162 assert "FOO:[23.5]" in result.output163 164 result = runner.invoke(cli, ["--foo=bar"])165 assert result.exception166- assert 'Invalid value for "--foo": bar is not a valid float' in result.output166+ assert "Invalid value for '--foo': bar is not a valid float" in result.output167 168 169 def test_boolean_option(runner):170 for default in True, False:10 unmodified lines181 assert not result.exception182 assert result.output == "False\n"183 result = runner.invoke(cli, [])184 assert not result.exception185- assert result.output == "%s\n" % default185+ assert result.output == "{}\n".format(default)186 187 for default in True, False:188 189 @click.command()2 unmodified lines192 click.echo(flag)193 194 result = runner.invoke(cli, ["--flag"])195 assert not result.exception196- assert result.output == "%s\n" % (not default)196+ assert result.output == "{}\n".format(not default)197 result = runner.invoke(cli, [])198 assert not result.exception199- assert result.output == "%s\n" % (default)199+ assert result.output == "{}\n".format(default)200 201 202 def test_boolean_conversion(runner):203 for default in True, False:14 unmodified lines218 assert result.output == "False\n"219 220 result = runner.invoke(cli, [])221 assert not result.exception222- assert result.output == "%s\n" % default222+ assert result.output == "{}\n".format(default)223 224 225 def test_file_option(runner):226 @click.command()53 unmodified lines280 os.mkdir("example.txt")281 result_in = runner.invoke(input_non_lazy, ["--file=example.txt"])282 assert result_in.exit_code == 2283 assert (284- 'Invalid value for "--file": Could not open file: example.txt'284+ "Invalid value for '--file': Could not open file: example.txt"285 in result_in.output286 )287 288 13 unmodified lines302 with open("test/foo.txt", "rb") as f:303 assert f.read() == b"meh\n"304 305 result = runner.invoke(write_to_dir, ["-O", "test/foo.txt"])306- assert (307- 'Invalid value for "-O": Directory "test/foo.txt" is a file.'308- in result.output309- )306+ assert "is a file" in result.output307 308 @click.command()309 @click.option("-f", type=click.Path(exists=True))310 def showtype(f):314- click.echo("is_file=%s" % os.path.isfile(f))315- click.echo("is_dir=%s" % os.path.isdir(f))311+ click.echo("is_file={}".format(os.path.isfile(f)))312+ click.echo("is_dir={}".format(os.path.isdir(f)))313 314 with runner.isolated_filesystem():315 result = runner.invoke(showtype, ["-f", "xxx"])319- assert (320- 'Error: Invalid value for "-f": Path "xxx" does not exist' in result.output321- )316+ assert "does not exist" in result.output317 318 result = runner.invoke(showtype, ["-f", "."])319 assert "is_file=False" in result.output320 assert "is_dir=True" in result.output321 322 @click.command()323 @click.option("-f", type=click.Path())324 def exists(f):330- click.echo("exists=%s" % os.path.exists(f))325+ click.echo("exists={}".format(os.path.exists(f)))326 327 with runner.isolated_filesystem():328 result = runner.invoke(exists, ["-f", "xxx"])329 assert "exists=False" in result.output14 unmodified lines344 345 result = runner.invoke(cli, ["--method=meh"])346 assert result.exit_code == 2347 assert (353- 'Invalid value for "--method": invalid choice: meh. '354- "(choose from foo, bar, baz)" in result.output348+ "Invalid value for '--method': invalid choice: meh."349+ " (choose from foo, bar, baz)" in result.output350 )351 352 result = runner.invoke(cli, ["--help"])353 assert "--method [foo|bar|baz]" in result.output15 unmodified lines369 370 result = runner.invoke(cli, ["--start_date=2015-09"])371 assert result.exit_code == 2372 assert (378- 'Invalid value for "--start_date": '379- "invalid datetime format: 2015-09. "380- "(choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"373+ "Invalid value for '--start_date':"374+ " invalid datetime format: 2015-09."375+ " (choose from %Y-%m-%d, %Y-%m-%dT%H:%M:%S, %Y-%m-%d %H:%M:%S)"376 ) in result.output377 378 result = runner.invoke(cli, ["--help"])379 assert (24 unmodified lines404 405 result = runner.invoke(cli, ["--x=6"])406 assert result.exit_code == 2407 assert (413- 'Invalid value for "--x": 6 is not in the valid range of 0 to 5.\n'408+ "Invalid value for '--x': 6 is not in the valid range of 0 to 5.\n"409 in result.output410 )411 412 @click.command()26 unmodified lines439 440 result = runner.invoke(cli, ["--x=6.0"])441 assert result.exit_code == 2442 assert (448- 'Invalid value for "--x": 6.0 is not in the valid range of 0 to 5.\n'443+ "Invalid value for '--x': 6.0 is not in the valid range of 0 to 5.\n"444 in result.output445 )446 447 @click.command()21 unmodified lines469 click.echo(foo)470 471 result = runner.invoke(cli, [])472 assert result.exit_code == 2478- assert 'Missing option "--foo"' in result.output473+ assert "Missing option '--foo'" in result.output474 475 476 def test_evaluation_order(runner):477 called = []83 unmodified linesmodified:tests/test_chain.py+16 added-43 removed
5 unmodified lines6 7 8 def debug():9 click.echo(10- "%s=%s"11- % (sys._getframe(1).f_code.co_name, "|".join(click.get_current_context().args),)10+ "{}={}".format(11+ sys._getframe(1).f_code.co_name, "|".join(click.get_current_context().args)12+ )13 )14 15 16 def test_basic_chaining(runner):59 unmodified lines76 77 @cli.command("sdist")78 @click.option("--format")79 def sdist(format):79- click.echo("sdist called %s" % format)80+ click.echo("sdist called {}".format(format))81 82 @cli.command("bdist")83 @click.option("--format")84 def bdist(format):84- click.echo("bdist called %s" % format)85+ click.echo("bdist called {}".format(format))86 87 result = runner.invoke(cli, ["bdist", "--format=1", "sdist", "--format=2"])88 assert not result.exception88- assert result.output.splitlines() == [89- "bdist called 1",90- "sdist called 2",91- ]89+ assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]90 91 92 def test_chaining_with_arguments(runner):93 @click.group(chain=True)2 unmodified lines96 97 @cli.command("sdist")98 @click.argument("format")99 def sdist(format):102- click.echo("sdist called %s" % format)100+ click.echo("sdist called {}".format(format))101 102 @cli.command("bdist")103 @click.argument("format")104 def bdist(format):107- click.echo("bdist called %s" % format)105+ click.echo("bdist called {}".format(format))106 107 result = runner.invoke(cli, ["bdist", "1", "sdist", "2"])108 assert not result.exception111- assert result.output.splitlines() == [112- "bdist called 1",113- "sdist called 2",114- ]109+ assert result.output.splitlines() == ["bdist called 1", "sdist called 2"]110 111 112 def test_pipeline(runner):113 @click.group(chain=True, invoke_without_command=True)26 unmodified lines140 return processor141 142 result = runner.invoke(cli, ["-i", "-"], input="foo\nbar")143 assert not result.exception149- assert result.output.splitlines() == [150- "foo",151- "bar",152- ]144+ assert result.output.splitlines() == ["foo", "bar"]145 146 result = runner.invoke(cli, ["-i", "-", "strip"], input="foo \n bar")147 assert not result.exception156- assert result.output.splitlines() == [157- "foo",158- "bar",159- ]148+ assert result.output.splitlines() == ["foo", "bar"]149 150 result = runner.invoke(cli, ["-i", "-", "strip", "uppercase"], input="foo \n bar")151 assert not result.exception163- assert result.output.splitlines() == [164- "FOO",165- "BAR",166- ]152+ assert result.output.splitlines() == ["FOO", "BAR"]153 154 155 def test_args_and_chain(runner):156 @click.group(chain=True)13 unmodified lines170 debug()171 172 result = runner.invoke(cli, ["a", "b", "c"])173 assert not result.exception188- assert result.output.splitlines() == [189- "cli=",190- "a=",191- "b=",192- "c=",193- ]174+ assert result.output.splitlines() == ["cli=", "a=", "b=", "c="]175 176 177 def test_multicommand_arg_behavior(runner):178 with pytest.raises(RuntimeError):12 unmodified lines191 192 @click.group(chain=True)193 @click.argument("arg")194 def cli(arg):214- click.echo("cli:%s" % arg)195+ click.echo("cli:{}".format(arg))196 197 @cli.command()198 def a():199 click.echo("a")200 201 result = runner.invoke(cli, ["foo", "a"])202 assert not result.exception222- assert result.output.splitlines() == [223- "cli:foo",224- "a",225- ]203+ assert result.output.splitlines() == ["cli:foo", "a"]204 205 206 @pytest.mark.xfail207 def test_multicommand_chaining(runner):18 unmodified lines226 debug()227 228 result = runner.invoke(cli, ["l1a", "l2a", "l1b"])229 assert not result.exception252- assert result.output.splitlines() == [253- "cli=",254- "l1a=",255- "l2a=",256- "l1b=",257- ]230+ assert result.output.splitlines() == ["cli=", "l1a=", "l2a=", "l1b="]modified:tests/test_commands.py+5 added-5 removed
24 unmodified lines25 26 @cli.command()27 @click.option("--count", default=1)28 def test(count):29- click.echo("Count: %d" % count)29+ click.echo("Count: {:d}".format(count))30 31 @cli.command()32 @click.option("--count", default=1)33 @click.pass_context67 unmodified lines101 def test_group_with_args(runner):102 @click.group()103 @click.argument("obj")104 def cli(obj):105- click.echo("obj=%s" % obj)105+ click.echo("obj={}".format(obj))106 107 @cli.command()108 def move():109 click.echo("move")100 unmodified lines210 211 @cli.command()212 @click.pass_context213 def sync(ctx):214- click.echo("Debug is %s" % (ctx.obj["DEBUG"] and "on" or "off"))214+ click.echo("Debug is {}".format("on" if ctx.obj["DEBUG"] else "off"))215 216 result = runner.invoke(cli, ["sync"])217 assert result.exception is None218 assert result.output == "Debug is off\n"44 unmodified lines263 @click.command(context_settings=dict(ignore_unknown_options=True))264 @click.argument("args", nargs=-1, type=click.UNPROCESSED)265 @click.option("--verbose", "-v", count=True)266 def cli(verbose, args):267- click.echo("Verbosity: %s" % verbose)268- click.echo("Args: %s" % "|".join(args))267+ click.echo("Verbosity: {}".format(verbose))268+ click.echo("Args: {}".format("|".join(args)))269 270 result = runner.invoke(cli, ["-foo", "-vvvvx", "--muhaha", "x", "y", "-x"])271 assert not result.exception272 assert result.output.splitlines() == [29 unmodified linesmodified:tests/test_context.py+3 added-3 removed
88 unmodified lines89 result = runner.invoke(cli, ["test"])90 assert result.exception is not None91 assert isinstance(result.exception, RuntimeError)92 assert (93- "Managed to invoke callback without a context object "94- "of type 'Foo' existing" in str(result.exception)93+ "Managed to invoke callback without a context object of type"94+ " 'Foo' existing" in str(result.exception)95 )96 97 98 def test_multi_enter(runner):29 unmodified lines128 assert click.get_current_context(silent=True) is None129 130 131 def test_context_meta(runner):132- LANG_KEY = __name__ + ".lang"132+ LANG_KEY = "{}.lang".format(__name__)133 134 def set_language(value):135 click.get_current_context().meta[LANG_KEY] = value136 127 unmodified linesmodified:tests/test_defaults.py+4 added-10 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:[%s]" % foo)9+ click.echo("FOO:[{}]".format(foo))10 11 result = runner.invoke(cli, [])12 assert not result.exception13 assert "FOO:[42.0]" in result.output8 unmodified lines22 click.echo(item)23 24 result = runner.invoke(cli, [])25 assert not result.exception26- assert result.output.splitlines() == [27- "23.0",28- "42.0",29- ]26+ assert result.output.splitlines() == ["23.0", "42.0"]27 28 29 def test_nargs_plus_multiple(runner):30 @click.command()1 unmodified line32 "--arg", default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT33 )34 def cli(arg):35 for item in arg:39- click.echo("<%d|%d>" % item)36+ click.echo("<{0[0]:d}|{0[1]:d}>".format(item))37 38 result = runner.invoke(cli, [])39 assert not result.exception43- assert result.output.splitlines() == [44- "<1|2>",45- "<3|4>",46- ]40+ assert result.output.splitlines() == ["<1|2>", "<3|4>"]modified:tests/test_formatting.py+15 added-15 removed
149 unmodified lines150 def test_formatting_usage_error(runner):151 @click.command()152 @click.argument("arg")153 def cmd(arg):154- click.echo("arg:" + arg)154+ click.echo("arg:{}".format(arg))155 156 result = runner.invoke(cmd, [])157 assert result.exit_code == 2158 assert result.output.splitlines() == [159 "Usage: cmd [OPTIONS] ARG",160- 'Try "cmd --help" for help.',160+ "Try 'cmd --help' for help.",161 "",162- 'Error: Missing argument "ARG".',162+ "Error: Missing argument 'ARG'.",163 ]164 165 166 def test_formatting_usage_error_metavar_missing_arg(runner):10 unmodified lines177 result = runner.invoke(cmd, [])178 assert result.exit_code == 2179 assert result.output.splitlines() == [180 "Usage: cmd [OPTIONS] metavar",181- 'Try "cmd --help" for help.',181+ "Try 'cmd --help' for help.",182 "",183- 'Error: Missing argument "metavar".',183+ "Error: Missing argument 'metavar'.",184 ]185 186 187 def test_formatting_usage_error_metavar_bad_arg(runner):5 unmodified lines193 result = runner.invoke(cmd, ["3.14"])194 assert result.exit_code == 2195 assert result.output.splitlines() == [196 "Usage: cmd [OPTIONS] metavar",197- 'Try "cmd --help" for help.',197+ "Try 'cmd --help' for help.",198 "",199- 'Error: Invalid value for "metavar": 3.14 is not a valid integer',199+ "Error: Invalid value for 'metavar': 3.14 is not a valid integer",200 ]201 202 203 def test_formatting_usage_error_nested(runner):3 unmodified lines207 208 @cmd.command()209 @click.argument("bar")210 def foo(bar):211- click.echo("foo:" + bar)211+ click.echo("foo:{}".format(bar))212 213 result = runner.invoke(cmd, ["foo"])214 assert result.exit_code == 2215 assert result.output.splitlines() == [216 "Usage: cmd foo [OPTIONS] BAR",217- 'Try "cmd foo --help" for help.',217+ "Try 'cmd foo --help' for help.",218 "",219- 'Error: Missing argument "BAR".',219+ "Error: Missing argument 'BAR'.",220 ]221 222 223 def test_formatting_usage_error_no_help(runner):224 @click.command(add_help_option=False)225 @click.argument("arg")226 def cmd(arg):227- click.echo("arg:" + arg)227+ click.echo("arg:{}".format(arg))228 229 result = runner.invoke(cmd, [])230 assert result.exit_code == 2231 assert result.output.splitlines() == [232 "Usage: cmd [OPTIONS] ARG",233 "",234- 'Error: Missing argument "ARG".',234+ "Error: Missing argument 'ARG'.",235 ]236 237 238 def test_formatting_usage_custom_help(runner):239 @click.command(context_settings=dict(help_option_names=["--man"]))240 @click.argument("arg")241 def cmd(arg):242- click.echo("arg:" + arg)242+ click.echo("arg:{}".format(arg))243 244 result = runner.invoke(cmd, [])245 assert result.exit_code == 2246 assert result.output.splitlines() == [247 "Usage: cmd [OPTIONS] ARG",248- 'Try "cmd --man" for help.',248+ "Try 'cmd --man' for help.",249 "",250- 'Error: Missing argument "ARG".',250+ "Error: Missing argument 'ARG'.",251 ]252 253 254 def test_formatting_custom_type_metavar(runner):99 unmodified linesmodified:tests/test_options.py+9 added-12 removed
45 unmodified lines46 @click.command()47 @click.option("--item", type=(str, int), multiple=True)48 def copy(item):49 for item in item:50- click.echo("name=%s id=%d" % item)50+ click.echo("name={0[0]} id={0[1]:d}".format(item))51 52 result = runner.invoke(copy, ["--item", "peter", "1", "--item", "max", "2"])53 assert not result.exception54- assert result.output.splitlines() == [55- "name=peter id=1",56- "name=max id=2",57- ]54+ assert result.output.splitlines() == ["name=peter id=1", "name=max id=2"]55 56 57 def test_counting(runner):58 @click.command()59 @click.option("-v", count=True, help="Verbosity", type=click.IntRange(0, 3))60 def cli(v):64- click.echo("verbosity=%d" % v)61+ click.echo("verbosity={:d}".format(v))62 63 result = runner.invoke(cli, ["-vvv"])64 assert not result.exception65 assert result.output == "verbosity=3\n"66 67 result = runner.invoke(cli, ["-vvvv"])68 assert result.exception69 assert (73- 'Invalid value for "-v": 4 is not in the valid range of 0 to 3.'70+ "Invalid value for '-v': 4 is not in the valid range of 0 to 3."71 in result.output72 )73 74 result = runner.invoke(cli, [])26 unmodified lines101 assert result.output == "foo\nbar\n"102 103 result = runner.invoke(cli, [])104 assert result.exception108- assert 'Error: Missing option "-m" / "--message".' in result.output105+ assert "Error: Missing option '-m' / '--message'." in result.output106 107 108 def test_empty_envvar(runner):109 @click.command()110 @click.option("--mypath", type=click.Path(exists=True), envvar="MYPATH")111 def cli(mypath):115- click.echo("mypath: %s" % mypath)112+ click.echo("mypath: {}".format(mypath))113 114 result = runner.invoke(cli, [], env={"MYPATH": ""})115 assert result.exit_code == 0116 assert result.output == "mypath: None\n"28 unmodified lines145 result = runner.invoke(146 cmd,147 [],148 auto_envvar_prefix="TEST",152- env={"TEST_ARG": "foo%sbar" % os.path.pathsep},149+ env={"TEST_ARG": "foo{}bar".format(os.path.pathsep)},150 )151 assert not result.exception152 assert result.output == "foo|bar\n"153 148 unmodified lines302 def cmd(foo):303 click.echo(foo)304 305 result = runner.invoke(cmd, ["--foo", "-1"])309- assert 'Invalid value for "--foo": Value needs to be positive' in result.output306+ assert "Invalid value for '--foo': Value needs to be positive" in result.output307 308 result = runner.invoke(cmd, ["--foo", "42"])309 assert result.output == "42\n"310 44 unmodified lines355 356 result = runner.invoke(cmd)357 assert result.exit_code == 2358 error, separator, choices = result.output.partition("Choose from")362- assert 'Error: Missing option "--foo". ' in error359+ assert "Error: Missing option '--foo'. " in error360 assert "Choose from" in separator361 assert "foo" in choices362 assert "bar" in choices363 195 unmodified linesmodified:tests/test_testing.py+4 added-4 removed
63 unmodified lines64 def test_prompts():65 @click.command()66 @click.option("--foo", prompt=True)67 def test(foo):68- click.echo("foo=%s" % foo)68+ click.echo("foo={}".format(foo))69 70 runner = CliRunner()71 result = runner.invoke(test, input="wau wau\n")72 assert not result.exception1 unmodified line74 75 @click.command()76 @click.option("--foo", prompt=True, hide_input=True)77 def test(foo):78- click.echo("foo=%s" % foo)78+ click.echo("foo={}".format(foo))79 80 runner = CliRunner()81 result = runner.invoke(test, input="wau wau\n")82 assert not result.exception47 unmodified lines130 assert result.output == "hello world\n"131 assert not result.exception132 133 result = runner.invoke(cli, color=True)134- assert result.output == click.style("hello world", fg="blue") + "\n"134+ assert result.output == "{}\n".format(click.style("hello world", fg="blue"))135 assert not result.exception136 137 138 def test_with_color_but_pause_not_blocking():79 unmodified lines218 219 def test_env():220 @click.command()221 def cli_env():222- click.echo("ENV=%s" % os.environ["TEST_CLICK_ENV"])222+ click.echo("ENV={}".format(os.environ["TEST_CLICK_ENV"]))223 224 runner = CliRunner()225 226 env_orig = dict(os.environ)77 unmodified linesmodified:tests/test_utils.py+4 added-4 removed
201 unmodified lines202 assert styled_text == "\x1b[31mfoo\x1b[0m"203 204 click.echo(styled_text, color=False)205 out, err = capfd.readouterr()206- assert out == text + "\n"206+ assert out == "{}\n".format(text)207 208 click.echo(styled_text, color=True)209 out, err = capfd.readouterr()210- assert out == styled_text + "\n"210+ assert out == "{}\n".format(styled_text)211 212 isatty = True213 click.echo(styled_text)214 out, err = capfd.readouterr()215- assert out == styled_text + "\n"215+ assert out == "{}\n".format(styled_text)216 217 isatty = False218 click.echo(styled_text)219 out, err = capfd.readouterr()220- assert out == text + "\n"220+ assert out == "{}\n".format(text)221 222 223 @pytest.mark.skipif(WIN, reason="Test too complex to make work windows.")224 def test_echo_writing_to_standard_error(capfd, monkeypatch):171 unmodified linesmodified:README.rst+2 added-3 removed
36 unmodified lines37 import click38 39 @click.command()40 @click.option("--count", default=1, help="Number of greetings.")41- @click.option("--name", prompt="Your name",42- help="The person to greet.")41+ @click.option("--name", prompt="Your name", help="The person to greet.")42 def hello(count, name):43 """Simple program that greets NAME for a total of COUNT times."""44 for _ in range(count):46- click.echo("Hello, %s!" % name)45+ click.echo(f"Hello, {name}!")46 47 if __name__ == '__main__':48 hello()49 30 unmodified lines