Skip to content
Myr

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

7 files+160 added−88 removed

modified:src/click/__init__.py+11 added-1 removed
32 unmodified lines
33from .exceptions import UsageError as UsageError34from .formatting import HelpFormatter as HelpFormatter35from .formatting import wrap_text as wrap_text36from .globals import get_current_context as get_current_context37from .parser import OptionParser as OptionParser37from .termui import clear as clear38from .termui import confirm as confirm39from .termui import echo_via_pager as echo_via_pager40from .termui import edit as edit
53 unmodified lines
94 stacklevel=2,95 )96 return _MultiCommand9798 if name == "OptionParser":99 from .parser import _OptionParser100101 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 _OptionParser108109 raise AttributeError(name)
modified:src/click/core.py+34 added-18 removed
23 unmodified lines
24from .formatting import join_options25from .globals import pop_context26from .globals import push_context27from .parser import _flag_needs_value28from .parser import OptionParser29from .parser import split_opt28from .parser import _OptionParser29from .parser import _split_opt30from .termui import confirm31from .termui import prompt32from .termui import style33from .utils import _detect_program_name
189 unmodified lines
223 value is not set, it defaults to the value from the parent224 context. ``Command.show_default`` overrides this default for the225 specific command.226227 .. versionchanged:: 8.2228 The ``protected_args`` attribute is deprecated and will be removed in229 Click 9.0. ``args`` will contain remaining unparsed tokens.230231 .. versionchanged:: 8.1232 The ``show_default`` parameter is overridden by233 ``Command.show_default``, instead of the other way around.234
55 unmodified lines
290 #: 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()297298 if obj is None and parent is not None:
129 unmodified lines
428 self._depth = 0429 self._parameter_source: t.Dict[str, ParameterSource] = {}430 self._exit_stack = ExitStack()431432 @property433 def protected_args(self) -> t.List[str]:434 import warnings435436 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_args443444 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 lines
1024 callback=show_help,1025 help=_("Show this message and exit."),1026 )10271012 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 lines
1227 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 )12331234 return results1235
517 unmodified lines
17531754 rest = super().parse_args(ctx, args)17551756 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:]17611762 return ctx.args17631764 def invoke(self, ctx: Context) -> t.Any:
1 unmodified line
1766 if self._result_callback is not None:1767 value = ctx.invoke(self._result_callback, value, **ctx.params)1768 return value17691754 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 lines
1777 return _process_result([] if self.chain else rv)1778 ctx.fail(_("Missing command."))17791780 # 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 = []17841785 # 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 lines
1850 # 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 lines
2208 value = value()22092210 return value22112196 def add_to_parser(self, parser: OptionParser, ctx: Context) -> None:2212 def add_to_parser(self, parser: _OptionParser, ctx: Context) -> None:2213 raise NotImplementedError()22142215 def consume_value(2216 self, ctx: Context, opts: t.Mapping[str, t.Any]
380 unmodified lines
2597 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 lines
2608 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)26142615 if name is None and possible_names:2616 possible_names.sort(key=lambda x: -len(x[0])) # group long options first
14 unmodified lines
2631 )26322633 return name, opts, secondary_opts26342619 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 lines
2748 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 lines
29772978 def get_error_hint(self, ctx: Context) -> str:2979 return f"'{self.make_metavar()}'"29802965 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)298329842985def __getattr__(name: str) -> object:
21 unmodified lines
modified:src/click/formatting.py+2 added-2 removed
1 unmodified line
2from contextlib import contextmanager3from gettext import gettext as _45from ._compat import term_len6from .parser import split_opt6from .parser import _split_opt78# Can force a width. This is used by the test system9FORCED_WIDTH: t.Optional[int] = None10
278 unmodified lines
289 rv = []290 any_prefix_is_slash = False291292 for opt in options:293 prefix = split_opt(opt)[0]293 prefix = _split_opt(opt)[0]294295 if prefix == "/":296 any_prefix_is_slash = True297
4 unmodified lines
modified:src/click/parser.py+59 added-59 removed
104 unmodified lines
105106 return tuple(rv), list(args)107108109def split_opt(opt: str) -> t.Tuple[str, str]:109def _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:]116117118def normalize_opt(opt: str, ctx: t.Optional["Context"]) -> str:118def _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)}"123124125def 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.129130 .. code-block:: python131132 split_arg_string("example 'my file")133 ["example", "my file"]134135 split_arg_string("example my\\")136 ["example", "my"]137138 :param string: String to split.139 """140 import shlex141142 lex = shlex.shlex(string, posix=True)143 lex.whitespace_split = True144 lex.commenters = ""145 out = []146147 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)155156 return out157158159class Option:125class _Option:126 def __init__(127 self,128 obj: "CoreOption",129 opts: t.Sequence[str],
6 unmodified lines
136 self._long_opts = []137 self.prefixes: t.Set[str] = set()138139 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 lines
159 @property160 def takes_value(self) -> bool:161 return self.action in ("store", "append")162197 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: ignore
7 unmodified lines
175 raise ValueError(f"unknown action '{self.action}'")176 state.order.append(self.obj)177178213class Argument:179class _Argument:180 def __init__(self, obj: "CoreArgument", dest: t.Optional[str], nargs: int = 1):181 self.dest = dest182 self.nargs = nargs183 self.obj = obj184185 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 lines
207 state.opts[self.dest] = value # type: ignore208 state.order.append(self.obj)209210245class ParsingState:211class _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"] = []217218253class OptionParser:219class _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 lines
227 types or defaults).228229 :param ctx: optionally the :class:`~click.Context` where this parser230 should go with.231232 .. deprecated:: 8.2233 Will be removed in Click 9.0.234 """235236 def __init__(self, ctx: t.Optional["Context"] = None) -> None:237 #: The :class:`~click.Context` for this parser. This might be
13 unmodified lines
251 if ctx is not None:252 self.allow_interspersed_args = ctx.allow_interspersed_args253 self.ignore_unknown_options = ctx.ignore_unknown_options254286 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] = []259260 def add_option(261 self,262 obj: "CoreOption",
10 unmodified lines
273274 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 lines
289290 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))294295 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 lines
300 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.order312344 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 lines
320321 state.largs = args322 state.rargs = []323355 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 what
28 unmodified lines
357 # *empty* -- still a subset of [arg0, ..., arg(i-1)], but358 # not a very interesting subset!359360 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 lines
386 value = None387388 option.process(value, state)389421 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 = []395396 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 += 1400401 if not option:
25 unmodified lines
427 if self.ignore_unknown_options and unknown_options:428 state.largs.append(f"{prefix}{''.join(unknown_options)}")429430 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.nargs434435 if len(state.rargs) < nargs:
28 unmodified lines
464 del state.rargs[:nargs]465466 return value467499 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)478479 # 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 lines
495 if not self.ignore_unknown_options:496 raise497498 state.largs.append(arg)499500501def __getattr__(name: str) -> object:502 import warnings503504 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}"]517518 if name == "split_arg_string":519 from .shell_completion import split_arg_string520521 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_string528529 raise AttributeError(name)
modified:src/click/shell_completion.py+40 added-4 removed
8 unmodified lines
9from .core import Group10from .core import Option11from .core import Parameter12from .core import ParameterSource13from .parser import split_arg_string13from .utils import echo141516def shell_complete(
415 unmodified lines
432 """433 return _available_shells.get(shell)434435436def 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.440441 .. code-block:: python442443 split_arg_string("example 'my file")444 ["example", "my file"]445446 split_arg_string("example my\\")447 ["example", "my"]448449 :param string: String to split.450451 .. versionchanged:: 8.2452 Moved to ``shell_completion`` from ``parser``.453 """454 import shlex455456 lex = shlex.shlex(string, posix=True)457 lex.whitespace_split = True458 lex.commenters = ""459 out = []460461 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)469470 return out471472473def _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 lines
543 :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.args548549 while args:550 command = ctx.command551
4 unmodified lines
556 if cmd is None:557 return ctx558559 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 = ctx563564 while args:
12 unmodified lines
577 )578 args = sub_ctx.args579580 ctx = sub_ctx545 args = [*sub_ctx.protected_args, *sub_ctx.args]581 args = [*sub_ctx._protected_args, *sub_ctx.args]582 else:583 break584585 return ctx
47 unmodified lines
modified:tests/test_parser.py+4 added-4 removed
1import pytest23import click4from click.parser import OptionParser5from click.parser import split_arg_string4from click.parser import _OptionParser5from click.shell_completion import split_arg_string678@pytest.mark.parametrize(9 ("value", "expect"),
9 unmodified lines
19 assert split_arg_string(value) == expect202122def test_parser_default_prefixes():23 parser = OptionParser()23 parser = _OptionParser()24 assert parser._opt_prefixes == {"-", "--"}252627def 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 lines
12- ``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`1819 - ``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``.262728Version 8.1.729-------------3031Released 2023-08-17
1100 unmodified lines