deprecate `OptionParser` (#2592)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents edcd2dc, 3630add · Browse files · 7 files·+160 added−88 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+160 added−88 removed
- tests:+4 added−4 removed
- other:+156 added−84 removed
Provenance
- Commit
988c683- Tree
101f7b7- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
edcd2dc- Parent 2
3630add
7 files changed+160 added−88 removed
modified:src/click/__init__.py+11 added-1 removed
32 unmodified lines33 from .exceptions import UsageError as UsageError34 from .formatting import HelpFormatter as HelpFormatter35 from .formatting import wrap_text as wrap_text36 from .globals import get_current_context as get_current_context37-from .parser import OptionParser as OptionParser37 from .termui import clear as clear38 from .termui import confirm as confirm39 from .termui import echo_via_pager as echo_via_pager40 from .termui import edit as edit53 unmodified lines94 stacklevel=2,95 )96 return _MultiCommand97 98+ if name == "OptionParser":99+ from .parser import _OptionParser100+101+ warnings.warn(102+ "'OptionParser' is deprecated and will be removed in Click 9.0. The"103+ " old parser is available in 'optparse'.",104+ DeprecationWarning,105+ stacklevel=2,106+ )107+ return _OptionParser108+109 raise AttributeError(name)modified:src/click/core.py+34 added-18 removed
23 unmodified lines24 from .formatting import join_options25 from .globals import pop_context26 from .globals import push_context27 from .parser import _flag_needs_value28-from .parser import OptionParser29-from .parser import split_opt28+from .parser import _OptionParser29+from .parser import _split_opt30 from .termui import confirm31 from .termui import prompt32 from .termui import style33 from .utils import _detect_program_name189 unmodified lines223 value is not set, it defaults to the value from the parent224 context. ``Command.show_default`` overrides this default for the225 specific command.226 227+ .. versionchanged:: 8.2228+ The ``protected_args`` attribute is deprecated and will be removed in229+ Click 9.0. ``args`` will contain remaining unparsed tokens.230+231 .. versionchanged:: 8.1232 The ``show_default`` parameter is overridden by233 ``Command.show_default``, instead of the other way around.234 55 unmodified lines290 #: protected arguments. These are arguments that are prepended291 #: to `args` when certain parsing scenarios are encountered but292 #: must be never propagated to another arguments. This is used293 #: to implement nested parsing.290- self.protected_args: t.List[str] = []294+ self._protected_args: t.List[str] = []295 #: the collected prefixes of the command's options.296 self._opt_prefixes: t.Set[str] = set(parent._opt_prefixes) if parent else set()297 298 if obj is None and parent is not None:129 unmodified lines428 self._depth = 0429 self._parameter_source: t.Dict[str, ParameterSource] = {}430 self._exit_stack = ExitStack()431 432+ @property433+ def protected_args(self) -> t.List[str]:434+ import warnings435+436+ warnings.warn(437+ "'protected_args' is deprecated and will be removed in Click 9.0."438+ " 'args' will contain remaining unparsed tokens.",439+ DeprecationWarning,440+ stacklevel=2,441+ )442+ return self._protected_args443+444 def to_info_dict(self) -> t.Dict[str, t.Any]:445 """Gather information that could be useful for a tool generating446 user-facing documentation. This traverses the entire CLI447 structure.576 unmodified lines1024 callback=show_help,1025 help=_("Show this message and exit."),1026 )1027 1012- def make_parser(self, ctx: Context) -> OptionParser:1028+ def make_parser(self, ctx: Context) -> _OptionParser:1029 """Creates the underlying option parser for this command."""1014- parser = OptionParser(ctx)1030+ parser = _OptionParser(ctx)1031 for param in self.get_params(ctx):1032 param.add_to_parser(parser, ctx)1033 return parser1034 192 unmodified lines1227 if isinstance(ctx.command, Group) and ctx.command.chain:1228 results.extend(1229 CompletionItem(name, help=command.get_short_help_str())1230 for name, command in _complete_visible_commands(ctx, incomplete)1215- if name not in ctx.protected_args1231+ if name not in ctx._protected_args1232 )1233 1234 return results1235 517 unmodified lines1753 1754 rest = super().parse_args(ctx, args)1755 1756 if self.chain:1741- ctx.protected_args = rest1757+ ctx._protected_args = rest1758 ctx.args = []1759 elif rest:1744- ctx.protected_args, ctx.args = rest[:1], rest[1:]1760+ ctx._protected_args, ctx.args = rest[:1], rest[1:]1761 1762 return ctx.args1763 1764 def invoke(self, ctx: Context) -> t.Any:1 unmodified line1766 if self._result_callback is not None:1767 value = ctx.invoke(self._result_callback, value, **ctx.params)1768 return value1769 1754- if not ctx.protected_args:1770+ if not ctx._protected_args:1771 if self.invoke_without_command:1772 # No subcommand was invoked, so the result callback is1773 # invoked with the group return value for regular1774 # groups, or an empty list for chained groups.2 unmodified lines1777 return _process_result([] if self.chain else rv)1778 ctx.fail(_("Missing command."))1779 1780 # Fetch args back out1765- args = [*ctx.protected_args, *ctx.args]1781+ args = [*ctx._protected_args, *ctx.args]1782 ctx.args = []1767- ctx.protected_args = []1783+ ctx._protected_args = []1784 1785 # If we're not in chain mode, we only allow the invocation of a1786 # single command but we also inform the current context about the1787 # name of the command to invoke.62 unmodified lines1850 # an option we want to kick off parsing again for arguments to1851 # resolve things like --help which now should go to the main1852 # place.1853 if cmd is None and not ctx.resilient_parsing:1838- if split_opt(cmd_name)[0]:1854+ if _split_opt(cmd_name)[0]:1855 self.parse_args(ctx, ctx.args)1856 ctx.fail(_("No such command {name!r}.").format(name=original_cmd_name))1857 return cmd_name if cmd else None, cmd, args[1:]1858 349 unmodified lines2208 value = value()2209 2210 return value2211 2196- def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2212+ def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:2213 raise NotImplementedError()2214 2215 def consume_value(2216 self, ctx: Context, opts: t.Mapping[str, t.Any]380 unmodified lines2597 if split_char in decl:2598 first, second = decl.split(split_char, 1)2599 first = first.rstrip()2600 if first:2585- possible_names.append(split_opt(first))2601+ possible_names.append(_split_opt(first))2602 opts.append(first)2603 second = second.lstrip()2604 if second:2605 secondary_opts.append(second.lstrip())2 unmodified lines2608 f"Boolean option {decl!r} cannot use the"2609 " same flag for true/false."2610 )2611 else:2596- possible_names.append(split_opt(decl))2612+ possible_names.append(_split_opt(decl))2613 opts.append(decl)2614 2615 if name is None and possible_names:2616 possible_names.sort(key=lambda x: -len(x[0])) # group long options first14 unmodified lines2631 )2632 2633 return name, opts, secondary_opts2634 2619- def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2635+ def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:2636 if self.multiple:2637 action = "append"2638 elif self.count:2639 action = "count"108 unmodified lines2748 default_string = _("(dynamic)")2749 elif self.is_bool_flag and self.secondary_opts:2750 # For boolean flags that have distinct True/False opts,2751 # use the opt without prefix instead of the value.2736- default_string = split_opt(2752+ default_string = _split_opt(2753 (self.opts if self.default else self.secondary_opts)[0]2754 )[1]2755 elif self.is_bool_flag and not self.secondary_opts and not default_value:2756 default_string = ""220 unmodified lines2977 2978 def get_error_hint(self, ctx: Context) -> str:2979 return f"'{self.make_metavar()}'"2980 2965- def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2981+ def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:2982 parser.add_argument(dest=self.name, nargs=self.nargs, obj=self)2983 2984 2985 def __getattr__(name: str) -> object:21 unmodified linesmodified:src/click/formatting.py+2 added-2 removed
1 unmodified line2 from contextlib import contextmanager3 from gettext import gettext as _4 5 from ._compat import term_len6-from .parser import split_opt6+from .parser import _split_opt7 8 # Can force a width. This is used by the test system9 FORCED_WIDTH: t.Optional[int] = None10 278 unmodified lines289 rv = []290 any_prefix_is_slash = False291 292 for opt in options:293- prefix = split_opt(opt)[0]293+ prefix = _split_opt(opt)[0]294 295 if prefix == "/":296 any_prefix_is_slash = True297 4 unmodified linesmodified:src/click/parser.py+59 added-59 removed
104 unmodified lines105 106 return tuple(rv), list(args)107 108 109-def split_opt(opt: str) -> t.Tuple[str, str]:109+def _split_opt(opt: str) -> t.Tuple[str, str]:110 first = opt[:1]111 if first.isalnum():112 return "", opt113 if opt[1:2] == first:114 return opt[:2], opt[2:]115 return first, opt[1:]116 117 118-def normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str:118+def _normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str:119 if ctx is None or ctx.token_normalize_func is None:120 return opt121- prefix, opt = split_opt(opt)121+ prefix, opt = _split_opt(opt)122 return f"{prefix}{ctx.token_normalize_func(opt)}"123 124 125-def split_arg_string(string: str) -> t.List[str]:126- """Split an argument string as with :func:`shlex.split`, but don't127- fail if the string is incomplete. Ignores a missing closing quote or128- incomplete escape sequence and uses the partial token as-is.129-130- .. code-block:: python131-132- split_arg_string("example 'my file")133- ["example", "my file"]134-135- split_arg_string("example my\\")136- ["example", "my"]137-138- :param string: String to split.139- """140- import shlex141-142- lex = shlex.shlex(string, posix=True)143- lex.whitespace_split = True144- lex.commenters = ""145- out = []146-147- try:148- for token in lex:149- out.append(token)150- except ValueError:151- # Raised when end-of-string is reached in an invalid state. Use152- # the partial token as-is. The quote or escape character is in153- # lex.state, not lex.token.154- out.append(lex.token)155-156- return out157-158-159-class Option:125+class _Option:126 def __init__(127 self,128 obj: "CoreOption",129 opts: t.Sequence[str],6 unmodified lines136 self._long_opts = []137 self.prefixes: t.Set[str] = set()138 139 for opt in opts:174- prefix, value = split_opt(opt)140+ prefix, value = _split_opt(opt)141 if not prefix:142 raise ValueError(f"Invalid start character for option ({opt})")143 self.prefixes.add(prefix[0])144 if len(prefix) == 1 and len(value) == 1:14 unmodified lines159 @property160 def takes_value(self) -> bool:161 return self.action in ("store", "append")162 197- def process(self, value: t.Any, state: "ParsingState") -> None:163+ def process(self, value: t.Any, state: "_ParsingState") -> None:164 if self.action == "store":165 state.opts[self.dest] = value # type: ignore166 elif self.action == "store_const":167 state.opts[self.dest] = self.const # type: ignore7 unmodified lines175 raise ValueError(f"unknown action '{self.action}'")176 state.order.append(self.obj)177 178 213-class Argument:179+class _Argument:180 def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1):181 self.dest = dest182 self.nargs = nargs183 self.obj = obj184 185 def process(186 self,187 value: t.Union[t.Optional[str], t.Sequence[t.Optional[str]]],222- state: "ParsingState",188+ state: "_ParsingState",189 ) -> None:190 if self.nargs > 1:191 assert value is not None192 holes = sum(1 for x in value if x is None)14 unmodified lines207 state.opts[self.dest] = value # type: ignore208 state.order.append(self.obj)209 210 245-class ParsingState:211+class _ParsingState:212 def __init__(self, rargs: t.List[str]) -> None:213 self.opts: t.Dict[str, t.Any] = {}214 self.largs: t.List[str] = []215 self.rargs = rargs216 self.order: t.List["CoreParameter"] = []217 218 253-class OptionParser:219+class _OptionParser:220 """The option parser is an internal class that is ultimately used to221 parse options and arguments. It's modelled after optparse and brings222 a similar but vastly simplified API. It should generally not be used223 directly as the high level Click classes wrap it for you.3 unmodified lines227 types or defaults).228 229 :param ctx: optionally the :class:`~click.Context` where this parser230 should go with.231+232+ .. deprecated:: 8.2233+ Will be removed in Click 9.0.234 """235 236 def __init__(self, ctx: t.Optional["Context"] = None) -> None:237 #: The :class:`~click.Context` for this parser. This might be13 unmodified lines251 if ctx is not None:252 self.allow_interspersed_args = ctx.allow_interspersed_args253 self.ignore_unknown_options = ctx.ignore_unknown_options254 286- self._short_opt: t.Dict[str, Option] = {}287- self._long_opt: t.Dict[str, Option] = {}255+ self._short_opt: t.Dict[str, _Option] = {}256+ self._long_opt: t.Dict[str, _Option] = {}257 self._opt_prefixes = {"-", "--"}289- self._args: t.List[Argument] = []258+ self._args: t.List[_Argument] = []259 260 def add_option(261 self,262 obj: "CoreOption",10 unmodified lines273 274 The `obj` can be used to identify the option in the order list275 that is returned from the parser.276 """308- opts = [normalize_opt(opt, self.ctx) for opt in opts]309- option = Option(obj, opts, dest, action=action, nargs=nargs, const=const)277+ opts = [_normalize_opt(opt, self.ctx) for opt in opts]278+ option = _Option(obj, opts, dest, action=action, nargs=nargs, const=const)279 self._opt_prefixes.update(option.prefixes)280 for opt in option._short_opts:281 self._short_opt[opt] = option282 for opt in option._long_opts:6 unmodified lines289 290 The `obj` can be used to identify the option in the order list291 that is returned from the parser.292 """324- self._args.append(Argument(obj, dest=dest, nargs=nargs))293+ self._args.append(_Argument(obj, dest=dest, nargs=nargs))294 295 def parse_args(296 self, args: t.List[str]297 ) -> t.Tuple[t.Dict[str, t.Any], t.List[str], t.List["CoreParameter"]]:2 unmodified lines300 arguments if there are any. The order is a list of objects as they301 appear on the command line. If arguments appear multiple times they302 will be memorized multiple times as well.303 """335- state = ParsingState(args)304+ state = _ParsingState(args)305 try:306 self._process_args_for_options(state)307 self._process_args_for_args(state)308 except UsageError:309 if self.ctx is None or not self.ctx.resilient_parsing:310 raise311 return state.opts, state.largs, state.order312 344- def _process_args_for_args(self, state: ParsingState) -> None:313+ def _process_args_for_args(self, state: _ParsingState) -> None:314 pargs, args = _unpack_args(315 state.largs + state.rargs, [x.nargs for x in self._args]316 )317 2 unmodified lines320 321 state.largs = args322 state.rargs = []323 355- def _process_args_for_options(self, state: ParsingState) -> None:324+ def _process_args_for_options(self, state: _ParsingState) -> None:325 while state.rargs:326 arg = state.rargs.pop(0)327 arglen = len(arg)328 # Double dashes always handled explicitly regardless of what28 unmodified lines357 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but358 # not a very interesting subset!359 360 def _match_long_opt(392- self, opt: str, explicit_value: t.Optional[str], state: ParsingState361+ self, opt: str, explicit_value: t.Optional[str], state: _ParsingState362 ) -> None:363 if opt not in self._long_opt:364 from difflib import get_close_matches365 20 unmodified lines386 value = None387 388 option.process(value, state)389 421- def _match_short_opt(self, arg: str, state: ParsingState) -> None:390+ def _match_short_opt(self, arg: str, state: _ParsingState) -> None:391 stop = False392 i = 1393 prefix = arg[0]394 unknown_options = []395 396 for ch in arg[1:]:428- opt = normalize_opt(f"{prefix}{ch}", self.ctx)397+ opt = _normalize_opt(f"{prefix}{ch}", self.ctx)398 option = self._short_opt.get(opt)399 i += 1400 401 if not option:25 unmodified lines427 if self.ignore_unknown_options and unknown_options:428 state.largs.append(f"{prefix}{''.join(unknown_options)}")429 430 def _get_value_from_state(462- self, option_name: str, option: Option, state: ParsingState431+ self, option_name: str, option: _Option, state: _ParsingState432 ) -> t.Any:433 nargs = option.nargs434 435 if len(state.rargs) < nargs:28 unmodified lines464 del state.rargs[:nargs]465 466 return value467 499- def _process_opts(self, arg: str, state: ParsingState) -> None:468+ def _process_opts(self, arg: str, state: _ParsingState) -> None:469 explicit_value = None470 # Long option handling happens in two parts. The first part is471 # supporting explicitly attached values. In any case, we will try472 # to long match the option first.473 if "=" in arg:474 long_opt, explicit_value = arg.split("=", 1)475 else:476 long_opt = arg508- norm_long_opt = normalize_opt(long_opt, self.ctx)477+ norm_long_opt = _normalize_opt(long_opt, self.ctx)478 479 # At this point we will match the (assumed) long option through480 # the long option matching code. Note that this allows options481 # like "-foo" to be matched as long options.13 unmodified lines495 if not self.ignore_unknown_options:496 raise497 498 state.largs.append(arg)499+500+501+def __getattr__(name: str) -> object:502+ import warnings503+504+ if name in {505+ "OptionParser",506+ "Argument",507+ "Option",508+ "split_opt",509+ "normalize_opt",510+ "ParsingState",511+ }:512+ warnings.warn(513+ f"'parser.{name}' is deprecated and will be removed in Click 9.0."514+ " The old parser is available in 'optparse'."515+ )516+ return globals()[f"_{name}"]517+518+ if name == "split_arg_string":519+ from .shell_completion import split_arg_string520+521+ warnings.warn(522+ "Importing 'parser.split_arg_string' is deprecated, it will only be"523+ " available in 'shell_completion' in Click 9.0.",524+ DeprecationWarning,525+ stacklevel=2,526+ )527+ return split_arg_string528+529+ raise AttributeError(name)modified:src/click/shell_completion.py+40 added-4 removed
8 unmodified lines9 from .core import Group10 from .core import Option11 from .core import Parameter12 from .core import ParameterSource13-from .parser import split_arg_string13 from .utils import echo14 15 16 def shell_complete(415 unmodified lines432 """433 return _available_shells.get(shell)434 435 436+def split_arg_string(string: str) -> t.List[str]:437+ """Split an argument string as with :func:`shlex.split`, but don't438+ fail if the string is incomplete. Ignores a missing closing quote or439+ incomplete escape sequence and uses the partial token as-is.440+441+ .. code-block:: python442+443+ split_arg_string("example 'my file")444+ ["example", "my file"]445+446+ split_arg_string("example my\\")447+ ["example", "my"]448+449+ :param string: String to split.450+451+ .. versionchanged:: 8.2452+ Moved to ``shell_completion`` from ``parser``.453+ """454+ import shlex455+456+ lex = shlex.shlex(string, posix=True)457+ lex.whitespace_split = True458+ lex.commenters = ""459+ out = []460+461+ try:462+ for token in lex:463+ out.append(token)464+ except ValueError:465+ # Raised when end-of-string is reached in an invalid state. Use466+ # the partial token as-is. The quote or escape character is in467+ # lex.state, not lex.token.468+ out.append(lex.token)469+470+ return out471+472+473 def _is_incomplete_argument(ctx: Context, param: Parameter) -> bool:474 """Determine if the given parameter is an argument that can still475 accept values.476 66 unmodified lines543 :param args: List of complete args before the incomplete value.544 """545 ctx_args["resilient_parsing"] = True546 ctx = cli.make_context(prog_name, args.copy(), **ctx_args)511- args = ctx.protected_args + ctx.args547+ args = ctx._protected_args + ctx.args548 549 while args:550 command = ctx.command551 4 unmodified lines556 if cmd is None:557 return ctx558 559 ctx = cmd.make_context(name, args, parent=ctx, resilient_parsing=True)524- args = ctx.protected_args + ctx.args560+ args = ctx._protected_args + ctx.args561 else:562 sub_ctx = ctx563 564 while args:12 unmodified lines577 )578 args = sub_ctx.args579 580 ctx = sub_ctx545- args = [*sub_ctx.protected_args, *sub_ctx.args]581+ args = [*sub_ctx._protected_args, *sub_ctx.args]582 else:583 break584 585 return ctx47 unmodified linesmodified:tests/test_parser.py+4 added-4 removed
1 import pytest2 3 import click4-from click.parser import OptionParser5-from click.parser import split_arg_string4+from click.parser import _OptionParser5+from click.shell_completion import split_arg_string6 7 8 @pytest.mark.parametrize(9 ("value", "expect"),9 unmodified lines19 assert split_arg_string(value) == expect20 21 22 def test_parser_default_prefixes():23- parser = OptionParser()23+ parser = _OptionParser()24 assert parser._opt_prefixes == {"-", "--"}25 26 27 def test_parser_collects_prefixes():28 ctx = click.Context(click.Command("test"))29- parser = OptionParser(ctx)29+ parser = _OptionParser(ctx)30 click.Option("+p", is_flag=True).add_to_parser(parser, ctx)31 click.Option("!e", is_flag=True).add_to_parser(parser, ctx)32 assert parser._opt_prefixes == {"-", "--", "+", "!"}modified:CHANGES.rst+10 added
11 unmodified lines12 - ``BaseCommand`` is deprecated. ``Command`` is the base class for all13 commands. :issue:`2589`14 - ``MultiCommand`` is deprecated. ``Group`` is the base class for all group15 commands. :issue:`2590`16+- The current parser and related classes and methods, are deprecated.17+ :issue:`2205`18 19+ - ``OptionParser`` and the ``parser`` module, which is a modified copy of20+ ``optparse`` in the standard library.21+ - ``Context.protected_args`` is unneeded. ``Context.args`` contains any22+ remaining arguments while parsing.23+ - ``Parameter.add_to_parser`` (on both ``Argument`` and ``Option``) is24+ unneeded. Parsing works directly without building a separate parser.25+ - ``split_arg_string`` is moved from ``parser`` to ``shell_completion``.26 27+28 Version 8.1.729 -------------30 31 Released 2023-08-171100 unmodified lines