Skip to content
Myr

Merge pull request #1829 from MLH-Fellowship/add-i18n

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

Wrapped public messages with gettext for i18n support

authored by David Lord · committed by GitHub · parents c0f9c06, 8d49e14 · Browse files · 16 files+238 added−118 removed
This commit

State

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

Diff stats

16 files+238 added−118 removed

  • tests:+7 added−6 removed
  • other:+231 added−112 removed

16 files+238 added−118 removed

modified:src/click/_termui_impl.py+7 added-2 removed
6 unmodified lines
7import math8import os9import sys10import time11from gettext import gettext as _1213from ._compat import _default_text_stdout14from ._compat import CYGWIN15from ._compat import get_best_encoding
473 unmodified lines
489 try:490 c = subprocess.Popen(f'{editor} "{filename}"', env=environ, shell=True)491 exit_code = c.wait()492 if exit_code != 0:492 raise ClickException(f"{editor}: Editing failed!")493 raise ClickException(494 _("{editor}: Editing failed").format(editor=editor)495 )496 except OSError as e:494 raise ClickException(f"{editor}: Editing failed: {e}")497 raise ClickException(498 _("{editor}: Editing failed: {e}").format(editor=editor, e=e)499 )500501 def edit(self, text):502 import tempfile503
197 unmodified lines
modified:src/click/_unicodefun.py+39 added-28 removed
1import codecs2import os3from gettext import gettext as _456def _verify_python_env():7 """Ensures that the environment is good for Unicode."""
5 unmodified lines
13 fs_enc = "ascii"14 if fs_enc != "ascii":15 return1616 extra = ""17 extra = [18 _(19 "Click will abort further execution because Python was"20 " configured to use ASCII as encoding for the environment."21 " Consult https://click.palletsprojects.com/unicode-support/"22 " for mitigation steps."23 )24 ]2526 if os.name == "posix":27 import subprocess2829 try:
15 unmodified lines
45 good_locales.add(locale)46 if locale.lower() in ("c.utf8", "c.utf-8"):47 has_c_utf8 = True4840 extra += "\n\n"49 if not good_locales:50 extra.append(42 extra += (43 "Additional information: on this system no suitable"44 " UTF-8 locales were discovered. This most likely"45 " requires resolving by reconfiguring the locale"46 " system."51 _(52 "Additional information: on this system no suitable"53 " UTF-8 locales were discovered. This most likely"54 " requires resolving by reconfiguring the locale"55 " system."56 )57 )58 elif has_c_utf8:49 extra += (50 "This system supports the C.UTF-8 locale which is"51 " recommended. You might be able to resolve your issue"52 " by exporting the following environment variables:\n\n"53 " export LC_ALL=C.UTF-8\n"54 " export LANG=C.UTF-8"59 extra.append(60 _(61 "This system supports the C.UTF-8 locale which is"62 " recommended. You might be able to resolve your"63 " issue by exporting the following environment"64 " variables:"65 )66 )67 extra.append(" export LC_ALL=C.UTF-8\n export LANG=C.UTF-8")68 else:57 extra += (58 "This system lists some UTF-8 supporting locales that"59 " you can pick from. The following suitable locales"60 f" were discovered: {', '.join(sorted(good_locales))}"69 extra.append(70 _(71 "This system lists some UTF-8 supporting locales"72 " that you can pick from. The following suitable"73 " locales were discovered: {locales}"74 ).format(locales=", ".join(sorted(good_locales)))75 )7677 bad_locale = None78 for locale in os.environ.get("LC_ALL"), os.environ.get("LANG"):
1 unmodified line
80 bad_locale = locale81 if locale is not None:82 break83 if bad_locale is not None:70 extra += (71 "\n\nClick discovered that you exported a UTF-8 locale"72 " but the locale system could not pick up from it"73 " because it does not exist. The exported locale is"74 f" {bad_locale!r} but it is not supported"84 extra.append(85 _(86 "Click discovered that you exported a UTF-8 locale"87 " but the locale system could not pick up from it"88 " because it does not exist. The exported locale is"89 " {locale!r} but it is not supported."90 ).format(locale=bad_locale)91 )9277 raise RuntimeError(78 "Click will abort further execution because Python was"79 " configured to use ASCII as encoding for the environment."80 " Consult https://click.palletsprojects.com/unicode-support/"81 f" for mitigation steps.{extra}"82 )93 raise RuntimeError("\n\n".join(extra))
modified:src/click/core.py+27 added-19 removed
4 unmodified lines
5import typing as t6from contextlib import contextmanager7from contextlib import ExitStack8from functools import update_wrapper9from gettext import gettext as _10from gettext import ngettext11from itertools import repeat1213from ._unicodefun import _verify_python_env14from .exceptions import Abort
981 unmodified lines
996 return e.exit_code997 except Abort:998 if not standalone_mode:999 raise998 echo("Aborted!", file=sys.stderr)1000 echo(_("Aborted!"), file=sys.stderr)1001 sys.exit(1)10021003 def _main_shell_completion(self, ctx_args, prog_name, complete_var=None):1004 """Check if the shell is asking for tab completion, process
166 unmodified lines
1171 is_flag=True,1172 is_eager=True,1173 expose_value=False,1174 callback=show_help,1173 help="Show this message and exit.",1175 help=_("Show this message and exit."),1176 )11771178 def make_parser(self, ctx):1179 """Creates the underlying option parser for this command."""
20 unmodified lines
1200 if not text and self.help:1201 text = make_default_short_help(self.help, limit)12021203 if self.deprecated:1202 text = f"(Deprecated) {text}"1204 text = _("(Deprecated) {text}").format(text=text)12051206 return text.strip()12071208 def format_help(self, ctx, formatter):
17 unmodified lines
1226 """Writes the help text to the formatter if it exists."""1227 text = self.help or ""12281229 if self.deprecated:1228 text = f"(Deprecated) {text}"1230 text = _("(Deprecated) {text}").format(text=text)12311232 if text:1233 formatter.write_paragraph()1234
8 unmodified lines
1243 if rv is not None:1244 opts.append(rv)12451246 if opts:1245 with formatter.section("Options"):1247 with formatter.section(_("Options")):1248 formatter.write_dl(opts)12491250 def format_epilog(self, ctx, formatter):1251 """Writes the epilog into the formatter if it exists."""
14 unmodified lines
1266 value, args = param.handle_parse_result(ctx, opts, args)12671268 if args and not ctx.allow_extra_args and not ctx.resilient_parsing:1269 ctx.fail(1268 "Got unexpected extra"1269 f" argument{'s' if len(args) != 1 else ''}"1270 f" ({' '.join(map(make_str, args))})"1270 ngettext(1271 "Got unexpected extra argument ({args})",1272 "Got unexpected extra arguments ({args})",1273 len(args),1274 ).format(args=" ".join(map(str, args)))1275 )12761277 ctx.args = args1278 return args
4 unmodified lines
1283 """1284 if self.deprecated:1285 echo(1286 style(1283 f"DeprecationWarning: The command {self.name!r} is deprecated.",1287 _("DeprecationWarning: The command {name!r} is deprecated.").format(1288 name=self.name1289 ),1290 fg="red",1291 ),1292 err=True,1293 )
185 unmodified lines
1479 help = cmd.get_short_help_str(limit)1480 rows.append((subcommand, help))14811482 if rows:1477 with formatter.section("Commands"):1483 with formatter.section(_("Commands")):1484 formatter.write_dl(rows)14851486 def parse_args(self, ctx, args):1487 if not args and self.no_args_is_help and not ctx.resilient_parsing:
23 unmodified lines
1511 # for chained groups.1512 with ctx:1513 super().invoke(ctx)1514 return _process_result([] if self.chain else None)1509 ctx.fail("Missing command.")1515 ctx.fail(_("Missing command."))15161517 # Fetch args back out1518 args = ctx.protected_args + ctx.args1519 ctx.args = []
65 unmodified lines
1585 # place.1586 if cmd is None and not ctx.resilient_parsing:1587 if split_opt(cmd_name)[0]:1588 self.parse_args(ctx, ctx.args)1583 ctx.fail(f"No such command '{original_cmd_name}'.")1589 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1590 return cmd.name if cmd else None, cmd, args[1:]15911592 def get_command(self, ctx, cmd_name):1593 """Given a context and a command name, this returns a
469 unmodified lines
2063 if self.multiple2064 else len(value) != self.nargs2065 )2066 ):2061 were = "was" if len(value) == 1 else "were"2067 ctx.fail(2063 f"Argument {self.name!r} takes {self.nargs} values but"2064 f" {len(value)} {were} given."2068 ngettext(2069 "Argument {name!r} takes {nargs} values but 1 was given.",2070 "Argument {name!r} takes {nargs} values but {len} were given.",2071 len(value),2072 ).format(name=self.name, nargs=self.nargs, len=len(value))2073 )20742075 if self.callback is not None:2076 value = self.callback(ctx, self, value)
351 unmodified lines
2428 ", ".join(str(d) for d in envvar)2429 if isinstance(envvar, (list, tuple))2430 else envvar2431 )2424 extra.append(f"env var: {var_str}")2432 extra.append(_("env var: {var}").format(var=var_str))24332434 default_value = self.get_default(ctx, call=False)2435 show_default_is_str = isinstance(self.show_default, str)2436
4 unmodified lines
2441 default_string = f"({self.show_default})"2442 elif isinstance(default_value, (list, tuple)):2443 default_string = ", ".join(str(d) for d in default_value)2444 elif callable(default_value):2437 default_string = "(dynamic)"2445 default_string = _("(dynamic)")2446 elif self.is_bool_flag and self.secondary_opts:2447 # For boolean flags that have distinct True/False opts,2448 # use the opt without prefix instead of the value.2449 default_string = split_opt(
1 unmodified line
2451 )[1]2452 else:2453 default_string = default_value24542447 extra.append(f"default: {default_string}")2455 extra.append(_("default: {default}").format(default=default_string))24562457 if isinstance(self.type, _NumberRangeBase):2458 range_str = self.type._describe_range()24592460 if range_str:2461 extra.append(range_str)24622463 if self.required:2456 extra.append("required")2464 extra.append(_("required"))2465 if extra:2466 extra_str = ";".join(extra)2467 help = f"{help} [{extra_str}]" if help else f"[{extra_str}]"2468
162 unmodified lines
modified:src/click/decorators.py+9 added-4 removed
1import inspect2import typing as t3from functools import update_wrapper4from gettext import gettext as _56from .core import Argument7from .core import Command8from .core import Group
271 unmodified lines
280 version=None,281 *param_decls,282 package_name=None,283 prog_name=None,283 message="%(prog)s, version %(version)s",284 message=None,285 **kwargs,286):287 """Add a ``--version`` option which immediately prints the version288 number and exits the program.
15 unmodified lines
304 not provided, Click will try to detect it.305 :param prog_name: The name of the CLI to show in the message. If not306 provided, it will be detected from the command.307 :param message: The message to show. The values ``%(prog)s``,307 ``%(package)s``, and ``%(version)s`` are available.308 ``%(package)s``, and ``%(version)s`` are available. Defaults to309 ``"%(prog)s, version %(version)s"``.310 :param kwargs: Extra arguments are passed to :func:`option`.311 :raise RuntimeError: ``version`` could not be detected.312313 .. versionchanged:: 8.0
2 unmodified lines
316317 .. versionchanged:: 8.0318 Use :mod:`importlib.metadata` instead of ``pkg_resources``.319 """320 if message is None:321 message = _("%(prog)s, version %(version)s")322323 if version is None and package_name is None:324 frame = inspect.currentframe()325 f_globals = frame.f_back.f_globals if frame is not None else None326 # break reference cycle
58 unmodified lines
385386 kwargs.setdefault("is_flag", True)387 kwargs.setdefault("expose_value", False)388 kwargs.setdefault("is_eager", True)384 kwargs.setdefault("help", "Show the version and exit.")389 kwargs.setdefault("help", _("Show the version and exit."))390 kwargs["callback"] = callback391 return option(*param_decls, **kwargs)392393
22 unmodified lines
416417 kwargs.setdefault("is_flag", True)418 kwargs.setdefault("expose_value", False)419 kwargs.setdefault("is_eager", True)415 kwargs.setdefault("help", "Show this message and exit.")420 kwargs.setdefault("help", _("Show this message and exit."))421 kwargs["callback"] = callback422 return option(*param_decls, **kwargs)
modified:src/click/exceptions.py+48 added-23 removed
1from gettext import gettext as _2from gettext import ngettext34from ._compat import filename_to_ui5from ._compat import get_text_stderr6from .utils import echo7
22 unmodified lines
3031 def show(self, file=None):32 if file is None:33 file = get_text_stderr()31 echo(f"Error: {self.format_message()}", file=file)34 echo(_("Error: {message}").format(message=self.format_message()), file=file)353637class UsageError(ClickException):38 """An internal exception that signals a usage error. This typically
16 unmodified lines
55 file = get_text_stderr()56 color = None57 hint = ""58 if self.cmd is not None and self.cmd.get_help_option(self.ctx) is not None:56 hint = (57 f"Try '{self.ctx.command_path}"58 f" {self.ctx.help_option_names[0]}' for help.\n"59 hint = _("Try '{command} {option}' for help.").format(60 command=self.ctx.command_path, option=self.ctx.help_option_names[0]61 )62 hint = f"{hint}\n"63 if self.ctx is not None:64 color = self.ctx.color65 echo(f"{self.ctx.get_usage()}\n{hint}", file=file, color=color)63 echo(f"Error: {self.format_message()}", file=file, color=color)66 echo(67 _("Error: {message}").format(message=self.format_message()),68 file=file,69 color=color,70 )717273class BadParameter(UsageError):74 """An exception that formats out a standardized error message for a
23 unmodified lines
98 param_hint = self.param_hint99 elif self.param is not None:100 param_hint = self.param.get_error_hint(self.ctx)101 else:95 return f"Invalid value: {self.message}"96 param_hint = _join_param_hints(param_hint)102 return _("Invalid value: {message}").format(message=self.message)10398 return f"Invalid value for {param_hint}: {self.message}"104 return _("Invalid value for {param_hint}: {message}").format(105 param_hint=_join_param_hints(param_hint), message=self.message106 )107108109class MissingParameter(BadParameter):110 """Raised if click required an option or argument but it was not
19 unmodified lines
130 elif self.param is not None:131 param_hint = self.param.get_error_hint(self.ctx)132 else:133 param_hint = None134135 param_hint = _join_param_hints(param_hint)136 param_hint = f" {param_hint}" if param_hint else ""137138 param_type = self.param_type139 if param_type is None and self.param is not None:140 param_type = self.param.param_type_name
2 unmodified lines
143 if self.param is not None:144 msg_extra = self.param.type.get_missing_message(self.param)145 if msg_extra:146 if msg:137 msg += f". {msg_extra}"147 msg += f". {msg_extra}"148 else:149 msg = msg_extra150141 hint_str = f" {param_hint}" if param_hint else ""142 return f"Missing {param_type}{hint_str}.{' ' if msg else ''}{msg or ''}"151 msg = f" {msg}" if msg else ""152153 # Translate param_type for known types.154 if param_type == "argument":155 missing = _("Missing argument")156 elif param_type == "option":157 missing = _("Missing option")158 elif param_type == "parameter":159 missing = _("Missing parameter")160 else:161 missing = _("Missing {param_type}").format(param_type=param_type)162163 return f"{missing}{param_hint}.{msg}"164165 def __str__(self):166 if self.message is None:167 param_name = self.param.name if self.param else None147 return f"missing parameter: {param_name}"168 return _("Missing parameter: {param_name}").format(param_name=param_name)169 else:170 return self.message171172
5 unmodified lines
178 """179180 def __init__(self, option_name, message=None, possibilities=None, ctx=None):181 if message is None:161 message = f"no such option: {option_name}"182 message = _("No such option: {name}").format(name=option_name)183184 super().__init__(message, ctx)185 self.option_name = option_name186 self.possibilities = possibilities187188 def format_message(self):168 bits = [self.message]169 if self.possibilities:170 if len(self.possibilities) == 1:171 bits.append(f"Did you mean {self.possibilities[0]}?")172 else:173 possibilities = sorted(self.possibilities)174 bits.append(f"(Possible options: {', '.join(possibilities)})")175 return " ".join(bits)189 if not self.possibilities:190 return self.message191192 possibility_str = ", ".join(sorted(self.possibilities))193 suggest = ngettext(194 "Did you mean {possibility}?",195 "(Possible options: {possibilities})",196 len(self.possibilities),197 ).format(possibility=possibility_str, possibilities=possibility_str)198 return f"{self.message} {suggest}"199200201class BadOptionUsage(UsageError):202 """Raised if an option is generally supplied but the use of the option203 was incorrect. This is for instance raised if the number of arguments204 for an option is not correct.
22 unmodified lines
227228 def __init__(self, filename, hint=None):229 ui_filename = filename_to_ui(filename)230 if hint is None:208 hint = "unknown error"231 hint = _("unknown error")232233 super().__init__(hint)234 self.ui_filename = ui_filename235 self.filename = filename236237 def format_message(self):215 return f"Could not open file {self.ui_filename}: {self.message}"238 return _("Could not open file {filename!r}: {message}").format(239 filename=self.ui_filename, message=self.message240 )241242243class Abort(RuntimeError):244 """An internal signalling exception that signals Click to abort."""
13 unmodified lines
modified:src/click/formatting.py+7 added-2 removed
1import typing as t2from contextlib import contextmanager3from gettext import gettext as _45from ._compat import term_len6from .parser import split_opt7
121 unmodified lines
129 def dedent(self):130 """Decreases the indentation."""131 self.current_indent -= self.indent_increment132132 def write_usage(self, prog, args="", prefix="Usage: "):133 def write_usage(self, prog, args="", prefix=None):134 """Writes a usage line into the buffer.135136 :param prog: the program name.137 :param args: whitespace separated list of arguments.137 :param prefix: the prefix for the first line.138 :param prefix: The prefix for the first line. Defaults to139 ``"Usage: "``.140 """141 if prefix is None:142 prefix = f"{_('Usage:')} "143144 usage_prefix = f"{prefix:>{self.current_indent}}{prog} "145 text_width = self.width - self.current_indent146147 if text_width >= (term_len(usage_prefix) + 20):
135 unmodified lines
modified:src/click/parser.py+14 added-4 removed
20 unmodified lines
21# maintained by the Python Software Foundation.22# Copyright 2001-2006 Gregory P. Ward23# Copyright 2002-2006 Python Software Foundation24from collections import deque25from gettext import gettext as _26from gettext import ngettext2728from .exceptions import BadArgumentUsage29from .exceptions import BadOptionUsage30from .exceptions import NoSuchOption
164 unmodified lines
195 if holes == len(value):196 value = None197 elif holes != 0:198 raise BadArgumentUsage(197 f"argument {self.dest} takes {self.nargs} values"199 _("Argument {name!r} takes {nargs} values.").format(200 name=self.dest, nargs=self.nargs201 )202 )203204 if self.nargs == -1 and self.obj.envvar is not None:205 value = None
156 unmodified lines
362363 value = self._get_value_from_state(opt, option, state)364365 elif explicit_value is not None:362 raise BadOptionUsage(opt, f"{opt} option does not take a value")366 raise BadOptionUsage(367 opt, _("Option {name!r} does not take a value.").format(name=opt)368 )369370 else:371 value = None372
46 unmodified lines
419 if option.obj._flag_needs_value:420 # Option allows omitting the value.421 value = _flag_needs_value422 else:417 n_str = "an argument" if nargs == 1 else f"{nargs} arguments"423 raise BadOptionUsage(419 option_name, f"{option_name} option requires {n_str}."424 option_name,425 ngettext(426 "Option {name!r} requires an argument.",427 "Option {name!r} requires {nargs} arguments.",428 nargs,429 ).format(name=option_name, nargs=nargs),430 )431 elif nargs == 1:432 next_rarg = state.rargs[0]433
45 unmodified lines
modified:src/click/shell_completion.py+6 added-3 removed
1import os2import re3import typing as t4from gettext import gettext as _56from .core import Argument7from .core import MultiCommand8from .core import Option
280 unmodified lines
289 major, minor = match.groups()290291 if major < "4" or major == "4" and minor < "4":292 raise RuntimeError(293 _(292 "Shell completion is not supported for Bash"293 " versions older than 4.4."294 "Shell completion is not supported for Bash"295 " versions older than 4.4."296 )297 )298 else:299 raise RuntimeError(297 "Couldn't detect Bash version, shell completion is not supported."300 _("Couldn't detect Bash version, shell completion is not supported.")301 )302303 def source(self):304 self._check_version()
241 unmodified lines
modified:src/click/termui.py+13 added-7 removed
2 unmodified lines
3import itertools4import os5import sys6import typing as t7from gettext import gettext as _89from ._compat import is_bytes10from ._compat import isatty11from ._compat import strip_ansi
133 unmodified lines
145 )146147 if confirmation_prompt:148 if confirmation_prompt is True:148 confirmation_prompt = "Repeat for confirmation"149 confirmation_prompt = _("Repeat for confirmation")150151 confirmation_prompt = _build_prompt(confirmation_prompt, prompt_suffix)152153 while 1:
7 unmodified lines
161 try:162 result = value_proc(value)163 except UsageError as e:164 if hide_input:164 echo("Error: the value you entered was invalid", err=err)165 echo(_("Error: The value you entered was invalid."), err=err)166 else:166 echo(f"Error: {e.message}", err=err) # noqa: B306167 echo(_("Error: {e.message}").format(e=e), err=err) # noqa: B306168 continue169 if not confirmation_prompt:170 return result171 while 1:
1 unmodified line
173 if value2:174 break175 if value == value2:176 return result176 echo("Error: the two entered values do not match", err=err)177 echo(_("Error: The two entered values do not match."), err=err)178179180def confirm(181 text, default=False, abort=False, prompt_suffix=": ", show_default=True, err=False
40 unmodified lines
222 rv = False223 elif default is not None and value == "":224 rv = default225 else:225 echo("Error: invalid input", err=err)226 echo(_("Error: invalid input"), err=err)227 continue228 break229 if abort and not rv:230 raise Abort()
500 unmodified lines
731732 return f()733734734def pause(info="Press any key to continue ...", err=False):735def pause(info=None, err=False):736 """This command stops execution and waits for the user to press any737 key to continue. This is similar to the Windows batch "pause"738 command. If the program is not run through a terminal, this command739 will instead do nothing.
2 unmodified lines
742743 .. versionadded:: 4.0744 Added the `err` parameter.745745 :param info: the info string to print before pausing.746 :param info: The message to print before pausing. Defaults to747 ``"Press any key to continue..."``.748 :param err: if set to message goes to ``stderr`` instead of749 ``stdout``, the same as with echo.750 """751 if not isatty(sys.stdin) or not isatty(sys.stdout):752 return753754 if info is None:755 info = _("Press any key to continue...")756757 try:758 if info:759 echo(info, nl=False, err=err)760 try:
6 unmodified lines
modified:src/click/types.py+59 added-20 removed
1import os2import stat3import typing as t4from datetime import datetime5from gettext import gettext as _6from gettext import ngettext78from ._compat import _get_argv_encoding9from ._compat import filename_to_ui10from ._compat import get_filesystem_encoding
218 unmodified lines
229 # Use square braces to indicate an option or optional argument.230 return f"[{choices_str}]"231232 def get_missing_message(self, param):231 choice_str = ",\n\t".join(self.choices)232 return f"Choose from:\n\t{choice_str}"233 return _("Choose from:\n\t{choices}").format(choices=",\n\t".join(self.choices))234235 def convert(self, value, param, ctx):236 # Match through normalization and case sensitivity237 # first do token_normalize_func, then lowercase
18 unmodified lines
256257 if normed_value in normed_choices:258 return normed_choices[normed_value]259259 one_of = "one of " if len(self.choices) > 1 else ""260 choices_str = ", ".join(repr(c) for c in self.choices)261 self.fail(f"{value!r} is not {one_of}{choices_str}.", param, ctx)260 choices_str = ", ".join(map(repr, self.choices))261 self.fail(262 ngettext(263 "{value!r} is not {choice}.",264 "{value!r} is not one of {choices}.",265 len(self.choices),266 ).format(value=value, choice=choices_str, choices=choices_str),267 param,268 ctx,269 )270271 def __repr__(self):272 return f"Choice({list(self.choices)})"273
68 unmodified lines
342343 if converted is not None:344 return converted345338 plural = "s" if len(self.formats) > 1 else ""339 formats_str = ", ".join(repr(f) for f in self.formats)346 formats_str = ", ".join(map(repr, self.formats))347 self.fail(341 f"{value!r} does not match the format{plural} {formats_str}.", param, ctx348 ngettext(349 "{value!r} does not match the format {format}.",350 "{value!r} does not match the formats {formats}.",351 len(self.formats),352 ).format(value=value, format=formats_str, formats=formats_str),353 param,354 ctx,355 )356357 def __repr__(self):358 return "DateTime"
5 unmodified lines
364 def convert(self, value, param, ctx):365 try:366 return self._number_class(value)367 except ValueError:355 self.fail(f"{value!r} is not a valid {self.name}.", param, ctx)368 self.fail(369 _("{value!r} is not a valid {number_type}.").format(370 value=value, number_type=self.name371 ),372 param,373 ctx,374 )375376377class _NumberRangeBase(_NumberParamTypeBase):378 def __init__(self, min=None, max=None, min_open=False, max_open=False, clamp=False):
32 unmodified lines
411 if gt_max:412 return self._clamp(self.max, -1, self.max_open)413414 if lt_min or gt_max:396 self.fail(f"{rv} is not in the range {self._describe_range()}.", param, ctx)415 self.fail(416 _("{value} is not in the range {range}.").format(417 value=rv, range=self._describe_range()418 ),419 param,420 ctx,421 )422423 return rv424425 def _clamp(self, bound, dir, open):
115 unmodified lines
541542 if norm in {"0", "false", "f", "no", "n", "off"}:543 return False544520 self.fail(f"{value!r} is not a valid boolean.", param, ctx)545 self.fail(546 _("{value!r} is not a valid boolean.").format(value=value), param, ctx547 )548549 def __repr__(self):550 return "BOOL"551
11 unmodified lines
563564 try:565 return uuid.UUID(value)566 except ValueError:540 self.fail(f"{value!r} is not a valid UUID.", param, ctx)567 self.fail(568 _("{value!r} is not a valid UUID.").format(value=value), param, ctx569 )570571 def __repr__(self):572 return "UUID"573
152 unmodified lines
726 self.allow_dash = allow_dash727 self.type = path_type728729 if self.file_okay and not self.dir_okay:701 self.name = "file"730 self.name = _("file")731 elif self.dir_okay and not self.file_okay:703 self.name = "directory"732 self.name = _("directory")733 else:705 self.name = "path"734 self.name = _("path")735736 def to_info_dict(self):737 info_dict = super().to_info_dict()738 info_dict.update(
35 unmodified lines
774 except OSError:775 if not self.exists:776 return self.coerce_path_result(rv)777 self.fail(749 f"{self.name.title()} {filename_to_ui(value)!r} does not exist.",778 _("{name} {filename!r} does not exist.").format(779 name=self.name.title(), filename=filename_to_ui(value)780 ),781 param,782 ctx,783 )784785 if not self.file_okay and stat.S_ISREG(st.st_mode):786 self.fail(756 f"{self.name.title()} {filename_to_ui(value)!r} is a file.",787 _("{name} {filename!r} is a file.").format(788 name=self.name.title(), filename=filename_to_ui(value)789 ),790 param,791 ctx,792 )793 if not self.dir_okay and stat.S_ISDIR(st.st_mode):794 self.fail(762 f"{self.name.title()} {filename_to_ui(value)!r} is a directory.",795 _("{name} {filename!r} is a directory.").format(796 name=self.name.title(), filename=filename_to_ui(value)797 ),798 param,799 ctx,800 )801 if self.writable and not os.access(value, os.W_OK):802 self.fail(768 f"{self.name.title()} {filename_to_ui(value)!r} is not writable.",803 _("{name} {filename!r} is not writable.").format(804 name=self.name.title(), filename=filename_to_ui(value)805 ),806 param,807 ctx,808 )809 if self.readable and not os.access(value, os.R_OK):810 self.fail(774 f"{self.name.title()} {filename_to_ui(value)!r} is not readable.",811 _("{name} {filename!r} is not readable.").format(812 name=self.name.title(), filename=filename_to_ui(value)813 ),814 param,815 ctx,816 )817
152 unmodified lines
modified:tests/test_arguments.py+2 added-2 removed
228 unmodified lines
229230 with pytest.raises(click.MissingParameter) as excinfo:231 click.Argument(["a"], required=True).process_value(ctx, None)232233 assert str(excinfo.value) == "missing parameter: a"233 assert str(excinfo.value) == "Missing parameter: a"234235236def test_implicit_non_required(runner):237 @click.command()
62 unmodified lines
300 assert result.output.strip() == "7"301302 result = runner.invoke(cmd, ["3"])303 assert result.exception is not None304 assert "argument a takes 2 values" in result.output304 assert "Argument 'a' takes 2 values." in result.output305306307def test_multiple_param_decls_not_allowed(runner):308 with pytest.raises(TypeError):
66 unmodified lines
modified:tests/test_basic.py+1 added-1 removed
118 unmodified lines
119 assert "FOO:[42]" in result.output120121 result = runner.invoke(cli, ["--foo"])122 assert result.exception123 assert "--foo option requires an argument" in result.output123 assert "Option '--foo' requires an argument." in result.output124125 result = runner.invoke(cli, ["--foo="])126 assert not result.exception127 assert "FOO:[]" in result.output
422 unmodified lines
modified:tests/test_imports.py+1 added
45 unmodified lines
46 "datetime",47 "enum",48 "typing",49 "types",50 "gettext",51}5253if WIN:54 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])
14 unmodified lines
modified:tests/test_options.py+2 added-2 removed
81 unmodified lines
82 pass8384 result = runner.invoke(cli, [unknown_flag])85 assert result.exception86 assert f"no such option: {unknown_flag}" in result.output86 assert f"No such option: {unknown_flag}" in result.output878889@pytest.mark.parametrize(90 ("value", "expect"),
349 unmodified lines
440441 with pytest.raises(click.MissingParameter) as excinfo:442 click.Option(["-a"], required=True).process_value(ctx, None)443444 assert str(excinfo.value) == "missing parameter: a"444 assert str(excinfo.value) == "Missing parameter: a"445446447def test_missing_choice(runner):448 @click.command()
289 unmodified lines
modified:tests/test_termui.py+1 added-1 removed
374 unmodified lines
375@pytest.mark.parametrize(376 ("prompt_required", "required", "args", "expect"),377 [378 (True, False, None, "prompt"),379 (True, False, ["-v"], "-v option requires an argument"),379 (True, False, ["-v"], "Option '-v' requires an argument."),380 (False, True, None, "prompt"),381 (False, True, ["-v"], "prompt"),382 ],383)
64 unmodified lines
modified:CHANGES.rst+2 added
195 unmodified lines
196 well as in the short help. The notice is not in all caps.197 :issue:`1791`198- When taking arguments from ``sys.argv`` on Windows, glob patterns,199 user dir, and env vars are expanded. :issue:`1096`200- Marked messages shown by the CLI with ``gettext()`` to allow201 applications to translate Click's built-in strings. :issue:`303`202203204Version 7.1.2205-------------
635 unmodified lines