Merge branch '8.1.x'
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 · parents 187666a, f20395d · Browse files · 28 files·+696 added−247 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
28 files+696 added−247 removed
- tests:+213 added−46 removed
- other:+483 added−201 removed
Provenance
- Commit
d9af5cf- Tree
57774e0- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
187666a- Parent 2
f20395d
28 files changed+696 added−247 removed
modified:docs/arguments.rst+3 added-9 removed
122 unmodified lines123 -------------------124 125 In the previous example, the files were opened immediately. But what if126 we just want the filename? The naïve way is to use the default string127-argument type. However, remember that Click is Unicode-based, so the string128-will always be a Unicode value. Unfortunately, filenames can be Unicode or129-bytes depending on which operating system is being used. As such, the type130-is insufficient.127+argument type. The :class:`Path` type has several checks available which raise nice128+errors if they fail, such as existence. Filenames in these error messages are formatted129+with :func:`format_filename`, so any undecodable bytes will be printed nicely.130 132-Instead, you should be using the :class:`Path` type, which automatically133-handles this ambiguity. Not only will it return either bytes or Unicode134-depending on what makes more sense, but it will also be able to do some135-basic checks for you such as existence checks.136-131 Example:132 133 .. click:example::134 129 unmodified linesmodified:docs/complex.rst+163 added
216 unmodified lines217 218 .. click:run::219 220 invoke(cp, [])221+222+Lazily Loading Subcommands223+--------------------------224+225+Large CLIs and CLIs with slow imports may benefit from deferring the loading of226+subcommands. The interfaces which support this mode of use are227+:meth:`MultiCommand.list_commands` and :meth:`MultiCommand.get_command`. A custom228+:class:`MultiCommand` subclass can implement a lazy loader by storing extra data such229+that :meth:`MultiCommand.get_command` is responsible for running imports.230+231+Since the primary case for this is a :class:`Group` which loads its subcommands lazily,232+the following example shows a lazy-group implementation.233+234+.. warning::235+236+ Lazy loading of python code can result in hard to track down bugs, circular imports237+ in order-dependent codebases, and other surprising behaviors. It is recommended that238+ this technique only be used in concert with testing which will at least run the239+ ``--help`` on each subcommand. That will guarantee that each subcommand can be loaded240+ successfully.241+242+Defining the Lazy Group243+```````````````````````244+245+The following :class:`Group` subclass adds an attribute, ``lazy_subcommands``, which246+stores a mapping from subcommand names to the information for importing them.247+248+.. code-block:: python249+250+ # in lazy_group.py251+ import importlib252+ import click253+254+ class LazyGroup(click.Group):255+ def __init__(self, *args, lazy_subcommands=None, **kwargs):256+ super().__init__(*args, **kwargs)257+ # lazy_subcommands is a map of the form:258+ #259+ # {command-name} -> {module-name}.{command-object-name}260+ #261+ self.lazy_subcommands = lazy_subcommands or {}262+263+ def list_commands(self, ctx):264+ base = super().list_commands(ctx)265+ lazy = sorted(self.lazy_subcommands.keys())266+ return base + lazy267+268+ def get_command(self, ctx, cmd_name):269+ if cmd_name in self.lazy_subcommands:270+ return self._lazy_load(cmd_name)271+ return super().get_command(ctx, cmd_name)272+273+ def _lazy_load(self, cmd_name):274+ # lazily loading a command, first get the module name and attribute name275+ import_path = self.lazy_subcommands[cmd_name]276+ modname, cmd_object_name = import_path.rsplit(".", 1)277+ # do the import278+ mod = importlib.import_module(modname)279+ # get the Command object from that module280+ cmd_object = getattr(mod, cmd_object_name)281+ # check the result to make debugging easier282+ if not isinstance(cmd_object, click.BaseCommand):283+ raise ValueError(284+ f"Lazy loading of {import_path} failed by returning "285+ "a non-command object"286+ )287+ return cmd_object288+289+Using LazyGroup To Define a CLI290+```````````````````````````````291+292+With ``LazyGroup`` defined, it's now possible to write a group which lazily loads its293+subcommands like so:294+295+.. code-block:: python296+297+ # in main.py298+ import click299+ from lazy_group import LazyGroup300+301+ @click.group(302+ cls=LazyGroup,303+ lazy_subcommands={"foo": "foo.cli", "bar": "bar.cli"},304+ help="main CLI command for lazy example",305+ )306+ def cli():307+ pass308+309+ # in foo.py310+ import click311+312+ @click.group(help="foo command for lazy example")313+ def cli():314+ pass315+316+ # in bar.py317+ import click318+ from lazy_group import LazyGroup319+320+ @click.group(321+ cls=LazyGroup,322+ lazy_subcommands={"baz": "baz.cli"},323+ help="bar command for lazy example",324+ )325+ def cli():326+ pass327+328+ # in baz.py329+ import click330+331+ @click.group(help="baz command for lazy example")332+ def cli():333+ pass334+335+336+What triggers Lazy Loading?337+```````````````````````````338+339+There are several events which may trigger lazy loading by running the340+:meth:`MultiCommand.get_command` function.341+Some are intuititve, and some are less so.342+343+All cases are described with respect to the above example, assuming the main program344+name is ``cli``.345+346+1. Command resolution. If a user runs ``cli bar baz``, this must first resolve ``bar``,347+ and then resolve ``baz``. Each subcommand resolution step does a lazy load.348+2. Helptext rendering. In order to get the short help description of subcommands,349+ ``cli --help`` will load ``foo`` and ``bar``. Note that it will still not load350+ ``baz``.351+3. Shell completion. In order to get the subcommands of a lazy command, ``cli <TAB>``352+ will need to resolve the subcommands of ``cli``. This process will trigger the lazy353+ loads.354+355+Further Deferring Imports356+`````````````````````````357+358+It is possible to make the process even lazier, but it is generally more difficult the359+more you want to defer work.360+361+For example, subcommands could be represented as a custom :class:`BaseCommand` subclass362+which defers importing the command until it is invoked, but which provides363+:meth:`BaseCommand.get_short_help_str` in order to support completions and helptext.364+More simply, commands can be constructed whose callback functions defer any actual work365+until after an import.366+367+This command definition provides ``foo``, but any of the work associated with importing368+the "real" callback function is deferred until invocation time:369+370+.. click:example::371+372+ @click.command()373+ @click.option("-n", type=int)374+ @click.option("-w", type=str)375+ def foo(n, w):376+ from mylibrary import foo_concrete377+378+ foo_concrete(n, w)379+380+Because ``click`` builds helptext and usage info from options, arguments, and command381+attributes, it has no awareness that the underlying function is in any way handling a382+deferred import. Therefore, all ``click``-provided utilities and functionality will work383+as normal on such a command.modified:docs/conf.py-5 removed
1 from pallets_sphinx_themes import get_version2 from pallets_sphinx_themes import ProjectLink3 4-import click._compat5-6-# compat until pallets-sphinx-themes is updated7-click._compat.text_type = str8-4 # Project --------------------------------------------------------------5 6 project = "Click"7 copyright = "2014 Pallets"45 unmodified linesmodified:docs/contrib.rst+10 added-14 removed
2 unmodified lines3 =============4 click-contrib5 =============6 7-As the userbase of Click grows, more and more major feature requests pop up in8-Click's bugtracker. As reasonable as it may be for those features to be bundled9-with Click instead of being a standalone project, many of those requested10-features are either highly experimental or have unproven practical use, while11-potentially being a burden to maintain.7+As the number of users of Click grows, more and more major feature requests are8+made. To users it may seem reasonable to include those features with Click;9+however, many of them are experimental or aren't practical to support10+generically. Maintainers have to choose what is reasonable to maintain in Click11+core.12 13-This is why click-contrib_ exists. The GitHub organization is a collection of14-possibly experimental third-party packages whose featureset does not belong15-into Click, but also a playground for major features that may be added to Click16-in the future. It is also meant to coordinate and concentrate effort on writing17-third-party extensions for Click, and to ease the effort of searching for such18-extensions. In that sense it could be described as a low-maintenance19-alternative to extension repositories of other frameworks.13+The click-contrib_ GitHub organization exists as a place to collect third-party14+packages that extend Click's features. It is also meant to ease the effort of15+searching for such extensions.16 17 Please note that the quality and stability of those packages may be different22-than what you expect from Click itself. While published under a common23-organization, they are still projects separate from Click.18+than Click itself. While published under a common organization, they are still19+separate from Click and the Pallets maintainers.20 21 .. _click-contrib: https://github.com/click-contrib/modified:docs/documentation.rst+28 added-2 removed
83 unmodified lines84 Preventing Rewrapping85 ---------------------86 87 The default behavior of Click is to rewrap text based on the width of the88-terminal. In some circumstances, this can become a problem. The main issue89-is when showing code examples, where newlines are significant.88+terminal, to a maximum 80 characters. In some circumstances, this can become89+a problem. The main issue is when showing code examples, where newlines are90+significant.91 92 Rewrapping can be disabled on a per-paragraph basis by adding a line with93 solely the ``\b`` escape marker in it. This line will be removed from the94 help text and rewrapping will be disabled.25 unmodified lines120 .. click:run::121 122 invoke(cli, args=['--help'])123 124+To change the maximum width, pass ``max_content_width`` when calling the command.125+126+.. code-block:: python127+128+ cli(max_content_width=120)129+130+131 .. _doc-meta-variables:132 133 Truncating Help Texts134 ---------------------81 unmodified lines216 .. click:run::217 218 invoke(cli, prog_name='repo.py')219 220+Command Epilog Help221+-------------------222 223+The help epilog is like the help string but it's printed at the end of the help224+page after everything else. Useful for showing example command usages or225+referencing additional help resources.226+227+.. click:example::228+229+ @click.command(epilog='Check out our docs at https://click.palletsprojects.com/ for more details')230+ def init():231+ """Initializes the repository."""232+233+And what it looks like:234+235+.. click:run::236+237+ invoke(init, prog_name='repo.py', args=['--help'])238+239 Help Parameter Customization240 ----------------------------241 242 .. versionadded:: 2.025 unmodified linesmodified:docs/quickstart.rst+8 added-26 removed
27 unmodified lines28 29 Virtualenv to the rescue! Virtualenv enables multiple side-by-side30 installations of Python, one for each project. It doesn't actually31 install separate copies of Python, but it does provide a clever way to32-keep different project environments isolated. Let's see how virtualenv33-works.32+keep different project environments isolated.33 35-If you are on Mac OS X or Linux::34+Create your project folder, then a virtualenv within it::35 37- $ pip install virtualenv --user38-39-One of these will probably install virtualenv on your system. Maybe it's even40-in your package manager. If you use Ubuntu, try::41-42- $ sudo apt-get install python-virtualenv43-44-If you are on Windows (or none of the above methods worked) you must install45-``pip`` first. For more information about this, see `installing pip`_.46-Once you have it installed, run the ``pip`` command from above, but without47-the `sudo` prefix.48-49-.. _installing pip: https://pip.readthedocs.io/en/latest/installing/50-51-Once you have virtualenv installed, just fire up a shell and create52-your own environment. I usually create a project folder and a `venv`53-folder within::54-36 $ mkdir myproject37 $ cd myproject57- $ virtualenv venv58- New python executable in venv/bin/python38+ $ python3 -m venv .venv39 40 Now, whenever you want to work on a project, you only have to activate the41 corresponding environment. On OS X and Linux, do the following::42 63- $ . venv/bin/activate43+ $ . .venv/bin/activate44+ (venv) $45 46 If you are a Windows user, the following command is for you::47 67- $ venv\scripts\activate48+ > .venv\scripts\activate49+ (venv) >50 51 Either way, you should now be using your virtualenv (notice how the prompt of52 your shell has changed to show the active environment).53 72-And if you want to go back to the real world, use the following command::54+And if you want to stop using the virtualenv, use the following command::55 56 $ deactivate57 58 After doing this, the prompt of your shell should be as familiar as before.218 unmodified linesmodified:src/click/_compat.py+13 added-16 removed
5 unmodified lines6 import typing as t7 from weakref import WeakKeyDictionary8 9 CYGWIN = sys.platform.startswith("cygwin")10-MSYS2 = sys.platform.startswith("win") and ("GCC" in sys.version)11-# Determine local App Engine environment, per Google's own suggestion12-APP_ENGINE = "APPENGINE_RUNTIME" in os.environ and "Development/" in os.environ.get(13- "SERVER_SOFTWARE", ""14-)15-WIN = sys.platform.startswith("win") and not APP_ENGINE and not MSYS210+WIN = sys.platform.startswith("win")11 auto_wrap_for_ansi: t.Optional[t.Callable[[t.TextIO], t.TextIO]] = None12 _ansi_re = re.compile(r"\033\[[;?0-9]*[a-zA-Z]")13 14 20-def get_filesystem_encoding() -> str:21- return sys.getfilesystemencoding() or sys.getdefaultencoding()22-23-15 def _make_text_stream(16 stream: t.BinaryIO,17 encoding: t.Optional[str],18 errors: t.Optional[str],338 unmodified lines357 return _force_correct_text_writer(sys.stderr, encoding, errors, force_writable=True)358 359 360 def _wrap_io_open(370- file: t.Union[str, "os.PathLike[t.AnyStr]", int],361+ file: t.Union[str, "os.PathLike[str]", int],362 mode: str,363 encoding: t.Optional[str],364 errors: t.Optional[str],365 ) -> t.IO[t.Any]:4 unmodified lines370 return open(file, mode, encoding=encoding, errors=errors)371 372 373 def open_stream(383- filename: str,374+ filename: "t.Union[str, os.PathLike[str]]",375 mode: str = "r",376 encoding: t.Optional[str] = None,377 errors: t.Optional[str] = "strict",378 atomic: bool = False,379 ) -> t.Tuple[t.IO[t.Any], bool]:380 binary = "b" in mode381+ filename = os.fspath(filename)382 383 # Standard streams first. These are simple because they ignore the384 # atomic flag. Use fsdecode to handle Path("-").385 if os.fsdecode(filename) == "-":169 unmodified lines555 556 else:557 558 def _get_argv_encoding() -> str:567- return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()559+ return getattr(sys.stdin, "encoding", None) or sys.getfilesystemencoding()560 561 def _get_windows_console_stream(562 f: t.TextIO, encoding: t.Optional[str], errors: t.Optional[str]563 ) -> t.Optional[t.TextIO]:11 unmodified lines575 return False576 577 578 def _make_cached_stream_func(587- src_func: t.Callable[[], t.TextIO], wrapper_func: t.Callable[[], t.TextIO]588-) -> t.Callable[[], t.TextIO]:579+ src_func: t.Callable[[], t.Optional[t.TextIO]],580+ wrapper_func: t.Callable[[], t.TextIO],581+) -> t.Callable[[], t.Optional[t.TextIO]]:582 cache: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()583 591- def func() -> t.TextIO:584+ def func() -> t.Optional[t.TextIO]:585 stream = src_func()586+587+ if stream is None:588+ return None589+590 try:591 rv = cache.get(stream)592 except Exception:593 rv = None30 unmodified linesmodified:src/click/_termui_impl.py+31 added-9 removed
8 unmodified lines9 import sys10 import time11 import typing as t12 from gettext import gettext as _13+from io import StringIO14+from types import TracebackType15 16 from ._compat import _default_text_stdout17 from ._compat import CYGWIN18 from ._compat import get_best_encoding41 unmodified lines60 self.show_eta = show_eta61 self.show_percent = show_percent62 self.show_pos = show_pos63 self.item_show_func = item_show_func62- self.label = label or ""64+ self.label: str = label or ""65+66 if file is None:67 file = _default_text_stdout()68+69+ # There are no standard streams attached to write to. For example,70+ # pythonw on Windows.71+ if file is None:72+ file = StringIO()73+74 self.file = file75 self.color = color76 self.update_min_steps = update_min_steps77 self._completed_intervals = 069- self.width = width70- self.autowidth = width == 078+ self.width: int = width79+ self.autowidth: bool = width == 080 81 if length is None:82 from operator import length_hint83 4 unmodified lines88 if iterable is None:89 if length is None:90 raise TypeError("iterable or length is required")91 iterable = t.cast(t.Iterable[V], range(length))83- self.iter = iter(iterable)92+ self.iter: t.Iterable[V] = iter(iterable)93 self.length = length94 self.pos = 095 self.avg: t.List[float] = []96+ self.last_eta: float97+ self.start: float98 self.start = self.last_eta = time.time()88- self.eta_known = False89- self.finished = False99+ self.eta_known: bool = False100+ self.finished: bool = False101 self.max_width: t.Optional[int] = None91- self.entered = False102+ self.entered: bool = False103 self.current_item: t.Optional[V] = None93- self.is_hidden = not isatty(self.file)104+ self.is_hidden: bool = not isatty(self.file)105 self._last_line: t.Optional[str] = None106 107 def __enter__(self) -> "ProgressBar[V]":108 self.entered = True109 self.render_progress()110 return self111 101- def __exit__(self, *_: t.Any) -> None:112+ def __exit__(113+ self,114+ exc_type: t.Optional[t.Type[BaseException]],115+ exc_value: t.Optional[BaseException],116+ tb: t.Optional[TracebackType],117+ ) -> None:118 self.render_finish()119 120 def __iter__(self) -> t.Iterator[V]:121 if not self.entered:237 unmodified lines359 360 def pager(generator: t.Iterable[str], color: t.Optional[bool] = None) -> None:361 """Decide what method to use for paging through text."""362 stdout = _default_text_stdout()363+364+ # There are no standard streams attached to write to. For example,365+ # pythonw on Windows.366+ if stdout is None:367+ stdout = StringIO()368+369 if not isatty(sys.stdin) or not isatty(stdout):370 return _nullpager(stdout, generator, color)371 pager_cmd = (os.environ.get("PAGER", None) or "").strip()372 if pager_cmd:367 unmodified linesmodified:src/click/core.py+40 added-21 removed
5 unmodified lines6 import typing as t7 from collections import abc8 from contextlib import contextmanager9 from contextlib import ExitStack10-from functools import partial10 from functools import update_wrapper11 from gettext import gettext as _12 from gettext import ngettext13 from itertools import repeat14+from types import TracebackType15 16 from . import types17 from .exceptions import Abort18 from .exceptions import BadParameter435 unmodified lines454 self._depth += 1455 push_context(self)456 return self457 458- def __exit__(self, *_: t.Any) -> None:458+ def __exit__(459+ self,460+ exc_type: t.Optional[t.Type[BaseException]],461+ exc_value: t.Optional[BaseException],462+ tb: t.Optional[TracebackType],463+ ) -> None:464 self._depth -= 1465 if self._depth == 0:466 self.close()467 pop_context()617 unmodified lines1085 # chained commands which all returned `None` -- so it's not1086 # even always obvious that `rv` indicates success/failure1087 # by its truthiness/falsiness1088 ctx.exit()1084- except (EOFError, KeyboardInterrupt):1089+ except (EOFError, KeyboardInterrupt) as e:1090 echo(file=sys.stderr)1086- raise Abort() from None1091+ raise Abort() from e1092 except ClickException as e:1093 if not standalone_mode:1094 raise1095 e.show()37 unmodified lines1133 :param prog_name: Name of the executable in the shell.1134 :param complete_var: Name of the environment variable that holds1135 the completion instruction. Defaults to1136 ``_{PROG_NAME}_COMPLETE``.1137+1138+ .. versionchanged:: 8.2.01139+ Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).1140 """1141 if complete_var is None:1134- complete_var = f"_{prog_name}_COMPLETE".replace("-", "_").upper()1142+ complete_name = prog_name.replace("-", "_").replace(".", "_")1143+ complete_var = f"_{complete_name}_COMPLETE".upper()1144 1145 instruction = os.environ.get(complete_var)1146 1147 if not instruction:211 unmodified lines1359 self.format_epilog(ctx, formatter)1360 1361 def format_help_text(self, ctx: Context, formatter: HelpFormatter) -> None:1362 """Writes the help text to the formatter if it exists."""1354- text = self.help if self.help is not None else ""1363+ if self.help is not None:1364+ # truncate the help text to the first form feed1365+ text = inspect.cleandoc(self.help).partition("\f")[0]1366+ else:1367+ text = ""1368 1369 if self.deprecated:1370 text = _("(Deprecated) {text}").format(text=text)1371 1372 if text:1360- text = inspect.cleandoc(text).partition("\f")[0]1373 formatter.write_paragraph()1374 1375 with formatter.indentation():1376 formatter.write_text(text)493 unmodified lines1870 Added the :attr:`command_class` attribute.1871 """1872 from .decorators import command1873 1862- if self.command_class and kwargs.get("cls") is None:1863- kwargs["cls"] = self.command_class1864-1874 func: t.Optional[t.Callable[..., t.Any]] = None1875 1876 if args and callable(args[0]):1877 assert (1 unmodified line1879 ), "Use 'command(**kwargs)(callable)' to provide arguments."1880 (func,) = args1881 args = ()1882 1883+ if self.command_class and kwargs.get("cls") is None:1884+ kwargs["cls"] = self.command_class1885+1886 def decorator(f: t.Callable[..., t.Any]) -> Command:1887 cmd: Command = command(*args, **kwargs)(f)1888 self.add_command(cmd)1889 return cmd214 unmodified lines2104 t.Union[t.List["CompletionItem"], t.List[str]],2105 ]2106 ] = None,2107 ) -> None:2108+ self.name: t.Optional[str]2109+ self.opts: t.List[str]2110+ self.secondary_opts: t.List[str]2111 self.name, self.opts, self.secondary_opts = self._parse_decls(2112 param_decls or (), expose_value2113 )2099- self.type = types.convert_type(type, default)2114+ self.type: types.ParamType = types.convert_type(type, default)2115 2116 # Default nargs to what the type tells us if we have that2117 # information available.2118 if nargs is None:191 unmodified lines2310 _("Value must be an iterable."), ctx=ctx, param=self2311 ) from None2312 2313 if self.nargs == 1 or self.type.is_composite:2299- convert: t.Callable[[t.Any], t.Any] = partial(2300- self.type, param=self, ctx=ctx2301- )2314+2315+ def convert(value: t.Any) -> t.Any:2316+ return self.type(value, param=self, ctx=ctx)2317+2318 elif self.nargs == -1:2319 2304- def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2320+ def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...]2321 return tuple(self.type(x, self, ctx) for x in check_iter(value))2322 2323 else: # nargs > 12324 2309- def convert(value: t.Any) -> t.Tuple[t.Any, ...]:2325+ def convert(value: t.Any) -> t.Any: # t.Tuple[t.Any, ...]2326 value = tuple(check_iter(value))2327 2328 if len(value) != self.nargs:2329 raise BadParameter(239 unmodified lines2569 # Not a flag, and prompt is not enabled, can be used as a2570 # flag if flag_value is set.2571 self._flag_needs_value = flag_value is not None2572 2573+ self.default: t.Union[t.Any, t.Callable[[], t.Any]]2574+2575 if is_flag and default_is_missing and not self.required:2558- self.default: t.Union[t.Any, t.Callable[[], t.Any]] = False2576+ if multiple:2577+ self.default = ()2578+ else:2579+ self.default = False2580 2581 if flag_value is None:2582 flag_value = not self.default2583 2584+ self.type: types.ParamType2585 if is_flag and type is None:2586 # Re-guess the type from the flag value instead of the2587 # default.2588 self.type = types.convert_type(None, flag_value)2589 2590 self.is_flag: bool = is_flag2569- self.is_bool_flag = is_flag and isinstance(self.type, types.BoolParamType)2591+ self.is_bool_flag: bool = is_flag and isinstance(self.type, types.BoolParamType)2592 self.flag_value: t.Any = flag_value2593 2594 # Counting2595 self.count = count30 unmodified lines2626 2627 if self.is_flag:2628 raise TypeError("'count' is not valid with 'is_flag'.")2629 2608- if self.multiple and self.is_flag:2609- raise TypeError("'multiple' is not valid with 'is_flag', use 'count'.")2610-2630 def to_info_dict(self) -> t.Dict[str, t.Any]:2631 info_dict = super().to_info_dict()2632 info_dict.update(2633 help=self.help,409 unmodified linesmodified:src/click/decorators.py+12 added-8 removed
327 unmodified lines328 329 f.__click_params__.append(param) # type: ignore330 331 332-def argument(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]:332+def argument(333+ *param_decls: str, cls: t.Optional[t.Type[Argument]] = None, **attrs: t.Any334+) -> _Decorator[FC]:335 """Attaches an argument to the command. All positional arguments are336 passed as parameter declarations to :class:`Argument`; all keyword337 arguments are forwarded unchanged (except ``cls``).338 This is equivalent to creating an :class:`Argument` instance manually7 unmodified lines346 :param param_decls: Passed as positional arguments to the constructor of347 ``cls``.348 :param attrs: Passed as keyword arguments to the constructor of ``cls``.349 """350+ if cls is None:351+ cls = Argument352 353 def decorator(f: FC) -> FC:350- ArgumentClass = attrs.pop("cls", None) or Argument351- _param_memo(f, ArgumentClass(param_decls, **attrs))354+ _param_memo(f, cls(param_decls, **attrs))355 return f356 357 return decorator358 359 357-def option(*param_decls: str, **attrs: t.Any) -> _Decorator[FC]:360+def option(361+ *param_decls: str, cls: t.Optional[t.Type[Option]] = None, **attrs: t.Any362+) -> _Decorator[FC]:363 """Attaches an option to the command. All positional arguments are364 passed as parameter declarations to :class:`Option`; all keyword365 arguments are forwarded unchanged (except ``cls``).366 This is equivalent to creating an :class:`Option` instance manually7 unmodified lines374 :param param_decls: Passed as positional arguments to the constructor of375 ``cls``.376 :param attrs: Passed as keyword arguments to the constructor of ``cls``.377 """378+ if cls is None:379+ cls = Option380 381 def decorator(f: FC) -> FC:375- # Issue 926, copy attrs, so pre-defined options can re-use the same cls=376- option_attrs = attrs.copy()377- OptionClass = option_attrs.pop("cls", None) or Option378- _param_memo(f, OptionClass(param_decls, **option_attrs))382+ _param_memo(f, cls(param_decls, **attrs))383 return f384 385 return decorator386 184 unmodified linesmodified:src/click/exceptions.py+5 added-4 removed
1-import os1 import typing as t2 from gettext import gettext as _3 from gettext import ngettext4 5 from ._compat import get_text_stderr6 from .utils import echo7+from .utils import format_filename8 9 if t.TYPE_CHECKING:10+ from .core import Command11 from .core import Context12 from .core import Parameter13 14 42 unmodified lines57 58 def __init__(self, message: str, ctx: t.Optional["Context"] = None) -> None:59 super().__init__(message)60 self.ctx = ctx60- self.cmd = self.ctx.command if self.ctx else None61+ self.cmd: t.Optional["Command"] = self.ctx.command if self.ctx else None62 63 def show(self, file: t.Optional[t.IO[t.Any]] = None) -> None:64 if file is None:65 file = get_text_stderr()195 unmodified lines261 if hint is None:262 hint = _("unknown error")263 264 super().__init__(hint)264- self.ui_filename = os.fsdecode(filename)265+ self.ui_filename: str = format_filename(filename)266 self.filename = filename267 268 def format_message(self) -> str:269 return _("Could not open file {filename!r}: {message}").format(14 unmodified lines284 285 __slots__ = ("exit_code",)286 287 def __init__(self, code: int = 0) -> None:287- self.exit_code = code288+ self.exit_code: int = codemodified:src/click/parser.py+4 added-4 removed
166 unmodified lines167 const: t.Optional[t.Any] = None,168 ):169 self._short_opts = []170 self._long_opts = []171- self.prefixes = set()171+ self.prefixes: t.Set[str] = set()172 173 for opt in opts:174 prefix, value = split_opt(opt)175 if not prefix:17 unmodified lines193 @property194 def takes_value(self) -> bool:195 return self.action in ("store", "append")196 197- def process(self, value: str, state: "ParsingState") -> None:197+ def process(self, value: t.Any, state: "ParsingState") -> None:198 if self.action == "store":199 state.opts[self.dest] = value # type: ignore200 elif self.action == "store_const":201 state.opts[self.dest] = self.const # type: ignore69 unmodified lines271 #: This controls how the parser deals with interspersed arguments.272 #: If this is set to `False`, the parser will stop on the first273 #: non-option. Click uses this to implement nested subcommands274 #: safely.275- self.allow_interspersed_args = True275+ self.allow_interspersed_args: bool = True276 #: This tells the parser how to deal with unknown options. By277 #: default it will error out (which is sensible), but there is a278 #: second mode where it will ignore it and continue processing279 #: after shifting all the unknown options into the resulting args.280- self.ignore_unknown_options = False280+ self.ignore_unknown_options: bool = False281 282 if ctx is not None:283 self.allow_interspersed_args = ctx.allow_interspersed_args284 self.ignore_unknown_options = ctx.ignore_unknown_options245 unmodified linesmodified:src/click/shell_completion.py+30 added-25 removed
78 unmodified lines79 type: str = "plain",80 help: t.Optional[str] = None,81 **kwargs: t.Any,82 ) -> None:83- self.value = value84- self.type = type85- self.help = help83+ self.value: t.Any = value84+ self.type: str = type85+ self.help: t.Optional[str] = help86 self._info = kwargs87 88 def __getattr__(self, name: str) -> t.Any:89 return self._info.get(name)66 unmodified lines156 compadd -U -V unsorted -a completions157 fi158 }159 160+if [[ $zsh_eval_context[-1] == loadautofunc ]]; then161+ # autoload from fpath, call function directly162+ %(complete_func)s "$@"163+else164+ # eval/source/. command, register function for later160-compdef %(complete_func)s %(prog_name)s;165+ compdef %(complete_func)s %(prog_name)s166+fi167 """168 169 _SOURCE_FISH = """\164-function %(complete_func)s;165- set -l response;170+function %(complete_func)s171+ set -l response (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \172+COMP_CWORD=(commandline -t) %(prog_name)s)173 167- for value in (env %(complete_var)s=fish_complete COMP_WORDS=(commandline -cp) \168-COMP_CWORD=(commandline -t) %(prog_name)s);169- set response $response $value;170- end;174+ for completion in $response175+ set -l metadata (string split "," $completion)176 172- for completion in $response;173- set -l metadata (string split "," $completion);177+ if test $metadata[1] = "dir"178+ __fish_complete_directories $metadata[2]179+ else if test $metadata[1] = "file"180+ __fish_complete_path $metadata[2]181+ else if test $metadata[1] = "plain"182+ echo $metadata[2]183+ end184+ end185+end186 175- if test $metadata[1] = "dir";176- __fish_complete_directories $metadata[2];177- else if test $metadata[1] = "file";178- __fish_complete_path $metadata[2];179- else if test $metadata[1] = "plain";180- echo $metadata[2];181- end;182- end;183-end;184-187 complete --no-files --command %(prog_name)s --arguments \186-"(%(complete_func)s)";188+"(%(complete_func)s)"189 """190 191 192 class ShellComplete:111 unmodified lines304 def _check_version(self) -> None:305 import subprocess306 307 output = subprocess.run(306- ["bash", "-c", "echo ${BASH_VERSION}"], stdout=subprocess.PIPE308+ ["bash", "-c", 'echo "${BASH_VERSION}"'], stdout=subprocess.PIPE309 )310 match = re.search(r"^(\d+)\.(\d+)\.\d+", output.stdout.decode())311 312 if match is not None:129 unmodified lines442 if not isinstance(param, Argument):443 return False444 445 assert param.name is not None444- value = ctx.params[param.name]446+ # Will be None if expose_value is False.447+ value = ctx.params.get(param.name)448 return (449 param.nargs == -1450 or ctx.get_parameter_source(param.name) is not ParameterSource.COMMANDLINE451 or (67 unmodified lines519 520 ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)521 args = ctx.protected_args + ctx.args522 else:523+ sub_ctx = ctx524+525 while args:526 name, cmd, args = command.resolve_command(ctx, args)527 528 if cmd is None:65 unmodified linesmodified:src/click/termui.py+3 added-6 removed
1 import inspect2 import io3 import itertools4-import os4 import sys5 import typing as t6 from gettext import gettext as _7 8 from ._compat import isatty9 from ._compat import strip_ansi11-from ._compat import WIN10 from .exceptions import Abort11 from .exceptions import UsageError12 from .globals import resolve_color_default13 from .types import Choice426 unmodified lines440 .. versionadded:: 2.0441 """442 if not isatty(sys.stdout):443 return446- if WIN:447- os.system("cls")448- else:449- sys.stdout.write("\033[2J\033[1;1H")444 445+ # ANSI escape \033[2J clears the screen, \033[1;1H moves the cursor446+ echo("\033[2J\033[1;1H", nl=False)447 448+449 def _interpret_color(450 color: t.Union[int, t.Tuple[int, int, int], str], offset: int = 0451 ) -> str:452 if isinstance(color, int):332 unmodified linesmodified:src/click/testing.py+1 added-1 removed
181 unmodified lines182 echo_stdin: bool = False,183 mix_stderr: bool = True,184 ) -> None:185 self.charset = charset186- self.env = env or {}186+ self.env: t.Mapping[str, t.Optional[str]] = env or {}187 self.echo_stdin = echo_stdin188 self.mix_stderr = mix_stderr189 190 def get_default_prog_name(self, cli: "BaseCommand") -> str:289 unmodified linesmodified:src/click/types.py+49 added-30 removed
1 import os2 import stat3+import sys4 import typing as t5 from datetime import datetime6 from gettext import gettext as _7 from gettext import ngettext8 9 from ._compat import _get_argv_encoding9-from ._compat import get_filesystem_encoding10 from ._compat import open_stream11 from .exceptions import BadParameter12+from .utils import format_filename13 from .utils import LazyFile14 from .utils import safecall15 16 if t.TYPE_CHECKING:145 unmodified lines162 163 164 class FuncParamType(ParamType):165 def __init__(self, func: t.Callable[[t.Any], t.Any]) -> None:165- self.name = func.__name__166+ self.name: str = func.__name__167 self.func = func168 169 def to_info_dict(self) -> t.Dict[str, t.Any]:170 info_dict = super().to_info_dict()36 unmodified lines207 enc = _get_argv_encoding()208 try:209 value = value.decode(enc)210 except UnicodeError:210- fs_enc = get_filesystem_encoding()211+ fs_enc = sys.getfilesystemencoding()212 if fs_enc != enc:213 try:214 value = value.decode(fs_enc)215 except UnicodeError:137 unmodified lines353 354 name = "datetime"355 356 def __init__(self, formats: t.Optional[t.Sequence[str]] = None):356- self.formats = formats or ["%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]357+ self.formats: t.Sequence[str] = formats or [358+ "%Y-%m-%d",359+ "%Y-%m-%dT%H:%M:%S",360+ "%Y-%m-%d %H:%M:%S",361+ ]362 363 def to_info_dict(self) -> t.Dict[str, t.Any]:364 info_dict = super().to_info_dict()365 info_dict["formats"] = self.formats300 unmodified lines666 See :ref:`file-args` for more information.667 """668 669 name = "filename"665- envvar_list_splitter = os.path.pathsep670+ envvar_list_splitter: t.ClassVar[str] = os.path.pathsep671 672 def __init__(673 self,674 mode: str = "r",12 unmodified lines687 info_dict = super().to_info_dict()688 info_dict.update(mode=self.mode, encoding=self.encoding)689 return info_dict690 686- def resolve_lazy_flag(self, value: t.Any) -> bool:691+ def resolve_lazy_flag(self, value: "t.Union[str, os.PathLike[str]]") -> bool:692 if self.lazy is not None:693 return self.lazy689- if value == "-":694+ if os.fspath(value) == "-":695 return False696 elif "w" in self.mode:697 return True698 return False699 700 def convert(696- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]697- ) -> t.Any:698- try:699- if hasattr(value, "read") or hasattr(value, "write"):700- return value701+ self,702+ value: t.Union[str, "os.PathLike[str]", t.IO[t.Any]],703+ param: t.Optional["Parameter"],704+ ctx: t.Optional["Context"],705+ ) -> t.IO[t.Any]:706+ if _is_file_like(value):707+ return value708 709+ value = t.cast("t.Union[str, os.PathLike[str]]", value)710+711+ try:712 lazy = self.resolve_lazy_flag(value)713 714 if lazy:715 lf = LazyFile(21 unmodified lines737 ctx.call_on_close(safecall(f.flush))738 739 return f740 except OSError as e: # noqa: B014731- self.fail(f"'{os.fsdecode(value)}': {e.strerror}", param, ctx)741+ self.fail(f"'{format_filename(value)}': {e.strerror}", param, ctx)742 743 def shell_complete(744 self, ctx: "Context", param: "Parameter", incomplete: str745 ) -> t.List["CompletionItem"]:10 unmodified lines756 757 return [CompletionItem(incomplete, type="file")]758 759 760+def _is_file_like(value: t.Any) -> "te.TypeGuard[t.IO[t.Any]]":761+ return hasattr(value, "read") or hasattr(value, "write")762+763+764 class Path(ParamType):765 """The ``Path`` type is similar to the :class:`File` type, but766 returns the filename instead of an open file. Various checks can be767 enabled to validate the type of file and permissions.25 unmodified lines793 .. versionchanged:: 6.0794 Added the ``allow_dash`` parameter.795 """796 783- envvar_list_splitter = os.path.pathsep797+ envvar_list_splitter: t.ClassVar[str] = os.path.pathsep798 799 def __init__(800 self,801 exists: bool = False,16 unmodified lines818 self.allow_dash = allow_dash819 self.type = path_type820 821 if self.file_okay and not self.dir_okay:808- self.name = _("file")822+ self.name: str = _("file")823 elif self.dir_okay and not self.file_okay:824 self.name = _("directory")825 else:826 self.name = _("path")9 unmodified lines836 allow_dash=self.allow_dash,837 )838 return info_dict839 826- def coerce_path_result(self, rv: t.Any) -> t.Any:827- if self.type is not None and not isinstance(rv, self.type):840+ def coerce_path_result(841+ self, value: "t.Union[str, os.PathLike[str]]"842+ ) -> "t.Union[str, bytes, os.PathLike[str]]":843+ if self.type is not None and not isinstance(value, self.type):844 if self.type is str:829- rv = os.fsdecode(rv)845+ return os.fsdecode(value)846 elif self.type is bytes:831- rv = os.fsencode(rv)847+ return os.fsencode(value)848 else:833- rv = self.type(rv)849+ return t.cast("os.PathLike[str]", self.type(value))850 835- return rv851+ return value852 853 def convert(838- self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]839- ) -> t.Any:854+ self,855+ value: "t.Union[str, os.PathLike[str]]",856+ param: t.Optional["Parameter"],857+ ctx: t.Optional["Context"],858+ ) -> "t.Union[str, bytes, os.PathLike[str]]":859 rv = value860 861 is_dash = self.file_okay and self.allow_dash and rv in (b"-", "-")862 11 unmodified lines874 if not self.exists:875 return self.coerce_path_result(rv)876 self.fail(877 _("{name} {filename!r} does not exist.").format(859- name=self.name.title(), filename=os.fsdecode(value)878+ name=self.name.title(), filename=format_filename(value)879 ),880 param,881 ctx,882 )883 884 if not self.file_okay and stat.S_ISREG(st.st_mode):885 self.fail(886 _("{name} {filename!r} is a file.").format(868- name=self.name.title(), filename=os.fsdecode(value)887+ name=self.name.title(), filename=format_filename(value)888 ),889 param,890 ctx,891 )892 if not self.dir_okay and stat.S_ISDIR(st.st_mode):893 self.fail(894 _("{name} '{filename}' is a directory.").format(876- name=self.name.title(), filename=os.fsdecode(value)895+ name=self.name.title(), filename=format_filename(value)896 ),897 param,898 ctx,899 )900 901 if self.readable and not os.access(rv, os.R_OK):902 self.fail(903 _("{name} {filename!r} is not readable.").format(885- name=self.name.title(), filename=os.fsdecode(value)904+ name=self.name.title(), filename=format_filename(value)905 ),906 param,907 ctx,908 )909 910 if self.writable and not os.access(rv, os.W_OK):911 self.fail(912 _("{name} {filename!r} is not writable.").format(894- name=self.name.title(), filename=os.fsdecode(value)913+ name=self.name.title(), filename=format_filename(value)914 ),915 param,916 ctx,917 )918 919 if self.executable and not os.access(value, os.X_OK):920 self.fail(921 _("{name} {filename!r} is not executable.").format(903- name=self.name.title(), filename=os.fsdecode(value)922+ name=self.name.title(), filename=format_filename(value)923 ),924 param,925 ctx,926 )33 unmodified lines960 :param types: a list of types that should be used for the tuple items.961 """962 963 def __init__(self, types: t.Sequence[t.Union[t.Type[t.Any], ParamType]]) -> None:945- self.types = [convert_type(ty) for ty in types]964+ self.types: t.Sequence[ParamType] = [convert_type(ty) for ty in types]965 966 def to_info_dict(self) -> t.Dict[str, t.Any]:967 info_dict = super().to_info_dict()968 info_dict["types"] = [t.to_info_dict() for t in self.types]121 unmodified linesmodified:src/click/utils.py+56 added-17 removed
2 unmodified lines3 import sys4 import typing as t5 from functools import update_wrapper6 from types import ModuleType7+from types import TracebackType8 9 from ._compat import _default_text_stderr10 from ._compat import _default_text_stdout11 from ._compat import _find_binary_writer12 from ._compat import auto_wrap_for_ansi13 from ._compat import binary_streams13-from ._compat import get_filesystem_encoding14 from ._compat import open_stream15 from ._compat import should_strip_ansi16 from ._compat import strip_ansi17 from ._compat import text_streams28 unmodified lines46 def make_str(value: t.Any) -> str:47 """Converts a value into a valid string."""48 if isinstance(value, bytes):49 try:50- return value.decode(get_filesystem_encoding())50+ return value.decode(sys.getfilesystemencoding())51 except UnicodeError:52 return value.decode("utf-8", "replace")53 return str(value)54 56 unmodified lines111 """112 113 def __init__(114 self,115- filename: str,115+ filename: t.Union[str, "os.PathLike[str]"],116 mode: str = "r",117 encoding: t.Optional[str] = None,118 errors: t.Optional[str] = "strict",119 atomic: bool = False,120 ):121- self.name = filename121+ self.name: str = os.fspath(filename)122 self.mode = mode123 self.encoding = encoding124 self.errors = errors125 self.atomic = atomic126 self._f: t.Optional[t.IO[t.Any]]127+ self.should_close: bool128 128- if filename == "-":129+ if self.name == "-":130 self._f, self.should_close = open_stream(filename, mode, encoding, errors)131 else:132 if "r" in mode:133 # Open and close the file in case we're opening it for8 unmodified lines142 143 def __repr__(self) -> str:144 if self._f is not None:145 return repr(self._f)145- return f"<unopened file '{self.name}' {self.mode}>"146+ return f"<unopened file '{format_filename(self.name)}' {self.mode}>"147 148 def open(self) -> t.IO[t.Any]:149 """Opens the file if it's not yet open. This call might fail with150 a :exc:`FileError`. Not handling this error will produce an error26 unmodified lines177 178 def __enter__(self) -> "LazyFile":179 return self180 180- def __exit__(self, *_: t.Any) -> None:181+ def __exit__(182+ self,183+ exc_type: t.Optional[t.Type[BaseException]],184+ exc_value: t.Optional[BaseException],185+ tb: t.Optional[TracebackType],186+ ) -> None:187 self.close_intelligently()188 189 def __iter__(self) -> t.Iterator[t.AnyStr]:190 self.open()1 unmodified line192 193 194 class KeepOpenFile:195 def __init__(self, file: t.IO[t.Any]) -> None:190- self._file = file196+ self._file: t.IO[t.Any] = file197 198 def __getattr__(self, name: str) -> t.Any:199 return getattr(self._file, name)200 201 def __enter__(self) -> "KeepOpenFile":202 return self203 198- def __exit__(self, *_: t.Any) -> None:204+ def __exit__(205+ self,206+ exc_type: t.Optional[t.Type[BaseException]],207+ exc_value: t.Optional[BaseException],208+ tb: t.Optional[TracebackType],209+ ) -> None:210 pass211 212 def __repr__(self) -> str:213 return repr(self._file)52 unmodified lines266 file = _default_text_stderr()267 else:268 file = _default_text_stdout()269 270+ # There are no standard streams attached to write to. For example,271+ # pythonw on Windows.272+ if file is None:273+ return274+275 # Convert non bytes/text into the native string type.276 if message is not None and not isinstance(message, (str, bytes, bytearray)):277 out: t.Optional[t.Union[str, bytes]] = str(message)278 else:122 unmodified lines401 return f402 403 404 def format_filename(389- filename: t.Union[str, bytes, "os.PathLike[t.AnyStr]"], shorten: bool = False405+ filename: "t.Union[str, bytes, os.PathLike[str], os.PathLike[bytes]]",406+ shorten: bool = False,407 ) -> str:391- """Formats a filename for user display. The main purpose of this392- function is to ensure that the filename can be displayed at all. This393- will decode the filename to unicode if necessary in a way that it will394- not fail. Optionally, it can shorten the filename to not include the395- full path to the filename.408+ """Format a filename as a string for display. Ensures the filename can be409+ displayed by replacing any invalid bytes or surrogate escapes in the name410+ with the replacement character ``�``.411 412+ Invalid bytes or surrogate escapes will raise an error when written to a413+ stream with ``errors="strict". This will typically happen with ``stdout``414+ when the locale is something like ``en_GB.UTF-8``.415+416+ Many scenarios *are* safe to write surrogates though, due to PEP 538 and417+ PEP 540, including:418+419+ - Writing to ``stderr``, which uses ``errors="backslashreplace"``.420+ - The system has ``LANG=C.UTF-8``, ``C``, or ``POSIX``. Python opens421+ stdout and stderr with ``errors="surrogateescape"``.422+ - None of ``LANG/LC_*`` are set. Python assumes ``LANG=C.UTF-8``.423+ - Python is started in UTF-8 mode with ``PYTHONUTF8=1`` or ``-X utf8``.424+ Python opens stdout and stderr with ``errors="surrogateescape"``.425+426 :param filename: formats a filename for UI display. This will also convert427 the filename into unicode without failing.428 :param shorten: this optionally shortens the filename to strip of the429 path that leads up to it.430 """431 if shorten:432 filename = os.path.basename(filename)433+ else:434+ filename = os.fspath(filename)435 405- return os.fsdecode(filename)436+ if isinstance(filename, bytes):437+ filename = filename.decode(sys.getfilesystemencoding(), "replace")438+ else:439+ filename = filename.encode("utf-8", "surrogateescape").decode(440+ "utf-8", "replace"441+ )442 443+ return filename444 445+446 def get_app_dir(app_name: str, roaming: bool = True, force_posix: bool = False) -> str:447 r"""Returns the config folder for the application. The default behavior448 is to return whatever is most appropriate for the operating system.449 98 unmodified lines548 549 # The value of __package__ indicates how Python was called. It may550 # not exist if a setuptools script is installed as an egg. It may be551 # set incorrectly for entry points created with pip on Windows.552+ # It is set to "" inside a Shiv or PEX zipapp.514- if getattr(_main, "__package__", None) is None or (553+ if getattr(_main, "__package__", None) in {None, ""} or (554 os.name == "nt"555 and _main.__package__ == ""556 and not os.path.exists(path)557 and os.path.exists(f"{path}.exe")67 unmodified linesmodified:tests/conftest.py-19 removed
1-import os2-import tempfile3-1 import pytest2 3 from click.testing import CliRunner4 5 6 @pytest.fixture(scope="function")7 def runner(request):8 return CliRunner()12-13-14-def _check_symlinks_supported():15- with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:16- target = os.path.join(tempdir, "target")17- open(target, "w").close()18- link = os.path.join(tempdir, "link")19-20- try:21- os.symlink(target, link)22- return True23- except OSError:24- return False25-26-27-symlinks_supported = _check_symlinks_supported()modified:tests/test_arguments.py+20 added
379 unmodified lines380 381 result = runner.invoke(cli, ["arg1", "cmd", "arg2", "subcmd", "--help"])382 assert not result.exception383 assert "Usage: cli ARG1 cmd ARG2 subcmd [OPTIONS]" in result.output384+385+386+def test_when_argument_decorator_is_used_multiple_times_cls_is_preserved():387+ class CustomArgument(click.Argument):388+ pass389+390+ reusable_argument = click.argument("art", cls=CustomArgument)391+392+ @click.command()393+ @reusable_argument394+ def foo(arg):395+ pass396+397+ @click.command()398+ @reusable_argument399+ def bar(arg):400+ pass401+402+ assert isinstance(foo.params[0], CustomArgument)403+ assert isinstance(bar.params[0], CustomArgument)modified:tests/test_command_decorators.py+20 added
9 unmodified lines10 assert result.exception is None11 assert result.output == "hello\n"12 13 14+def test_custom_command_no_parens(runner):15+ class CustomCommand(click.Command):16+ pass17+18+ class CustomGroup(click.Group):19+ command_class = CustomCommand20+21+ @click.group(cls=CustomGroup)22+ def grp():23+ pass24+25+ @grp.command26+ def cli():27+ click.echo("hello custom command class")28+29+ result = runner.invoke(cli)30+ assert result.exception is None31+ assert result.output == "hello custom command class\n"32+33+34 def test_group_no_parens(runner):35 @click.group36 def grp():37 click.echo("grp1")34 unmodified linesmodified:tests/test_commands.py+12 added-14 removed
93 unmodified lines94 is not None95 )96 97 98-def test_help_truncation(runner):99- @click.command()100- def cli():101- """This is a command with truncated help.102- \f103-104- This text should be truncated.105- """106-107- result = runner.invoke(cli, ["--help"])108- assert result.exit_code == 0109- assert "This is a command with truncated help." in result.output110-111-98 def test_no_args_is_help(runner):99 @click.command(no_args_is_help=True)100 def cli():101 pass294 unmodified lines396 pass397 398 runner.invoke(group, ["command1"])399 assert opt_prefixes == {"-", "--", "~", "+"}400+401+402+@pytest.mark.parametrize("exc", (EOFError, KeyboardInterrupt))403+def test_abort_exceptions_with_disabled_standalone_mode(runner, exc):404+ @click.command()405+ def cli():406+ raise exc("catch me!")407+408+ rv = runner.invoke(cli, standalone_mode=False)409+ assert rv.exit_code == 1410+ assert isinstance(rv.exception.__cause__, exc)411+ assert rv.exception.__cause__.args == ("catch me!",)modified:tests/test_defaults.py+21 added
36 unmodified lines37 38 result = runner.invoke(cli, [])39 assert not result.exception40 assert result.output.splitlines() == ["<1|2>", "<3|4>"]41+42+43+def test_multiple_flag_default(runner):44+ """Default default for flags when multiple=True should be empty tuple."""45+46+ @click.command47+ # flag due to secondary token48+ @click.option("-y/-n", multiple=True)49+ # flag due to is_flag50+ @click.option("-f", is_flag=True, multiple=True)51+ # flag due to flag_value52+ @click.option("-v", "v", flag_value=1, multiple=True)53+ @click.option("-q", "v", flag_value=-1, multiple=True)54+ def cli(y, f, v):55+ return y, f, v56+57+ result = runner.invoke(cli, standalone_mode=False)58+ assert result.return_value == ((), (), ())59+60+ result = runner.invoke(cli, ["-y", "-n", "-f", "-v", "-q"], standalone_mode=False)61+ assert result.return_value == ((True, False), (True,), (1, -1))modified:tests/test_formatting.py+20 added
294 unmodified lines295 " --help Show this message and exit.",296 ]297 298 299+def test_truncating_docstring_no_help(runner):300+ @click.command()301+ @click.pass_context302+ def cli(ctx):303+ """304+ \f305+306+ This text should be truncated.307+ """308+309+ result = runner.invoke(cli, ["--help"], terminal_width=60)310+ assert not result.exception311+ assert result.output.splitlines() == [312+ "Usage: cli [OPTIONS]",313+ "",314+ "Options:",315+ " --help Show this message and exit.",316+ ]317+318+319 def test_removing_multiline_marker(runner):320 @click.group()321 def cli():322 pass46 unmodified linesmodified:tests/test_options.py-4 removed
909 unmodified lines910 ("kwargs", "message"),911 [912 ({"count": True, "multiple": True}, "'count' is not valid with 'multiple'."),913 ({"count": True, "is_flag": True}, "'count' is not valid with 'is_flag'."),914- (915- {"multiple": True, "is_flag": True},916- "'multiple' is not valid with 'is_flag', use 'count'.",917- ),914 ],915 )916 def test_invalid_flag_combinations(runner, kwargs, message):917 with pytest.raises(TypeError) as e:3 unmodified linesmodified:tests/test_types.py+109 added-5 removed
1 import os.path2 import pathlib3+import tempfile4 5 import pytest5-from conftest import symlinks_supported6 7 import click8+from click import FileError9 10 11 @pytest.mark.parametrize(12 ("type", "value", "expect"),91 unmodified lines104 assert result.exception is None105 assert result.return_value == expect106 107 108+def _symlinks_supported():109+ with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:110+ target = os.path.join(tempdir, "target")111+ open(target, "w").close()112+ link = os.path.join(tempdir, "link")113+114+ try:115+ os.symlink(target, link)116+ return True117+ except OSError:118+ return False119+120+121 @pytest.mark.skipif(108- not symlinks_supported, reason="The current OS or FS doesn't support symlinks."122+ not _symlinks_supported(), reason="The current OS or FS doesn't support symlinks."123 )124 def test_path_resolve_symlink(tmp_path, runner):125 test_file = tmp_path / "file"112- test_file_str = os.fsdecode(test_file)126+ test_file_str = os.fspath(test_file)127 test_file.write_text("")128 129 path_type = click.Path(resolve_path=True)130 param = click.Argument(["a"], type=path_type)3 unmodified lines134 test_dir.mkdir()135 136 abs_link = test_dir / "abs"137 abs_link.symlink_to(test_file)124- abs_rv = path_type.convert(os.fsdecode(abs_link), param, ctx)138+ abs_rv = path_type.convert(os.fspath(abs_link), param, ctx)139 assert abs_rv == test_file_str140 141 rel_link = test_dir / "rel"142 rel_link.symlink_to(pathlib.Path("..") / "file")129- rel_rv = path_type.convert(os.fsdecode(rel_link), param, ctx)143+ rel_rv = path_type.convert(os.fspath(rel_link), param, ctx)144 assert rel_rv == test_file_str145+146+147+def _non_utf8_filenames_supported():148+ with tempfile.TemporaryDirectory(prefix="click-pytest-") as tempdir:149+ try:150+ f = open(os.path.join(tempdir, "\udcff"), "w")151+ except OSError:152+ return False153+154+ f.close()155+ return True156+157+158+@pytest.mark.skipif(159+ not _non_utf8_filenames_supported(),160+ reason="The current OS or FS doesn't support non-UTF-8 filenames.",161+)162+def test_path_surrogates(tmp_path, monkeypatch):163+ monkeypatch.chdir(tmp_path)164+ type = click.Path(exists=True)165+ path = pathlib.Path("\udcff")166+167+ with pytest.raises(click.BadParameter, match="'�' does not exist"):168+ type.convert(path, None, None)169+170+ type = click.Path(file_okay=False)171+ path.touch()172+173+ with pytest.raises(click.BadParameter, match="'�' is a file"):174+ type.convert(path, None, None)175+176+ path.unlink()177+ type = click.Path(dir_okay=False)178+ path.mkdir()179+180+ with pytest.raises(click.BadParameter, match="'�' is a directory"):181+ type.convert(path, None, None)182+183+ path.rmdir()184+185+ def no_access(*args, **kwargs):186+ """Test environments may be running as root, so we have to fake the result of187+ the access tests that use os.access188+ """189+ p = args[0]190+ assert p == path, f"unexpected os.access call on file not under test: {p!r}"191+ return False192+193+ path.touch()194+ type = click.Path(readable=True)195+196+ with pytest.raises(click.BadParameter, match="'�' is not readable"):197+ with monkeypatch.context() as m:198+ m.setattr(os, "access", no_access)199+ type.convert(path, None, None)200+201+ type = click.Path(readable=False, writable=True)202+203+ with pytest.raises(click.BadParameter, match="'�' is not writable"):204+ with monkeypatch.context() as m:205+ m.setattr(os, "access", no_access)206+ type.convert(path, None, None)207+208+ type = click.Path(readable=False, executable=True)209+210+ with pytest.raises(click.BadParameter, match="'�' is not executable"):211+ with monkeypatch.context() as m:212+ m.setattr(os, "access", no_access)213+ type.convert(path, None, None)214+215+ path.unlink()216+217+218+@pytest.mark.parametrize(219+ "type",220+ [221+ click.File(mode="r"),222+ click.File(mode="r", lazy=True),223+ ],224+)225+def test_file_surrogates(type, tmp_path):226+ path = tmp_path / "\udcff"227+228+ with pytest.raises(click.BadParameter, match="�': No such file or directory"):229+ type.convert(path, None, None)230+231+232+def test_file_error_surrogates():233+ message = FileError(filename="\udcff").format_message()234+ assert message == "Could not open file '�': unknown error"modified:tests/test_utils.py+11 added-4 removed
41 unmodified lines42 click.echo("hello", file=f)43 assert f.getvalue() == "hello\n"44 45 46+def test_echo_no_streams(monkeypatch, runner):47+ """echo should not fail when stdout and stderr are None with pythonw on Windows."""48+ with runner.isolation():49+ sys.stdout = None50+ sys.stderr = None51+ click.echo("test")52+ click.echo("test", err=True)53+54+55 @pytest.mark.parametrize(56 ("styles", "ref"),57 [58 ({"fg": "black"}, "\x1b[30mx y\x1b[0m"),47 unmodified lines106 assert click.format_filename(b"foo.txt") == "foo.txt"107 assert click.format_filename(b"/x/foo.txt") == "/x/foo.txt"108 assert click.format_filename("/x/foo.txt") == "/x/foo.txt"109 assert click.format_filename("/x/foo.txt", shorten=True) == "foo.txt"110+ assert click.format_filename(b"/x/\xff.txt", shorten=True) == "�.txt"111 102- # filesystem encoding on windows permits this.103- if not WIN:104- assert click.format_filename(b"/x/foo\xff.txt", shorten=True) == "foo\udcff.txt"112 106-113 def test_prompts(runner):114 @click.command()115 def test():116 if click.confirm("Foo"):334 unmodified lines451 (str(pathlib.Path("/foo/bar/example.py")), None, "example.py"),452 ("example", None, "example"),453 (str(pathlib.Path("example/__main__.py")), "example", "python -m example"),454 (str(pathlib.Path("example/cli.py")), "example", "python -m example.cli"),455+ (str(pathlib.Path("./example")), "", "example"),456 ],457 )458 def test_detect_program_name(path, main, expected):459 assert click.utils._detect_program_name(path, _main=MockMain(main)) == expected48 unmodified linesmodified:.pre-commit-config.yaml+1 added-1 removed
1 unmodified line2 autoupdate_branch: "8.1.x"3 autoupdate_schedule: monthly4 repos:5 - repo: https://github.com/asottile/pyupgrade6- rev: v3.7.06+ rev: v3.8.07 hooks:8 - id: pyupgrade9 args: ["--py37-plus"]10 - repo: https://github.com/asottile/reorder-python-imports21 unmodified linesmodified:CHANGES.rst+26 added-3 removed
11 unmodified lines12 13 Version 8.1.414 -------------15 16-Unreleased16+Released 2023-07-0617 18 - Replace all ``typing.Dict`` occurrences to ``typing.MutableMapping`` for19- parameter hints. :issue:`2255`19+ parameter hints. :issue:`2255`20 - Improve type hinting for decorators and give all generic types parameters.21 :issue:`2398`22-- Fix return value and type signature of `shell_completion.add_completion_class` function. :pr:`2421`22+- Fix return value and type signature of `shell_completion.add_completion_class`23+ function. :pr:`2421`24+- Bash version detection doesn't fail on Windows. :issue:`2461`25+- Completion works if there is a dot (``.``) in the program name. :issue:`2166`26+- Improve type annotations for pyright type checker. :issue:`2268`27+- Improve responsiveness of ``click.clear()``. :issue:`2284`28+- Improve command name detection when using Shiv or PEX. :issue:`2332`29+- Avoid showing empty lines if command help text is empty. :issue:`2368`30+- ZSH completion script works when loaded from ``fpath``. :issue:`2344`.31+- ``EOFError`` and ``KeyboardInterrupt`` tracebacks are not suppressed when32+ ``standalone_mode`` is disabled. :issue:`2380`33+- ``@group.command`` does not fail if the group was created with a custom34+ ``command_class``. :issue:`2416`35+- ``multiple=True`` is allowed for flag options again and does not require36+ setting ``default=()``. :issue:`2246, 2292, 2295`37+- Make the decorators returned by ``@argument()`` and ``@option()`` reusable when the38+ ``cls`` parameter is used. :issue:`2294`39+- Don't fail when writing filenames to streams with strict errors. Replace invalid40+ bytes with the replacement character (``�``). :issue:`2395`41+- Remove unnecessary attempt to detect MSYS2 environment. :issue:`2355`42+- Remove outdated and unnecessary detection of App Engine environment. :pr:`2554`43+- ``echo()`` does not fail when no streams are attached, such as with ``pythonw`` on44+ Windows. :issue:`2415`45+- Argument with ``expose_value=False`` do not cause completion to fail. :issue:`2336`46 47 48 Version 8.1.349 -------------1040 unmodified lines