diff options
| author | David Lord <davidism@gmail.com> | 2020-03-08 08:57:08 -0700 |
|---|---|---|
| committer | David Lord <davidism@gmail.com> | 2020-03-08 08:57:08 -0700 |
| commit | 718485be48263056e7036ea9a60ce11b47e2fc26 (patch) | |
| tree | 0fa1b49ed926f18ab3d247c2cacada892908123a /src | |
| parent | f8f02bfc63cb6e63b7a3373384758f7226553408 (diff) | |
| download | click-718485be48263056e7036ea9a60ce11b47e2fc26.tar.gz | |
manual cleanup
Diffstat (limited to 'src')
| -rw-r--r-- | src/click/_bashcomplete.py | 2 | ||||
| -rw-r--r-- | src/click/_compat.py | 10 | ||||
| -rw-r--r-- | src/click/_termui_impl.py | 20 | ||||
| -rw-r--r-- | src/click/_unicodefun.py | 47 | ||||
| -rw-r--r-- | src/click/_winconsole.py | 4 | ||||
| -rw-r--r-- | src/click/core.py | 101 | ||||
| -rw-r--r-- | src/click/decorators.py | 4 | ||||
| -rw-r--r-- | src/click/exceptions.py | 28 | ||||
| -rw-r--r-- | src/click/formatting.py | 14 | ||||
| -rw-r--r-- | src/click/parser.py | 14 | ||||
| -rw-r--r-- | src/click/termui.py | 26 | ||||
| -rw-r--r-- | src/click/testing.py | 6 | ||||
| -rw-r--r-- | src/click/types.py | 73 | ||||
| -rw-r--r-- | src/click/utils.py | 12 |
14 files changed, 187 insertions, 174 deletions
diff --git a/src/click/_bashcomplete.py b/src/click/_bashcomplete.py index 3113808..8bca244 100644 --- a/src/click/_bashcomplete.py +++ b/src/click/_bashcomplete.py @@ -98,7 +98,7 @@ def get_completion_script(prog_name, complete_var, shell): return ( script % { - "complete_func": "_%s_completion" % cf_name, + "complete_func": "_{}_completion".format(cf_name), "script_names": prog_name, "autocomplete_var": complete_var, } diff --git a/src/click/_compat.py b/src/click/_compat.py index 38ab8c0..ed57a18 100644 --- a/src/click/_compat.py +++ b/src/click/_compat.py @@ -510,7 +510,7 @@ def _wrap_io_open(file, mode, encoding, errors): if not PY2 or binary: return io.open(file, mode, **kwargs) - f = io.open(file, "b" + mode.replace("t", "")) + f = io.open(file, "{}b".format(mode.replace("t", ""))) return _make_text_stream(f, **kwargs) @@ -535,10 +535,10 @@ def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False # Some usability stuff for atomic writes if "a" in mode: raise ValueError( - "Appending to an existing file is not supported, because that " - "would involve an expensive `copy`-operation to a temporary " - "file. Open the file in normal `w`-mode and copy explicitly " - "if that's what you're after." + "Appending to an existing file is not supported, because that" + " would involve an expensive `copy`-operation to a temporary" + " file. Open the file in normal `w`-mode and copy explicitly" + " if that's what you're after." ) if "x" in mode: raise ValueError("Use the `overwrite`-parameter instead.") diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py index 28a0d9c..c6e86cc 100644 --- a/src/click/_termui_impl.py +++ b/src/click/_termui_impl.py @@ -167,20 +167,19 @@ class ProgressBar(object): hours = t % 24 t //= 24 if t > 0: - days = t - return "%dd %02d:%02d:%02d" % (days, hours, minutes, seconds) + return "{}d {:02}:{:02}:{:02}".format(t, hours, minutes, seconds) else: - return "%02d:%02d:%02d" % (hours, minutes, seconds) + return "{:02}:{:02}:{:02}".format(hours, minutes, seconds) return "" def format_pos(self): pos = str(self.pos) if self.length_known: - pos += "/%s" % self.length + pos += "/{}".format(self.length) return pos def format_pct(self): - return ("% 4d%%" % int(self.pct * 100))[1:] + return "{: 4}%".format(int(self.pct * 100))[1:] def format_bar(self): if self.length_known: @@ -347,7 +346,10 @@ def pager(generator, color=None): fd, filename = tempfile.mkstemp() os.close(fd) try: - if hasattr(os, "system") and os.system("more %s" % shlex_quote(filename)) == 0: + if ( + hasattr(os, "system") + and os.system("more {}".format(shlex_quote(filename))) == 0 + ): return _pipepager(generator, "more", color) return _nullpager(stdout, generator, color) finally: @@ -366,7 +368,7 @@ def _pipepager(generator, cmd, color): # condition that cmd_detail = cmd.rsplit("/", 1)[-1].split() if color is None and cmd_detail[0] == "less": - less_flags = os.environ.get("LESS", "") + " ".join(cmd_detail[1:]) + less_flags = "{}{}".format(os.environ.get("LESS", ""), " ".join(cmd_detail[1:])) if not less_flags: env["LESS"] = "-R" color = True @@ -446,7 +448,7 @@ class Editor(object): if WIN: return "notepad" for editor in "sensible-editor", "vim", "nano": - if os.system("which %s >/dev/null 2>&1" % editor) == 0: + if os.system("which {} >/dev/null 2>&1".format(editor)) == 0: return editor return "vi" @@ -467,7 +469,7 @@ class Editor(object): ) exit_code = c.wait() if exit_code != 0: - raise ClickException("%s: Editing failed!" % editor) + raise ClickException("{}: Editing failed!".format(editor)) except OSError as e: raise ClickException("{}: Editing failed: {}".format(editor, e)) diff --git a/src/click/_unicodefun.py b/src/click/_unicodefun.py index 01c4bc3..781c365 100644 --- a/src/click/_unicodefun.py +++ b/src/click/_unicodefun.py @@ -38,12 +38,12 @@ def _check_for_unicode_literals(): warn( Warning( - "Click detected the use of the unicode_literals " - "__future__ import. This is heavily discouraged " - "because it can introduce subtle bugs in your " - 'code. You should instead use explicit u"" literals ' - "for your unicode strings. For more information see " - "https://click.palletsprojects.com/en/7.x/python3/" + "Click detected the use of the unicode_literals __future__" + " import. This is heavily discouraged because it can" + " introduce subtle bugs in your code. You should instead" + ' use explicit u"" literals for your unicode strings. For' + " more information see" + " https://click.palletsprojects.com/python3/" ), stacklevel=bad_frame, ) @@ -89,24 +89,25 @@ def _verify_python3_env(): extra += "\n\n" if not good_locales: extra += ( - "Additional information: on this system no suitable UTF-8\n" - "locales were discovered. This most likely requires resolving\n" - "by reconfiguring the locale system." + "Additional information: on this system no suitable" + " UTF-8 locales were discovered. This most likely" + " requires resolving by reconfiguring the locale" + " system." ) elif has_c_utf8: extra += ( - "This system supports the C.UTF-8 locale which is recommended.\n" - "You might be able to resolve your issue by exporting the\n" - "following environment variables:\n\n" + "This system supports the C.UTF-8 locale which is" + " recommended. You might be able to resolve your issue" + " by exporting the following environment variables:\n\n" " export LC_ALL=C.UTF-8\n" " export LANG=C.UTF-8" ) else: extra += ( - "This system lists a couple of UTF-8 supporting locales that\n" - "you can pick from. The following suitable locales were\n" - "discovered: %s" - ) % ", ".join(sorted(good_locales)) + "This system lists a couple of UTF-8 supporting locales" + " that you can pick from. The following suitable" + " locales were discovered: {}".format(", ".join(sorted(good_locales))) + ) bad_locale = None for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"): @@ -116,15 +117,15 @@ def _verify_python3_env(): break if bad_locale is not None: extra += ( - "\n\nClick discovered that you exported a UTF-8 locale\n" - "but the locale system could not pick up from it because\n" - 'it does not exist. The exported locale is "%s" but it\n' - "is not supported" - ) % bad_locale + "\n\nClick discovered that you exported a UTF-8 locale" + " but the locale system could not pick up from it" + " because it does not exist. The exported locale is" + " '{}' but it is not supported".format(bad_locale) + ) raise RuntimeError( "Click will abort further execution because Python 3 was" " configured to use ASCII as encoding for the environment." - " Consult https://click.palletsprojects.com/en/7.x/python3/ for" - " mitigation steps." + extra + " Consult https://click.palletsprojects.com/python3/ for" + " mitigation steps.{}".format(extra) ) diff --git a/src/click/_winconsole.py b/src/click/_winconsole.py index 7b5be34..b6c4274 100644 --- a/src/click/_winconsole.py +++ b/src/click/_winconsole.py @@ -155,7 +155,7 @@ class _WindowsConsoleReader(_WindowsConsoleRawIOBase): # wait for KeyboardInterrupt time.sleep(0.1) if not rv: - raise OSError("Windows error: %s" % GetLastError()) + raise OSError("Windows error: {}".format(GetLastError())) if buffer[0] == EOF: return 0 @@ -172,7 +172,7 @@ class _WindowsConsoleWriter(_WindowsConsoleRawIOBase): return "ERROR_SUCCESS" elif errno == ERROR_NOT_ENOUGH_MEMORY: return "ERROR_NOT_ENOUGH_MEMORY" - return "Windows error %s" % errno + return "Windows error {}".format(errno) def write(self, b): bytes_to_be_written = len(b) diff --git a/src/click/core.py b/src/click/core.py index 3537e59..2102696 100644 --- a/src/click/core.py +++ b/src/click/core.py @@ -62,7 +62,7 @@ def fast_exit(code): def _bashcomplete(cmd, prog_name, complete_var=None): """Internal handler for the bash completion support.""" if complete_var is None: - complete_var = "_%s_COMPLETE" % (prog_name.replace("-", "_")).upper() + complete_var = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper()) complete_instr = os.environ.get(complete_var) if not complete_instr: return @@ -78,20 +78,18 @@ def _check_multicommand(base_command, cmd_name, cmd, register=False): return if register: hint = ( - "It is not possible to add multi commands as children to " - "another multi command that is in chain mode" + "It is not possible to add multi commands as children to" + " another multi command that is in chain mode." ) else: hint = ( - "Found a multi command as subcommand to a multi command " - "that is in chain mode. This is not supported" + "Found a multi command as subcommand to a multi command" + " that is in chain mode. This is not supported." ) raise RuntimeError( - '%s. Command "%s" is set to chain and "%s" was ' - "added as subcommand but it in itself is a " - 'multi command. ("%s" is a %s within a chained ' - '%s named "%s").' - % ( + "{}. Command '{}' is set to chain and '{}' was added as" + " subcommand but it in itself is a multi command. ('{}' is a {}" + " within a chained {} named '{}').".format( hint, base_command.name, cmd_name, @@ -117,9 +115,9 @@ def invoke_param_callback(callback, ctx, param, value): warn( Warning( - 'Invoked legacy parameter callback "%s". The new ' - "signature for such callbacks starting with " - "click 2.0 is (ctx, param, value)." % callback + "Invoked legacy parameter callback '{}'. The new" + " signature for such callbacks starting with Click 2.0" + " is (ctx, param, value).".format(callback) ), stacklevel=3, ) @@ -129,9 +127,7 @@ def invoke_param_callback(callback, ctx, param, value): @contextmanager def augment_usage_errors(ctx, param=None): - """Context manager that attaches extra information to exceptions that - fly. - """ + """Context manager that attaches extra information to exceptions.""" try: yield except BadParameter as e: @@ -380,7 +376,7 @@ class Context(object): and self.info_name is not None ): auto_envvar_prefix = "{}_{}".format( - parent.auto_envvar_prefix, self.info_name.upper(), + parent.auto_envvar_prefix, self.info_name.upper() ) else: auto_envvar_prefix = auto_envvar_prefix.upper() @@ -463,7 +459,7 @@ class Context(object): Example usage:: - LANG_KEY = __name__ + '.lang' + LANG_KEY = f'{__name__}.lang' def set_language(value): ctx = get_current_context() @@ -510,7 +506,7 @@ class Context(object): if self.info_name is not None: rv = self.info_name if self.parent is not None: - rv = self.parent.command_path + " " + rv + rv = "{} {}".format(self.parent.command_path, rv) return rv.lstrip() def find_root(self): @@ -773,7 +769,9 @@ class BaseCommand(object): args = list(args) if prog_name is None: - prog_name = make_str(os.path.basename(sys.argv and sys.argv[0] or __file__)) + prog_name = make_str( + os.path.basename(sys.argv[0] if sys.argv else __file__) + ) # Hook for the Bash completion. This only activates if the Bash # completion is actually enabled, otherwise this is quite a fast @@ -1053,8 +1051,9 @@ class Command(BaseCommand): if args and not ctx.allow_extra_args and not ctx.resilient_parsing: ctx.fail( - "Got unexpected extra argument%s (%s)" - % (len(args) != 1 and "s" or "", " ".join(map(make_str, args))) + "Got unexpected extra argument{} ({})".format( + "s" if len(args) != 1 else "", " ".join(map(make_str, args)) + ) ) ctx.args = args @@ -1126,8 +1125,8 @@ class MultiCommand(Command): for param in self.params: if isinstance(param, Argument) and not param.required: raise RuntimeError( - "Multi commands in chain mode cannot " - "have optional arguments." + "Multi commands in chain mode cannot have" + " optional arguments." ) def collect_usage_pieces(self, ctx): @@ -1267,7 +1266,7 @@ class MultiCommand(Command): # set to ``*`` to inform the command that subcommands are executed # but nothing else. with ctx: - ctx.invoked_subcommand = args and "*" or None + ctx.invoked_subcommand = "*" if args else None Command.invoke(self, ctx) # Otherwise we make every single context and invoke them in a @@ -1314,7 +1313,7 @@ class MultiCommand(Command): if cmd is None and not ctx.resilient_parsing: if split_opt(cmd_name)[0]: self.parse_args(ctx, ctx.args) - ctx.fail('No such command "%s".' % original_cmd_name) + ctx.fail("No such command '{}'.".format(original_cmd_name)) return cmd_name, cmd, args[1:] @@ -1556,10 +1555,9 @@ class Parameter(object): if self.type.is_composite: if self.nargs <= 1: raise TypeError( - "Attempted to invoke composite type " - "but nargs has been set to %s. This is " - "not supported; nargs needs to be set to " - "a fixed value > 1." % self.nargs + "Attempted to invoke composite type but nargs has" + " been set to {}. This is not supported; nargs" + " needs to be set to a fixed value > 1.".format(self.nargs) ) if self.multiple: return tuple(self.type(x or (), self, ctx) for x in value or ()) @@ -1652,7 +1650,7 @@ class Parameter(object): indicate which param caused the error. """ hint_list = self.opts or [self.human_readable_name] - return " / ".join('"%s"' % x for x in hint_list) + return " / ".join(repr(x) for x in hint_list) class Option(Parameter): @@ -1794,7 +1792,7 @@ class Option(Parameter): raise TypeError("Name defined twice") name = decl else: - split_char = decl[:1] == "/" and ";" or "/" + split_char = ";" if decl[:1] == "/" else "/" if split_char in decl: first, second = decl.split(split_char, 1) first = first.rstrip() @@ -1821,9 +1819,8 @@ class Option(Parameter): if not opts and not secondary_opts: raise TypeError( - "No options defined but a name was passed (%s). " - "Did you mean to declare an argument instead " - "of an option?" % name + "No options defined but a name was passed ({}). Did you" + " mean to declare an argument instead of an option?".format(name) ) return name, opts, secondary_opts @@ -1844,16 +1841,15 @@ class Option(Parameter): if self.is_flag: kwargs.pop("nargs", None) + action_const = "{}_const".format(action) if self.is_bool_flag and self.secondary_opts: + parser.add_option(self.opts, action=action_const, const=True, **kwargs) parser.add_option( - self.opts, action=action + "_const", const=True, **kwargs - ) - parser.add_option( - self.secondary_opts, action=action + "_const", const=False, **kwargs + self.secondary_opts, action=action_const, const=False, **kwargs ) else: parser.add_option( - self.opts, action=action + "_const", const=self.flag_value, **kwargs + self.opts, action=action_const, const=self.flag_value, **kwargs ) else: kwargs["action"] = action @@ -1869,7 +1865,7 @@ class Option(Parameter): if any_slashes: any_prefix_is_slash[:] = [True] if not self.is_flag and not self.count: - rv += " " + self.make_metavar() + rv += " {}".format(self.make_metavar()) return rv rv = [_write_opts(self.opts)] @@ -1885,18 +1881,17 @@ class Option(Parameter): envvar = "{}_{}".format(ctx.auto_envvar_prefix, self.name.upper()) if envvar is not None: extra.append( - "env var: %s" - % ( - ", ".join("%s" % d for d in envvar) + "env var: {}".format( + ", ".join(str(d) for d in envvar) if isinstance(envvar, (list, tuple)) - else envvar, + else envvar ) ) if self.default is not None and (self.show_default or ctx.show_default): if isinstance(self.show_default, string_types): default_string = "({})".format(self.show_default) elif isinstance(self.default, (list, tuple)): - default_string = ", ".join("%s" % d for d in self.default) + default_string = ", ".join(str(d) for d in self.default) elif inspect.isfunction(self.default): default_string = "(dynamic)" else: @@ -1906,9 +1901,11 @@ class Option(Parameter): if self.required: extra.append("required") if extra: - help = "{}[{}]".format(help and help + " " or "", "; ".join(extra)) + help = "{}[{}]".format( + "{} ".format(help) if help else "", "; ".join(extra) + ) - return ((any_prefix_is_slash and "; " or " / ").join(rv), help) + return ("; " if any_prefix_is_slash else " / ").join(rv), help def get_default(self, ctx): # If we're a non boolean flag our default is more complex because @@ -2006,7 +2003,7 @@ class Argument(Parameter): if not var: var = self.name.upper() if not self.required: - var = "[%s]" % var + var = "[{}]".format(var) if self.nargs != 1: var += "..." return var @@ -2021,8 +2018,8 @@ class Argument(Parameter): name = name.replace("-", "_").lower() else: raise TypeError( - "Arguments take exactly one " - "parameter declaration, got %d" % len(decls) + "Arguments take exactly one parameter declaration, got" + " {}".format(len(decls)) ) return name, [arg], [] @@ -2030,7 +2027,7 @@ class Argument(Parameter): return [self.make_metavar()] def get_error_hint(self, ctx): - return '"%s"' % self.make_metavar() + return repr(self.make_metavar()) def add_to_parser(self, parser, ctx): parser.add_argument(dest=self.name, nargs=self.nargs, obj=self) diff --git a/src/click/decorators.py b/src/click/decorators.py index 7e10adb..c7b5af6 100644 --- a/src/click/decorators.py +++ b/src/click/decorators.py @@ -67,8 +67,8 @@ def make_pass_decorator(object_type, ensure=False): obj = ctx.find_object(object_type) if obj is None: raise RuntimeError( - "Managed to invoke callback without a " - "context object of type %r existing" % object_type.__name__ + "Managed to invoke callback without a context" + " object of type '{}' existing".format(object_type.__name__) ) return ctx.invoke(f, obj, *args, **kwargs) diff --git a/src/click/exceptions.py b/src/click/exceptions.py index 5f5bf58..9cc2f59 100644 --- a/src/click/exceptions.py +++ b/src/click/exceptions.py @@ -6,7 +6,7 @@ from .utils import echo def _join_param_hints(param_hint): if isinstance(param_hint, (tuple, list)): - return " / ".join('"%s"' % x for x in param_hint) + return " / ".join(repr(x) for x in param_hint) return param_hint @@ -39,7 +39,7 @@ class ClickException(Exception): def show(self, file=None): if file is None: file = get_text_stderr() - echo("Error: %s" % self.format_message(), file=file) + echo("Error: {}".format(self.format_message(), file=file)) class UsageError(ClickException): @@ -56,7 +56,7 @@ class UsageError(ClickException): def __init__(self, message, ctx=None): ClickException.__init__(self, message) self.ctx = ctx - self.cmd = self.ctx and self.ctx.command or None + self.cmd = self.ctx.command if self.ctx else None def show(self, file=None): if file is None: @@ -64,13 +64,13 @@ class UsageError(ClickException): color = None hint = "" if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None: - hint = 'Try "{} {}" for help.\n'.format( - self.ctx.command_path, self.ctx.help_option_names[0], + hint = "Try '{} {}' for help.\n".format( + self.ctx.command_path, self.ctx.help_option_names[0] ) if self.ctx is not None: color = self.ctx.color - echo(self.ctx.get_usage() + "\n%s" % hint, file=file, color=color) - echo("Error: %s" % self.format_message(), file=file, color=color) + echo("{}\n{}".format(self.ctx.get_usage(), hint), file=file, color=color) + echo("Error: {}".format(self.format_message()), file=file, color=color) class BadParameter(UsageError): @@ -102,7 +102,7 @@ class BadParameter(UsageError): elif self.param is not None: param_hint = self.param.get_error_hint(self.ctx) else: - return "Invalid value: %s" % self.message + return "Invalid value: {}".format(self.message) param_hint = _join_param_hints(param_hint) return "Invalid value for {}: {}".format(param_hint, self.message) @@ -144,14 +144,14 @@ class MissingParameter(BadParameter): msg_extra = self.param.type.get_missing_message(self.param) if msg_extra: if msg: - msg += ". " + msg_extra + msg += ". {}".format(msg_extra) else: msg = msg_extra return "Missing {}{}{}{}".format( param_type, - param_hint and " %s" % param_hint or "", - msg and ". " or ".", + " {}".format(param_hint) if param_hint else "", + ". " if msg else ".", msg or "", ) @@ -178,7 +178,7 @@ class NoSuchOption(UsageError): def __init__(self, option_name, message=None, possibilities=None, ctx=None): if message is None: - message = "no such option: %s" % option_name + message = "no such option: {}".format(option_name) UsageError.__init__(self, message, ctx) self.option_name = option_name self.possibilities = possibilities @@ -187,10 +187,10 @@ class NoSuchOption(UsageError): bits = [self.message] if self.possibilities: if len(self.possibilities) == 1: - bits.append("Did you mean %s?" % self.possibilities[0]) + bits.append("Did you mean {}?".format(self.possibilities[0])) else: possibilities = sorted(self.possibilities) - bits.append("(Possible options: %s)" % ", ".join(possibilities)) + bits.append("(Possible options: {})".format(", ".join(possibilities))) return " ".join(bits) diff --git a/src/click/formatting.py b/src/click/formatting.py index de90d6b..319c7f6 100644 --- a/src/click/formatting.py +++ b/src/click/formatting.py @@ -134,7 +134,7 @@ class HelpFormatter(object): :param args: whitespace separated list of arguments. :param prefix: the prefix for the first line. """ - usage_prefix = "%*s%s " % (self.current_indent, prefix, prog) + usage_prefix = "{:>{w}}{} ".format(prefix, prog, w=self.current_indent) text_width = self.width - self.current_indent if text_width >= (term_len(usage_prefix) + 20): @@ -163,7 +163,7 @@ class HelpFormatter(object): def write_heading(self, heading): """Writes a heading into the buffer.""" - self.write("%*s%s:\n" % (self.current_indent, "", heading)) + self.write("{:>{w}}{}:\n".format("", heading, w=self.current_indent)) def write_paragraph(self): """Writes a paragraph into the buffer.""" @@ -204,7 +204,7 @@ class HelpFormatter(object): first_col = min(widths[0], col_max) + col_spacing for first, second in iter_rows(rows, len(widths)): - self.write("%*s%s" % (self.current_indent, "", first)) + self.write("{:>{w}}{}".format("", first, w=self.current_indent)) if not second: self.write("\n") continue @@ -219,10 +219,14 @@ class HelpFormatter(object): lines = wrapped_text.splitlines() if lines: - self.write(lines[0] + "\n") + self.write("{}\n".format(lines[0])) for line in lines[1:]: - self.write("%*s%s\n" % (first_col + self.current_indent, "", line)) + self.write( + "{:>{w}}{}\n".format( + "", line, w=first_col + self.current_indent + ) + ) if len(lines) > 1: # separate long help from next option diff --git a/src/click/parser.py b/src/click/parser.py index b493ed4..f43ebfe 100644 --- a/src/click/parser.py +++ b/src/click/parser.py @@ -80,8 +80,8 @@ def _unpack_args(args, nargs_spec): def _error_opt_args(nargs, opt): if nargs == 1: - raise BadOptionUsage(opt, "%s option requires an argument" % opt) - raise BadOptionUsage(opt, "%s option requires %d arguments" % (opt, nargs)) + raise BadOptionUsage(opt, "{} option requires an argument".format(opt)) + raise BadOptionUsage(opt, "{} option requires {} arguments".format(opt, nargs)) def split_opt(opt): @@ -128,7 +128,7 @@ class Option(object): for opt in opts: prefix, value = split_opt(opt) if not prefix: - raise ValueError("Invalid start character for option (%s)" % opt) + raise ValueError("Invalid start character for option ({})".format(opt)) self.prefixes.add(prefix[0]) if len(prefix) == 1 and len(value) == 1: self._short_opts.append(opt) @@ -161,7 +161,7 @@ class Option(object): elif self.action == "count": state.opts[self.dest] = state.opts.get(self.dest, 0) + 1 else: - raise ValueError("unknown action %r" % self.action) + raise ValueError("unknown action '{}'".format(self.action)) state.order.append(self.obj) @@ -178,7 +178,7 @@ class Argument(object): value = None elif holes != 0: raise BadArgumentUsage( - "argument %s takes %d values" % (self.dest, self.nargs) + "argument {} takes {} values".format(self.dest, self.nargs) ) state.opts[self.dest] = value state.order.append(self.obj) @@ -344,7 +344,7 @@ class OptionParser(object): del state.rargs[:nargs] elif explicit_value is not None: - raise BadOptionUsage(opt, "%s option does not take a value" % opt) + raise BadOptionUsage(opt, "{} option does not take a value".format(opt)) else: value = None @@ -396,7 +396,7 @@ class OptionParser(object): # to the state as new larg. This way there is basic combinatorics # that can be achieved while still ignoring unknown arguments. if self.ignore_unknown_options and unknown_options: - state.largs.append(prefix + "".join(unknown_options)) + state.largs.append("{}{}".format(prefix, "".join(unknown_options))) def _process_opts(self, arg, state): explicit_value = None diff --git a/src/click/termui.py b/src/click/termui.py index c39569f..02ef9e9 100644 --- a/src/click/termui.py +++ b/src/click/termui.py @@ -59,7 +59,7 @@ def _build_prompt( ): prompt = text if type is not None and show_choices and isinstance(type, Choice): - prompt += " (" + ", ".join(map(str, type.choices)) + ")" + prompt += " ({})".format(", ".join(map(str, type.choices))) if default is not None and show_default: prompt = "{} [{}]".format(prompt, _format_default(default)) return prompt + suffix @@ -121,7 +121,7 @@ def prompt( result = None def prompt_func(text): - f = hide_input and hidden_prompt_func or visible_prompt_func + f = hidden_prompt_func if hide_input else visible_prompt_func try: # Write the prompt separately so that we get nice # coloring through colorama on Windows @@ -156,7 +156,7 @@ def prompt( try: result = value_proc(value) except UsageError as e: - echo("Error: %s" % e.message, err=err) # noqa: B306 + echo("Error: {}".format(e.message), err=err) # noqa: B306 continue if not confirmation_prompt: return result @@ -190,7 +190,7 @@ def confirm( ``stdout``, the same as with echo. """ prompt = _build_prompt( - text, prompt_suffix, show_default, default and "Y/n" or "y/N" + text, prompt_suffix, show_default, "Y/n" if default else "y/N" ) while 1: try: @@ -495,24 +495,24 @@ def style( bits = [] if fg: try: - bits.append("\033[%dm" % (_ansi_colors[fg])) + bits.append("\033[{}m".format(_ansi_colors[fg])) except KeyError: - raise TypeError("Unknown color %r" % fg) + raise TypeError("Unknown color '{}'".format(fg)) if bg: try: - bits.append("\033[%dm" % (_ansi_colors[bg] + 10)) + bits.append("\033[{}m".format(_ansi_colors[bg] + 10)) except KeyError: - raise TypeError("Unknown color %r" % bg) + raise TypeError("Unknown color '{}'".format(bg)) if bold is not None: - bits.append("\033[%dm" % (1 if bold else 22)) + bits.append("\033[{}m".format(1 if bold else 22)) if dim is not None: - bits.append("\033[%dm" % (2 if dim else 22)) + bits.append("\033[{}m".format(2 if dim else 22)) if underline is not None: - bits.append("\033[%dm" % (4 if underline else 24)) + bits.append("\033[{}m".format(4 if underline else 24)) if blink is not None: - bits.append("\033[%dm" % (5 if blink else 25)) + bits.append("\033[{}m".format(5 if blink else 25)) if reverse is not None: - bits.append("\033[%dm" % (7 if reverse else 27)) + bits.append("\033[{}m".format(7 if reverse else 27)) bits.append(text) if reset: bits.append(_ansi_reset_all) diff --git a/src/click/testing.py b/src/click/testing.py index c5d1450..a3dba3b 100644 --- a/src/click/testing.py +++ b/src/click/testing.py @@ -109,7 +109,7 @@ class Result(object): def __repr__(self): return "<{} {}>".format( - type(self).__name__, self.exception and repr(self.exception) or "okay", + type(self).__name__, repr(self.exception) if self.exception else "okay" ) @@ -210,12 +210,12 @@ class CliRunner(object): def visible_input(prompt=None): sys.stdout.write(prompt or "") val = input.readline().rstrip("\r\n") - sys.stdout.write(val + "\n") + sys.stdout.write("{}\n".format(val)) sys.stdout.flush() return val def hidden_input(prompt=None): - sys.stdout.write((prompt or "") + "\n") + sys.stdout.write("{}\n".format(prompt or "")) sys.stdout.flush() return input.readline().rstrip("\r\n") diff --git a/src/click/types.py b/src/click/types.py index 8f4b9d2..505c39f 100644 --- a/src/click/types.py +++ b/src/click/types.py @@ -158,10 +158,10 @@ class Choice(ParamType): self.case_sensitive = case_sensitive def get_metavar(self, param): - return "[%s]" % "|".join(self.choices) + return "[{}]".format("|".join(self.choices)) def get_missing_message(self, param): - return "Choose from:\n\t%s." % ",\n\t".join(self.choices) + return "Choose from:\n\t{}.".format(",\n\t".join(self.choices)) def convert(self, value, param, ctx): # Match through normalization and case sensitivity @@ -202,7 +202,7 @@ class Choice(ParamType): ) def __repr__(self): - return "Choice(%r)" % list(self.choices) + return "Choice('{}')".format(list(self.choices)) class DateTime(ParamType): @@ -264,7 +264,7 @@ class IntParamType(ParamType): try: return int(value) except ValueError: - self.fail("%s is not a valid integer" % value, param, ctx) + self.fail("{} is not a valid integer".format(value), param, ctx) def __repr__(self): return "INT" @@ -309,22 +309,24 @@ class IntRange(IntParamType): ) elif self.max is None: self.fail( - "%s is smaller than the minimum valid value " - "%s." % (rv, self.min), + "{} is smaller than the minimum valid value {}.".format( + rv, self.min + ), param, ctx, ) else: self.fail( - "%s is not in the valid range of %s to %s." - % (rv, self.min, self.max), + "{} is not in the valid range of {} to {}.".format( + rv, self.min, self.max + ), param, ctx, ) return rv def __repr__(self): - return "IntRange({!r}, {!r})".format(self.min, self.max) + return "IntRange({}, {})".format(self.min, self.max) class FloatParamType(ParamType): @@ -334,7 +336,9 @@ class FloatParamType(ParamType): try: return float(value) except ValueError: - self.fail("%s is not a valid floating point value" % value, param, ctx) + self.fail( + "{} is not a valid floating point value".format(value), param, ctx + ) def __repr__(self): return "FLOAT" @@ -379,22 +383,24 @@ class FloatRange(FloatParamType): ) elif self.max is None: self.fail( - "%s is smaller than the minimum valid value " - "%s." % (rv, self.min), + "{} is smaller than the minimum valid value {}.".format( + rv, self.min + ), param, ctx, ) else: self.fail( - "%s is not in the valid range of %s to %s." - % (rv, self.min, self.max), + "{} is not in the valid range of {} to {}.".format( + rv, self.min, self.max + ), param, ctx, ) return rv def __repr__(self): - return "FloatRange({!r}, {!r})".format(self.min, self.max) + return "FloatRange({}, {})".format(self.min, self.max) class BoolParamType(ParamType): @@ -408,7 +414,7 @@ class BoolParamType(ParamType): return True elif value in ("false", "f", "0", "no", "n"): return False - self.fail("%s is not a valid boolean" % value, param, ctx) + self.fail("{} is not a valid boolean".format(value), param, ctx) def __repr__(self): return "BOOL" @@ -425,7 +431,7 @@ class UUIDParameterType(ParamType): value = value.encode("ascii") return uuid.UUID(value) except ValueError: - self.fail("%s is not a valid UUID value" % value, param, ctx) + self.fail("{} is not a valid UUID value".format(value), param, ctx) def __repr__(self): return "UUID" @@ -510,8 +516,9 @@ class File(ParamType): return f except (IOError, OSError) as e: # noqa: B014 self.fail( - "Could not open file: %s: %s" - % (filename_to_ui(value), get_streerror(e),), + "Could not open file: {}: {}".format( + filename_to_ui(value), get_streerror(e) + ), param, ctx, ) @@ -603,7 +610,7 @@ class Path(ParamType): if not self.exists: return self.coerce_path_result(rv) self.fail( - '{} "{}" does not exist.'.format( + "{} '{}' does not exist.".format( self.path_type, filename_to_ui(value) ), param, @@ -612,13 +619,13 @@ class Path(ParamType): if not self.file_okay and stat.S_ISREG(st.st_mode): self.fail( - '{} "{}" is a file.'.format(self.path_type, filename_to_ui(value)), + "{} '{}' is a file.".format(self.path_type, filename_to_ui(value)), param, ctx, ) if not self.dir_okay and stat.S_ISDIR(st.st_mode): self.fail( - '{} "{}" is a directory.'.format( + "{} '{}' is a directory.".format( self.path_type, filename_to_ui(value) ), param, @@ -626,15 +633,17 @@ class Path(ParamType): ) if self.writable and not os.access(value, os.W_OK): self.fail( - '%s "%s" is not writable.' - % (self.path_type, filename_to_ui(value)), + "{} '{}' is not writable.".format( + self.path_type, filename_to_ui(value) + ), param, ctx, ) if self.readable and not os.access(value, os.R_OK): self.fail( - '%s "%s" is not readable.' - % (self.path_type, filename_to_ui(value)), + "{} '{}' is not readable.".format( + self.path_type, filename_to_ui(value) + ), param, ctx, ) @@ -661,7 +670,7 @@ class Tuple(CompositeParamType): @property def name(self): - return "<" + " ".join(ty.name for ty in self.types) + ">" + return "<{}>".format(" ".join(ty.name for ty in self.types)) @property def arity(self): @@ -670,15 +679,15 @@ class Tuple(CompositeParamType): def convert(self, value, param, ctx): if len(value) != len(self.types): raise TypeError( - "It would appear that nargs is set to conflict " - "with the composite type arity." + "It would appear that nargs is set to conflict with the" + " composite type arity." ) return tuple(ty(x, param, ctx) for ty, x in zip(self.types, value)) def convert_type(ty, default=None): - """Converts a callable or python ty into the most appropriate param - ty. + """Converts a callable or python type into the most appropriate + param type. """ guessed_type = False if ty is None and default is not None: @@ -712,7 +721,7 @@ def convert_type(ty, default=None): try: if issubclass(ty, ParamType): raise AssertionError( - "Attempted to use an uninstantiated parameter type (%s)." % ty + "Attempted to use an uninstantiated parameter type ({}).".format(ty) ) except TypeError: pass diff --git a/src/click/utils.py b/src/click/utils.py index 58517b3..79265e7 100644 --- a/src/click/utils.py +++ b/src/click/utils.py @@ -65,7 +65,7 @@ def make_default_short_help(help, max_length=45): for word in words: if word[-1:] == ".": done = True - new_length = result and 1 + len(word) or len(word) + new_length = 1 + len(word) if result else len(word) if total_length + new_length > max_length: result.append("...") done = True @@ -113,7 +113,7 @@ class LazyFile(object): def __repr__(self): if self._f is not None: return repr(self._f) - return "<unopened file {!r} {}>".format(self.name, self.mode) + return "<unopened file '{}' {}>".format(self.name, self.mode) def open(self): """Opens the file if it's not yet open. This call might fail with @@ -285,7 +285,7 @@ def get_binary_stream(name): """ opener = binary_streams.get(name) if opener is None: - raise TypeError("Unknown standard stream %r" % name) + raise TypeError("Unknown standard stream '{}'".format(name)) return opener() @@ -302,7 +302,7 @@ def get_text_stream(name, encoding=None, errors="strict"): """ opener = text_streams.get(name) if opener is None: - raise TypeError("Unknown standard stream %r" % name) + raise TypeError("Unknown standard stream '{}'".format(name)) return opener(encoding, errors) @@ -413,13 +413,13 @@ def get_app_dir(app_name, roaming=True, force_posix=False): application support folder. """ if WIN: - key = roaming and "APPDATA" or "LOCALAPPDATA" + key = "APPDATA" if roaming else "LOCALAPPDATA" folder = os.environ.get(key) if folder is None: folder = os.path.expanduser("~") return os.path.join(folder, app_name) if force_posix: - return os.path.join(os.path.expanduser("~/." + _posixify(app_name))) + return os.path.join(os.path.expanduser("~/.{}".format(_posixify(app_name)))) if sys.platform == "darwin": return os.path.join( os.path.expanduser("~/Library/Application Support"), app_name |
