summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorDavid Lord <davidism@gmail.com>2020-04-19 23:54:14 -0700
committerDavid Lord <davidism@gmail.com>2020-04-19 23:58:30 -0700
commit03dabdda8e48f0f87f13d24b9a2e65c1b0807635 (patch)
tree7f195251ffdb1399d0b289d4c0146e5c5e6027a2 /src
parentd8bd5b1e6ececb9f8ee7cc05a94216b86ce80aed (diff)
downloadclick-03dabdda8e48f0f87f13d24b9a2e65c1b0807635.tar.gz
f-strings everywhere
Diffstat (limited to 'src')
-rw-r--r--src/click/_bashcomplete.py2
-rw-r--r--src/click/_compat.py4
-rw-r--r--src/click/_termui_impl.py21
-rw-r--r--src/click/_textwrap.py2
-rw-r--r--src/click/_unicodefun.py10
-rw-r--r--src/click/_winconsole.py4
-rw-r--r--src/click/core.py61
-rw-r--r--src/click/decorators.py5
-rw-r--r--src/click/exceptions.py17
-rw-r--r--src/click/formatting.py14
-rw-r--r--src/click/parser.py6
-rw-r--r--src/click/termui.py24
-rw-r--r--src/click/testing.py7
-rw-r--r--src/click/types.py65
-rw-r--r--src/click/utils.py2
15 files changed, 101 insertions, 143 deletions
diff --git a/src/click/_bashcomplete.py b/src/click/_bashcomplete.py
index 1c865f6..b9e4900 100644
--- a/src/click/_bashcomplete.py
+++ b/src/click/_bashcomplete.py
@@ -345,7 +345,7 @@ def do_complete_fish(cli, prog_name):
for item in get_choices(cli, prog_name, args, incomplete):
if item[1]:
- echo("{arg}\t{desc}".format(arg=item[0], desc=item[1]))
+ echo(f"{item[0]}\t{item[1]}")
else:
echo(item[0])
diff --git a/src/click/_compat.py b/src/click/_compat.py
index 96b0dd8..85568ca 100644
--- a/src/click/_compat.py
+++ b/src/click/_compat.py
@@ -64,7 +64,7 @@ class _NonClosingTextIOWrapper(io.TextIOWrapper):
errors,
force_readable=False,
force_writable=False,
- **extra
+ **extra,
):
self._stream = stream = _FixupStream(stream, force_readable, force_writable)
super().__init__(stream, encoding, errors, **extra)
@@ -415,7 +415,7 @@ def open_stream(filename, mode="r", encoding=None, errors="strict", atomic=False
while True:
tmp_filename = os.path.join(
os.path.dirname(filename),
- ".__atomic-write{:08x}".format(random.randrange(1 << 32)),
+ f".__atomic-write{random.randrange(1 << 32):08x}",
)
try:
fd = os.open(tmp_filename, flags, 0o666 if perm is None else perm)
diff --git a/src/click/_termui_impl.py b/src/click/_termui_impl.py
index 84e3fc5..f03aa85 100644
--- a/src/click/_termui_impl.py
+++ b/src/click/_termui_impl.py
@@ -173,7 +173,7 @@ class ProgressBar:
return pos
def format_pct(self):
- return "{: 4}%".format(int(self.pct * 100))[1:]
+ return f"{int(self.pct * 100): 4}%"[1:]
def format_bar(self):
if self.length_known:
@@ -352,10 +352,7 @@ def pager(generator, color=None):
fd, filename = tempfile.mkstemp()
os.close(fd)
try:
- if (
- hasattr(os, "system")
- and os.system("more {}".format(shlex.quote(filename))) == 0
- ):
+ if hasattr(os, "system") and os.system(f"more {shlex.quote(filename)}") == 0:
return _pipepager(generator, "more", color)
return _nullpager(stdout, generator, color)
finally:
@@ -374,7 +371,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 = "{}{}".format(os.environ.get("LESS", ""), " ".join(cmd_detail[1:]))
+ less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_detail[1:])}"
if not less_flags:
env["LESS"] = "-R"
color = True
@@ -424,7 +421,7 @@ def _tempfilepager(generator, cmd, color):
with open_stream(filename, "wb")[0] as f:
f.write(text.encode(encoding))
try:
- os.system("{} {}".format(shlex.quote(cmd), shlex.quote(filename)))
+ os.system(f"{shlex.quote(cmd)} {shlex.quote(filename)}")
finally:
os.unlink(filename)
@@ -469,7 +466,7 @@ class Editor:
environ = None
try:
c = subprocess.Popen(
- "{} {}".format(shlex.quote(editor), shlex.quote(filename)),
+ f"{shlex.quote(editor)} {shlex.quote(filename)}",
env=environ,
shell=True,
)
@@ -546,16 +543,16 @@ def open_url(url, wait=False, locate=False):
elif WIN:
if locate:
url = _unquote_file(url)
- args = "explorer /select,{}".format(shlex.quote(url))
+ args = f"explorer /select,{shlex.quote(url)}"
else:
- args = 'start {} "" {}'.format("/WAIT" if wait else "", shlex.quote(url))
+ args = f"start {'/WAIT' if wait else ''} \"\" {shlex.quote(url)}"
return os.system(args)
elif CYGWIN:
if locate:
url = _unquote_file(url)
- args = "cygstart {}".format(shlex.quote(os.path.dirname(url)))
+ args = f"cygstart {shlex.quote(os.path.dirname(url))}"
else:
- args = "cygstart {} {}".format("-w" if wait else "", shlex.quote(url))
+ args = f"cygstart {'-w' if wait else ''} {shlex.quote(url)}"
return os.system(args)
try:
diff --git a/src/click/_textwrap.py b/src/click/_textwrap.py
index 6959087..7a052b7 100644
--- a/src/click/_textwrap.py
+++ b/src/click/_textwrap.py
@@ -33,5 +33,5 @@ class TextWrapper(textwrap.TextWrapper):
indent = self.initial_indent
if idx > 0:
indent = self.subsequent_indent
- rv.append(indent + line)
+ rv.append(f"{indent}{line}")
return "\n".join(rv)
diff --git a/src/click/_unicodefun.py b/src/click/_unicodefun.py
index 57545e0..7f3f234 100644
--- a/src/click/_unicodefun.py
+++ b/src/click/_unicodefun.py
@@ -55,9 +55,9 @@ def _verify_python3_env():
)
else:
extra += (
- "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)))
+ "This system lists some UTF-8 supporting locales that"
+ " you can pick from. The following suitable locales"
+ f" were discovered: {', '.join(sorted(good_locales))}"
)
bad_locale = None
@@ -71,12 +71,12 @@ def _verify_python3_env():
"\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)
+ f" {bad_locale!r} but it is not supported"
)
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/python3/ for"
- " mitigation steps.{}".format(extra)
+ f" mitigation steps.{extra}"
)
diff --git a/src/click/_winconsole.py b/src/click/_winconsole.py
index c46081f..923fdba 100644
--- a/src/click/_winconsole.py
+++ b/src/click/_winconsole.py
@@ -213,9 +213,7 @@ class ConsoleStream:
return self.buffer.isatty()
def __repr__(self):
- return "<ConsoleStream name={!r} encoding={!r}>".format(
- self.name, self.encoding
- )
+ return f"<ConsoleStream name={self.name!r} encoding={self.encoding!r}>"
class WindowsChunkedWriter:
diff --git a/src/click/core.py b/src/click/core.py
index 78b9ce4..e4061aa 100644
--- a/src/click/core.py
+++ b/src/click/core.py
@@ -36,12 +36,12 @@ SUBCOMMAND_METAVAR = "COMMAND [ARGS]..."
SUBCOMMANDS_METAVAR = "COMMAND1 [ARGS]... [COMMAND2 [ARGS]...]..."
DEPRECATED_HELP_NOTICE = " (DEPRECATED)"
-DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command %(name)s is deprecated."
+DEPRECATED_INVOKE_NOTICE = "DeprecationWarning: The command {name} is deprecated."
def _maybe_show_deprecated_notice(cmd):
if cmd.deprecated:
- echo(style(DEPRECATED_INVOKE_NOTICE % {"name": cmd.name}, fg="red"), err=True)
+ echo(style(DEPRECATED_INVOKE_NOTICE.format(name=cmd.name), fg="red"), err=True)
def fast_exit(code):
@@ -56,7 +56,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 = "_{}_COMPLETE".format(prog_name.replace("-", "_").upper())
+ complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()
complete_instr = os.environ.get(complete_var)
if not complete_instr:
return
@@ -81,17 +81,11 @@ def _check_multicommand(base_command, cmd_name, cmd, register=False):
" that is in chain mode. This is not supported."
)
raise RuntimeError(
- "{}. 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,
- cmd_name,
- cmd.__class__.__name__,
- base_command.__class__.__name__,
- base_command.name,
- )
+ f"{hint}. Command {base_command.name!r} is set to chain and"
+ f" {cmd_name!r} was added as a subcommand but it in itself is a"
+ f" multi command. ({cmd_name!r} is a {type(cmd).__name__}"
+ f" within a chained {type(base_command).__name__} named"
+ f" {base_command.name!r})."
)
@@ -159,8 +153,8 @@ class ParameterSource:
"""
if value not in cls.VALUES:
raise ValueError(
- "Invalid ParameterSource value: '{}'. Valid "
- "values are: {}".format(value, ",".join(cls.VALUES))
+ f"Invalid ParameterSource value: {value!r}. Valid"
+ f" values are: {','.join(cls.VALUES)}"
)
@@ -381,8 +375,8 @@ class Context:
and parent.auto_envvar_prefix is not None
and self.info_name is not None
):
- auto_envvar_prefix = "{}_{}".format(
- parent.auto_envvar_prefix, self.info_name.upper()
+ auto_envvar_prefix = (
+ f"{parent.auto_envvar_prefix}_{self.info_name.upper()}"
)
else:
auto_envvar_prefix = auto_envvar_prefix.upper()
@@ -1088,9 +1082,9 @@ class Command(BaseCommand):
if args and not ctx.allow_extra_args and not ctx.resilient_parsing:
ctx.fail(
- "Got unexpected extra argument{} ({})".format(
- "s" if len(args) != 1 else "", " ".join(map(make_str, args))
- )
+ "Got unexpected extra"
+ f" argument{'s' if len(args) != 1 else ''}"
+ f" ({' '.join(map(make_str, args))})"
)
ctx.args = args
@@ -1598,8 +1592,8 @@ class Parameter:
if self.nargs <= 1:
raise TypeError(
"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)
+ f" been set to {self.nargs}. This is not supported;"
+ " nargs needs to be set to a fixed value > 1."
)
if self.multiple:
return tuple(self.type(x or (), self, ctx) for x in value or ())
@@ -1863,8 +1857,9 @@ class Option(Parameter):
if not opts and not secondary_opts:
raise TypeError(
- "No options defined but a name was passed ({}). Did you"
- " mean to declare an argument instead of an option?".format(name)
+ f"No options defined but a name was passed ({name})."
+ " Did you mean to declare an argument instead of an"
+ " option?"
)
return name, opts, secondary_opts
@@ -1924,13 +1919,12 @@ class Option(Parameter):
if self.allow_from_autoenv and ctx.auto_envvar_prefix is not None:
envvar = f"{ctx.auto_envvar_prefix}_{self.name.upper()}"
if envvar is not None:
- extra.append(
- "env var: {}".format(
- ", ".join(str(d) for d in envvar)
- if isinstance(envvar, (list, tuple))
- else envvar
- )
+ var_str = (
+ ", ".join(str(d) for d in envvar)
+ if isinstance(envvar, (list, tuple))
+ else envvar
)
+ extra.append(f"env var: {var_str}")
if self.default is not None and (self.show_default or ctx.show_default):
if isinstance(self.show_default, str):
default_string = f"({self.show_default})"
@@ -1945,7 +1939,8 @@ class Option(Parameter):
if self.required:
extra.append("required")
if extra:
- help = "{}[{}]".format(f"{help} " if help else "", "; ".join(extra))
+ extra_str = ";".join(extra)
+ help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"
return ("; " if any_prefix_is_slash else " / ").join(rv), help
@@ -2061,7 +2056,7 @@ class Argument(Parameter):
else:
raise TypeError(
"Arguments take exactly one parameter declaration, got"
- " {}".format(len(decls))
+ f" {len(decls)}."
)
return name, [arg], []
diff --git a/src/click/decorators.py b/src/click/decorators.py
index e0596c8..3013305 100644
--- a/src/click/decorators.py
+++ b/src/click/decorators.py
@@ -66,7 +66,8 @@ def make_pass_decorator(object_type, ensure=False):
if obj is None:
raise RuntimeError(
"Managed to invoke callback without a context"
- " object of type '{}' existing".format(object_type.__name__)
+ f" object of type {object_type.__name__!r}"
+ " existing."
)
return ctx.invoke(f, obj, *args, **kwargs)
@@ -96,7 +97,7 @@ def _make_command(f, name, attrs, cls):
name=name or f.__name__.lower().replace("_", "-"),
callback=f,
params=params,
- **attrs
+ **attrs,
)
diff --git a/src/click/exceptions.py b/src/click/exceptions.py
index 2776a02..25b02bb 100644
--- a/src/click/exceptions.py
+++ b/src/click/exceptions.py
@@ -53,8 +53,9 @@ 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 = (
+ f"Try '{self.ctx.command_path}"
+ f" {self.ctx.help_option_names[0]}' for help.\n"
)
if self.ctx is not None:
color = self.ctx.color
@@ -137,12 +138,8 @@ class MissingParameter(BadParameter):
else:
msg = msg_extra
- return "Missing {}{}{}{}".format(
- param_type,
- f" {param_hint}" if param_hint else "",
- ". " if msg else ".",
- msg or "",
- )
+ hint_str = f" {param_hint}" if param_hint else ""
+ return f"Missing {param_type}{hint_str}.{' ' if msg else ''}{msg or ''}"
def __str__(self):
if self.message is None:
@@ -170,10 +167,10 @@ class NoSuchOption(UsageError):
bits = [self.message]
if self.possibilities:
if len(self.possibilities) == 1:
- bits.append("Did you mean {}?".format(self.possibilities[0]))
+ bits.append(f"Did you mean {self.possibilities[0]}?")
else:
possibilities = sorted(self.possibilities)
- bits.append("(Possible options: {})".format(", ".join(possibilities)))
+ bits.append(f"(Possible options: {', '.join(possibilities)})")
return " ".join(bits)
diff --git a/src/click/formatting.py b/src/click/formatting.py
index 5a8b81c..a298c2e 100644
--- a/src/click/formatting.py
+++ b/src/click/formatting.py
@@ -134,7 +134,7 @@ class HelpFormatter:
:param args: whitespace separated list of arguments.
:param prefix: the prefix for the first line.
"""
- usage_prefix = "{:>{w}}{} ".format(prefix, prog, w=self.current_indent)
+ usage_prefix = f"{prefix:>{self.current_indent}}{prog} "
text_width = self.width - self.current_indent
if text_width >= (term_len(usage_prefix) + 20):
@@ -163,7 +163,7 @@ class HelpFormatter:
def write_heading(self, heading):
"""Writes a heading into the buffer."""
- self.write("{:>{w}}{}:\n".format("", heading, w=self.current_indent))
+ self.write(f"{'':>{self.current_indent}}{heading}:\n")
def write_paragraph(self):
"""Writes a paragraph into the buffer."""
@@ -204,7 +204,7 @@ class HelpFormatter:
first_col = min(widths[0], col_max) + col_spacing
for first, second in iter_rows(rows, len(widths)):
- self.write("{:>{w}}{}".format("", first, w=self.current_indent))
+ self.write(f"{'':>{self.current_indent}}{first}")
if not second:
self.write("\n")
continue
@@ -219,14 +219,10 @@ class HelpFormatter:
lines = wrapped_text.splitlines()
if lines:
- self.write("{}\n".format(lines[0]))
+ self.write(f"{lines[0]}\n")
for line in lines[1:]:
- self.write(
- "{:>{w}}{}\n".format(
- "", line, w=first_col + self.current_indent
- )
- )
+ self.write(f"{'':>{first_col + self.current_indent}}{line}\n")
if len(lines) > 1:
# separate long help from next option
diff --git a/src/click/parser.py b/src/click/parser.py
index ae486d0..158abb0 100644
--- a/src/click/parser.py
+++ b/src/click/parser.py
@@ -100,7 +100,7 @@ def normalize_opt(opt, ctx):
if ctx is None or ctx.token_normalize_func is None:
return opt
prefix, opt = split_opt(opt)
- return prefix + ctx.token_normalize_func(opt)
+ return f"{prefix}{ctx.token_normalize_func(opt)}"
def split_arg_string(string):
@@ -361,7 +361,7 @@ class OptionParser:
unknown_options = []
for ch in arg[1:]:
- opt = normalize_opt(prefix + ch, self.ctx)
+ opt = normalize_opt(f"{prefix}{ch}", self.ctx)
option = self._short_opt.get(opt)
i += 1
@@ -399,7 +399,7 @@ class OptionParser:
# 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("{}{}".format(prefix, "".join(unknown_options)))
+ state.largs.append(f"{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 b9c91c7..a1bdf2a 100644
--- a/src/click/termui.py
+++ b/src/click/termui.py
@@ -56,10 +56,10 @@ def _build_prompt(
):
prompt = text
if type is not None and show_choices and isinstance(type, Choice):
- prompt += " ({})".format(", ".join(map(str, type.choices)))
+ prompt += f" ({', '.join(map(str, type.choices))})"
if default is not None and show_default:
- prompt = "{} [{}]".format(prompt, _format_default(default))
- return prompt + suffix
+ prompt = f"{prompt} [{_format_default(default)}]"
+ return f"{prompt}{suffix}"
def _format_default(default):
@@ -502,24 +502,24 @@ def style(
bits = []
if fg:
try:
- bits.append("\033[{}m".format(_ansi_colors[fg]))
+ bits.append(f"\033[{_ansi_colors[fg]}m")
except KeyError:
- raise TypeError(f"Unknown color '{fg}'")
+ raise TypeError(f"Unknown color {fg!r}")
if bg:
try:
- bits.append("\033[{}m".format(_ansi_colors[bg] + 10))
+ bits.append(f"\033[{_ansi_colors[bg] + 10}m")
except KeyError:
- raise TypeError(f"Unknown color '{bg}'")
+ raise TypeError(f"Unknown color {bg!r}")
if bold is not None:
- bits.append("\033[{}m".format(1 if bold else 22))
+ bits.append(f"\033[{1 if bold else 22}m")
if dim is not None:
- bits.append("\033[{}m".format(2 if dim else 22))
+ bits.append(f"\033[{2 if dim else 22}m")
if underline is not None:
- bits.append("\033[{}m".format(4 if underline else 24))
+ bits.append(f"\033[{4 if underline else 24}m")
if blink is not None:
- bits.append("\033[{}m".format(5 if blink else 25))
+ bits.append(f"\033[{5 if blink else 25}m")
if reverse is not None:
- bits.append("\033[{}m".format(7 if reverse else 27))
+ bits.append(f"\033[{7 if reverse else 27}m")
bits.append(text)
if reset:
bits.append(_ansi_reset_all)
diff --git a/src/click/testing.py b/src/click/testing.py
index 717d2e4..fd6bf61 100644
--- a/src/click/testing.py
+++ b/src/click/testing.py
@@ -99,9 +99,8 @@ class Result:
)
def __repr__(self):
- return "<{} {}>".format(
- type(self).__name__, repr(self.exception) if self.exception else "okay"
- )
+ exc_str = repr(self.exception) if self.exception else "okay"
+ return f"<{type(self).__name__} {exc_str}>"
class CliRunner:
@@ -196,7 +195,7 @@ class CliRunner:
return val
def hidden_input(prompt=None):
- sys.stdout.write("{}\n".format(prompt or ""))
+ sys.stdout.write(f"{prompt or ''}\n")
sys.stdout.flush()
return input.readline().rstrip("\r\n")
diff --git a/src/click/types.py b/src/click/types.py
index 7aae2fe..93cf701 100644
--- a/src/click/types.py
+++ b/src/click/types.py
@@ -157,10 +157,11 @@ class Choice(ParamType):
self.case_sensitive = case_sensitive
def get_metavar(self, param):
- return "[{}]".format("|".join(self.choices))
+ return f"[{'|'.join(self.choices)}]"
def get_missing_message(self, param):
- return "Choose from:\n\t{}.".format(",\n\t".join(self.choices))
+ choice_str = ",\n\t".join(self.choices)
+ return f"Choose from:\n\t{choice_str}"
def convert(self, value, param, ctx):
# Match through normalization and case sensitivity
@@ -188,15 +189,13 @@ class Choice(ParamType):
return normed_choices[normed_value]
self.fail(
- "invalid choice: {}. (choose from {})".format(
- value, ", ".join(self.choices)
- ),
+ f"invalid choice: {value}. (choose from {', '.join(self.choices)})",
param,
ctx,
)
def __repr__(self):
- return "Choice('{}')".format(list(self.choices))
+ return f"Choice({list(self.choices)})"
class DateTime(ParamType):
@@ -226,7 +225,7 @@ class DateTime(ParamType):
self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]
def get_metavar(self, param):
- return "[{}]".format("|".join(self.formats))
+ return f"[{'|'.join(self.formats)}]"
def _try_to_convert_date(self, value, format):
try:
@@ -242,9 +241,7 @@ class DateTime(ParamType):
return dtime
self.fail(
- "invalid datetime format: {}. (choose from {})".format(
- value, ", ".join(self.formats)
- )
+ f"invalid datetime format: {value}. (choose from {', '.join(self.formats)})"
)
def __repr__(self):
@@ -295,25 +292,19 @@ class IntRange(IntParamType):
):
if self.min is None:
self.fail(
- "{} is bigger than the maximum valid value {}.".format(
- rv, self.max
- ),
+ f"{rv} is bigger than the maximum valid value {self.max}.",
param,
ctx,
)
elif self.max is None:
self.fail(
- "{} is smaller than the minimum valid value {}.".format(
- rv, self.min
- ),
+ f"{rv} is smaller than the minimum valid value {self.min}.",
param,
ctx,
)
else:
self.fail(
- "{} is not in the valid range of {} to {}.".format(
- rv, self.min, self.max
- ),
+ f"{rv} is not in the valid range of {self.min} to {self.max}.",
param,
ctx,
)
@@ -367,25 +358,19 @@ class FloatRange(FloatParamType):
):
if self.min is None:
self.fail(
- "{} is bigger than the maximum valid value {}.".format(
- rv, self.max
- ),
+ f"{rv} is bigger than the maximum valid value {self.max}.",
param,
ctx,
)
elif self.max is None:
self.fail(
- "{} is smaller than the minimum valid value {}.".format(
- rv, self.min
- ),
+ f"{rv} is smaller than the minimum valid value {self.min}.",
param,
ctx,
)
else:
self.fail(
- "{} is not in the valid range of {} to {}.".format(
- rv, self.min, self.max
- ),
+ f"{rv} is not in the valid range of {self.min} to {self.max}.",
param,
ctx,
)
@@ -506,9 +491,7 @@ class File(ParamType):
return f
except OSError as e: # noqa: B014
self.fail(
- "Could not open file: {}: {}".format(
- filename_to_ui(value), get_strerror(e)
- ),
+ f"Could not open file: {filename_to_ui(value)}: {get_strerror(e)}",
param,
ctx,
)
@@ -600,40 +583,32 @@ class Path(ParamType):
if not self.exists:
return self.coerce_path_result(rv)
self.fail(
- "{} '{}' does not exist.".format(
- self.path_type, filename_to_ui(value)
- ),
+ f"{self.path_type} {filename_to_ui(value)!r} does not exist.",
param,
ctx,
)
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)),
+ f"{self.path_type} {filename_to_ui(value)!r} is a file.",
param,
ctx,
)
if not self.dir_okay and stat.S_ISDIR(st.st_mode):
self.fail(
- "{} '{}' is a directory.".format(
- self.path_type, filename_to_ui(value)
- ),
+ f"{self.path_type} {filename_to_ui(value)!r} is a directory.",
param,
ctx,
)
if self.writable and not os.access(value, os.W_OK):
self.fail(
- "{} '{}' is not writable.".format(
- self.path_type, filename_to_ui(value)
- ),
+ f"{self.path_type} {filename_to_ui(value)!r} is not writable.",
param,
ctx,
)
if self.readable and not os.access(value, os.R_OK):
self.fail(
- "{} '{}' is not readable.".format(
- self.path_type, filename_to_ui(value)
- ),
+ f"{self.path_type} {filename_to_ui(value)!r} is not readable.",
param,
ctx,
)
@@ -660,7 +635,7 @@ class Tuple(CompositeParamType):
@property
def name(self):
- return "<{}>".format(" ".join(ty.name for ty in self.types))
+ return f"<{' '.join(ty.name for ty in self.types)}>"
@property
def arity(self):
diff --git a/src/click/utils.py b/src/click/utils.py
index b18c83d..ffd26b3 100644
--- a/src/click/utils.py
+++ b/src/click/utils.py
@@ -408,7 +408,7 @@ def get_app_dir(app_name, roaming=True, force_posix=False):
folder = os.path.expanduser("~")
return os.path.join(folder, app_name)
if force_posix:
- return os.path.join(os.path.expanduser("~/.{}".format(_posixify(app_name))))
+ return os.path.join(os.path.expanduser(f"~/.{_posixify(app_name)}"))
if sys.platform == "darwin":
return os.path.join(
os.path.expanduser("~/Library/Application Support"), app_name